How to dynamically create buttons from Json string

Pena Roxana :

I parsed JSON data from URL into a list and now I want to create buttons with every item of the list, but I can't figured out how to do this. I'm not sure if the list is the best idea, but I this was the solution I found online.

public class SecondActivity extends AppCompatActivity {

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

    private ProgressDialog pDialog;
    private ListView lv;

    private static String url = "https://ggysqqcz.p51.rt3.io/available-remotes/TV";

    ArrayList<HashMap<String, String>> contactList;

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

        contactList = new ArrayList<>();

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

        new GetContacts().execute();

    }


    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SecondActivity.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 remotes = jsonObj.getJSONArray("remotes");

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

                        String id = c.getString("id");


                        HashMap<String, String> contact = new HashMap<>();


                        contact.put("id", id);

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


            ListAdapter adapter = new SimpleAdapter(

                    SecondActivity.this, contactList,
                  R.layout.list_item, new String[]{"id"}, new int[]{button1});

            lv.setAdapter(adapter);


        }
    }

public void onClickButton1(View view) {
        startActivity(new Intent(getApplicationContext(), ThirdActivity.class));
    }
}

This shows all the buttons, but obviously they all do the same thing when clicked because I have only button1. How can I make all the buttons do different activities?

Reaz Murshed :

I would like to suggest creating a custom adapter for your ListView which will have an onClick function for your button and based on the position of that item in your ListView, you can implement different actions in your onClick function. Hence I would like to suggest an adapter like the following.

public class ListAdapter extends ArrayAdapter<Item> {

    private int resourceLayout;
    private Context mContext;
    private ArrayList<Contact> contacts;

    public ListAdapter(Context context, int resource, ArrayList<Contact> contacts) {
        super(context, resource, items);
        this.resourceLayout = resource;
        this.mContext = context;
        this.contacts = contacts;
    }

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

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(mContext);
            v = vi.inflate(resourceLayout, null);
        }

        Item p = getItem(position);

        if (p != null) {
            Button btn = (TextView) v.findViewById(R.id.button1);

            if (btn != null) {
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(position == 1) implementSomethingFor1();
                        else if (position == 2) implementSomethingFor2();
                        // ... Define the other implementations
                    }
                });
            }
        }

        return v;
    }
}

And then use the adapter like the following.

ListView lv = (ListView) findViewById(R.id.list);
ListAdapter customAdapter = new ListAdapter(this, R.layout.list_item, contactList);
lv.setAdapter(customAdapter);

Please note that this is not an exact implementation. You should modify your custom adapter so that it serves your purpose.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142713&siteId=1