当从 Json 获取时,如何从具有多个 TextView 的列表项传递单个值?

How to pass a single value from List Item with multiple TextViews when it's fetched from Json?

我已经从 Json 文件中提取值到 ListView 中,列表视图中的每个项目都包含许多 TextView(并且它们的值分配给 Json 文件),我希望传递单独的值单个 ListItem 中存在的所有 TextViews 到另一个 activity 。让我知道该怎么做。

谢谢

这是代码,当我传递一个值时,它不是传递单个字符串,而是传递所有字符串,并在第二个屏幕上以 json 形式显示它们。 :

 import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class Other extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;


    // URL to get contacts JSON
    private static String url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxx";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();

   lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

           String value = lv.getAdapter().getItem(position).toString();



           String author = value.concat(String.valueOf(R.id.author));
           // Launching new Activity on selecting single List Item
           Intent i = new Intent(getApplicationContext(), Display.class);
           // sending data to new activity
           i.putExtra("author",author );
           startActivity(i);

       }
       }
   );


    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(Other.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("articles");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                         JSONObject c = contacts.getJSONObject(i);

                        String auth = c.getString("author");
                        String title = c.getString("title");
                        String des = c.getString("description");
                        String ur = c.getString("url");
                        String img = c.getString("urlToImage");
                        String dat = c.getString("publishedAt");


                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("author", auth);
                        contact.put("title", title);
                        contact.put("description", des);
                        contact.put("url", ur);
                        contact.put("urlToImage", img);
                        contact.put("publishedAt", dat);





                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    Other.this, contactList,
                    R.layout.list_item, new String[]{"author",
                    "title" , "urlToImage" , "url" , "publishedAt"}, new int[]{R.id.author, R.id.title , R.id.urlToImage , R.id.url , R.id.date});

            lv.setAdapter(adapter);
 }


    }
}

这是我 运行 时出现的内容 :

Screenshot of what happens after clicking a list item .

您绝对可以使用 Intent 对象传递多个值。将其视为键值对的集合。

您可以添加更多类似于 i.putExtra(“author”, author) 的值。

传递列表的一个好方法是使用 intent

将它们捆绑传递

通过时 Activity

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

收到时Activity

Bundle extras = getIntent().getExtras();
String value = extras.getString(key)

这样您就可以捆绑所有数据。我的建议是 为您的数据建模并尝试通过 bundle intent 发送您的对象

创建 ListAdapter 时,用 contactList 填充它,它是 MapList
问题出在这一行

String value = lv.getAdapter().getItem(position).toString();

在这里,您使用 getItem(position) 获得物品。这将 return 为您提供来自 contactList 的单个元素,即 Map。但是你在上面调用 toString,这会将 Map 转换为你不想要的 String

相反,将您的项目转换为 Map
在您的情况下,执行此操作。

HashMap<String, String> value = (HashMap) lv.getAdapter().getItem(position);

现在您可以使用

获取单个值
String author = value.get("author");

让它们符合您的意图

i.putExtra("author", author);

同样,如果需要,从 value.get() 中获取更多值并将它们全部放入意图中。