【问题标题】:How to pass a single value from List Item with multiple TextViews when it's fetched from Json?从Json获取时如何从具有多个TextViews的List Item传递单个值?
【发布时间】:2017-10-13 19:39:05
【问题描述】:

我已将 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 .

【问题讨论】:

    标签: android json listview listitem


    【解决方案1】:

    当您创建 ListAdapter 时,您使用 contactList 填充它,这是 Map 中的 List
    问题出在这一行

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

    在这里,您使用getItem(position) 获取该项目。这将返回来自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() 获取更多值并将它们全部放入意图中。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        传递列表的一种好方法是将它们捆绑在一起使用意图传递它

        关于通过活动

        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)
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多