AnonProg
AnonProg

Reputation: 117

How to retrieve values from ListView with JSON values on new activity?

The code below works fine. It populates a list with values from a JSON response and will open a new activity on selection of any of the items, as well as displaying the number of the item.

My question is how to have the selected item open an activity with the specific information from that item. Example: I select "Bob" from the List, I am taken to a new activity with the name of Bob, his email, and his phone. Or any other values that the JSON might have sent. If I select "George" it will do the same, but with the details for George.

I attempted unsuccessfully to do this on my own. Any help is appreciated.

Details.java code:

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 code:

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;

    }

}

New Activity that is being opened on selection of item: onDetailsSelect.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);

    }
}

Upvotes: 0

Views: 62

Answers (2)

Sin
Sin

Reputation: 83

Modify your onItemClick like that:

 @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);
    }

And retrieve the intent values in onDetailsSelect Activity, in 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");

  }

Upvotes: 1

Saumik Bhattacharya
Saumik Bhattacharya

Reputation: 941

You can pass your ArrayList and item position on which you have clicked in the ListView, to the new activity like this --

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);
}
});

In your 2nd Activity, you have to receive these using the below code --

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();

For all these implementations, you have to implement Serializable interface in both your Activities and also in the LoadUsers (Getter/Setter) class.

Hope this helps!

Upvotes: 1

Related Questions