当从Json中获取多个TextView时,如何从List Item传递单个值?

时间:2017-10-13 19:39:05

标签: android json listview listitem

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

由于

这是代码,当我传递一个值,然后传递一个字符串而不是传递所有字符串并在第二个屏幕上以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 .

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

传递列表的一个好方法是捆绑它们使用意图传递它

传递活动

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

关于接收活动

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

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

答案 2 :(得分:0)

创建ListAdapter时,请使用contactList填充ListMap。{ 问题出在这一行

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

在这里,您使用getItem(position)获取该项目。这将返回contactListMap的单个元素,该元素为toString。但是您正在调用Map,这会将String转换为您不想要的Map

相反,将您投放到HashMap<String, String> value = (HashMap) lv.getAdapter().getItem(position); 在你的情况下,这样做。

String author = value.get("author");

现在您可以使用

获取单个值
i.putExtra("author", author);

将它们置于你的意图

value.get()

同样,如果您愿意,可以从idx = np.arange(len(df)).repeat(df.desc.str.len(), 0) out = df.iloc[idx, ].assign(desc=np.concatenate(df.desc.values)) out Out[100]: desc id info 0 a 2 type 0 b 2 type 0 c 2 type 1 u 18 tail 1 v 18 tail 1 w 18 tail 获取更多值,并将所有值置于意图中。