【问题标题】:How to retrieve values from ListView with JSON values on new activity?如何使用新活动的 JSON 值从 ListView 中检索值?
【发布时间】:2016-05-03 17:18:50
【问题描述】:

下面的代码可以正常工作。它使用来自 JSON 响应的值填充列表,并在选择任何项目时打开一个新活动,并显示项目的编号。

我的问题是如何让所选项目使用该项目的特定信息打开一个活动。示例:我从列表中选择“Bob”,我被带到一个名为 Bob、他的电子邮件和他的电话的新活动。或 JSON 可能已发送的任何其他值。如果我选择“George”,它会执行相同的操作,但会显示 George 的详细信息。

我尝试自己做这件事没有成功。任何帮助表示赞赏。

Details.java 代码:

public class Details extends AppCompatActivity implements AdapterView.OnItemClickListener {
    // Log tag
    private static final String TAG = Details.class.getSimpleName();

    private static String url = "removed";
    private List<LoadUsers> detailList = new ArrayList<LoadUsers>();
    private ListView listView;
    private CustomListAdapter adapter;
    private Button ShowDetailsButton;
    private Button AddDetails;
    private ProgressDialog pDialog;

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

        listView = (ListView) findViewById(R.id.lv);
        adapter = new CustomListAdapter(this, detailList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(this);

        ShowDetailsButton = (Button) findViewById(R.id.show_details);
        AddDetails = (Button) findViewById(R.id.add_details);

   

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);
        pDialog.setMessage("Loading...");

        // changing action bar color
       // getActionBar().setBackgroundDrawable(
              //  new ColorDrawable(Color.parseColor("#1b1b1b")));

        ShowDetailsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                detailList.clear();
                // Showing progress dialog before making http request
                showPDialog();

                // Creating volley request obj
                JsonArrayRequest detailsReq = new JsonArrayRequest(url,
                        new Response.Listener<JSONArray>() {
                            @Override
                            public void onResponse(JSONArray response) {
                                Log.d(TAG, response.toString());
                                hidePDialog();

                                // Parsing json
                                for (int i = 0; i < response.length(); i++) {
                                    try {

                                        JSONObject obj = response.getJSONObject(i);
                                        LoadUsers details = new LoadUsers();
                                        details.setTitle(obj.getString("name"));
                                        details.setThumbnailUrl(obj.getString("image"));
                                        details.setEmail(obj.getString("email"));
                                        details.setPhone(obj.getString("phone"));

                                        // adding to array
                                        detailList.add(details);

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }

                                // notifying list adapter about data changes
                                // so that it renders the list view with updated data
                                adapter.notifyDataSetChanged();
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();

                    }
                });

                // Adding request to request queue
                AppController.getInstance().addToRequestQueue(detailsReq);
            }
        });

        AddDetails.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent i = new Intent(Details.this, MoreDetails.class);
                startActivity(i);
            }
        });

    }

    private void showPDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidePDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(this, "Item Clicked: " + position, Toast.LENGTH_SHORT).show();
        Intent i = new Intent(Details.this, onDetailsSelect.class);
        startActivity(i);
    }
}

CustomListAdapter.java 代码:

public class CustomListAdapter extends BaseAdapter {
    public Activity activity;
    private LayoutInflater inflater;
    private List<LoadUsers> usersItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<LoadUsers> usersItems) {
        this.activity = activity;
        this.usersItems = usersItems;
    }

    @Override
    public int getCount() {
        return usersItems.size();
    }

    @Override
    public Object getItem(int location) {
        return usersItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
            NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
            TextView title = (TextView) convertView.findViewById(R.id.title);
            TextView email = (TextView) convertView.findViewById(R.id.lvemail);
            TextView phone = (TextView) convertView.findViewById(R.id.lvphone);


            // getting user data for the row
            LoadUsers m = usersItems.get(position);

            // thumbnail image
            thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

            // title
            title.setText(m.getTitle());

            // email
            email.setText("Email: " + String.valueOf(m.getEmail()));

            // phone
            phone.setText("Phone: " + String.valueOf(m.getPhone()));

            return convertView;

    }

}

选择项目时打开的新活动: onDetailsS​​elect.java:

public class onDetailsSelect extends AppCompatActivity {

    Toolbar toolbar;
    ActionBarDrawerToggle mActionBarDrawerToggle;
    DrawerLayout drawerLayout;
    private TextView title, email, phone;
    private List<LoadUsers> usersItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_onuserselect);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        NetworkImageView thumbNail = (NetworkImageView) findViewById(R.id.thumbnail);
        title = (TextView) findViewById(R.id.title);
        email = (TextView) findViewById(R.id.lvemail);
        phone = (TextView) findViewById(R.id.lvphone);

    }
}

【问题讨论】:

    标签: android json listview android-activity


    【解决方案1】:

    像这样修改你的 onItemClick:

     @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(this, "Item Clicked: " + position, Toast.LENGTH_SHORT).show();
    
             TextView title = (TextView) view.findViewById(R.id.title);
             String title_text = title.getText().toString();
    
             TextView email = (TextView) view.findViewById(R.id.lvemail);
             String email_text = email.getText().toString();
    
             TextView phone = (TextView) view.findViewById(R.id.lvphone);
             String phone_text = phone.getText().toString();
    
             Intent i = new Intent(Details.this, onDetailsSelect.class);
             i.putExtra("title_intent", title_text);
             i.putExtra("email_intent", email_text);
             i.putExtra("phone_intent", phone_text);
    
            startActivity(i);
        }
    

    并在 onDetailsS​​elect Activity 中检索 Intent 值,在 onCreate 中:

     @Override
       public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.detail);
    
         Intent i = getIntent();
    
         String title = i.getStringExtra("title_intent");
         String email = i.getStringExtra("email_intent");
         String phone = i.getStringExtra("phone_intent");
    
      }
    

    【讨论】:

    • 像魅力一样工作。谢谢。
    【解决方案2】:

    您可以将您在ListView 中单击的ArrayList 和项目position 传递给这样的新活动--

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        String item_position = String.valueOf(position);
        ArrayList<ListRowItem> full_listitem = listitem;
        Intent intent = new Intent(context,SecondActivity.class);
        Bundle extras = new Bundle();
        extras.putString(CRRNT_ROW_NUMBER, item_position);
        extras.putSerializable(LISTITEM, full_listitem);
        intent.putExtras(extras);
        startActivity(intent);
    }
    });
    

    在您的第二个活动中,您必须使用以下代码接收这些 -

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    item_position = extras.getString(FirstActivity.CRRNT_ROW_NUMBER);
    listitem = (ArrayList<ListRowItem>)extras.getSerializable(FirstActivity.LISTITEM);
    
    position = Integer.parseInt(item_position);
    currentlistitem = listitem.get(position);
    
    String a = currentlistitem.getA();
    String b = currentlistitem.getB();
    

    对于所有这些实现,您必须在您的活动和LoadUsers (Getter/Setter) 类中实现Serializable 接口。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多