1

How can I give a button id the id from the parsed JSON data into the listview?

Currently I have this method:

    @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(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "description",
                "release_at", "details" }, new int[]{R.id.name,
                R.id.description, R.id.release_at});

        lv.setAdapter(adapter);
    }

I want to add the id to the created buttons, like so:

    <Button
        android:id="@+id/gameDetails"      // <- here I want to add my id
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

Later on I want to create an intent and post the button id to the new Activity something like this:

public void openDetails(View view) {
    String getContactId = new GetContacts().getButtonId();
    Intent paralaxActivityItent = new Intent(MainActivity.this, ParalaxToolbarActivity.class);
    paralaxActivityItent.putExtra("id", id); // the button id
    MainActivity.this.startActivity(paralaxActivityItent);
}

In the other Activity I want to show data realated to the id which I post.

Since im new to android developing I am not sure if that is the correct.

Edit:

This is my Adapter:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private List<String> friends;
    private Activity activity;
    private ArrayList<HashMap<String, String>> contactList;

    public RecyclerAdapter(Activity activity, List<String> friends) {
        this.friends = friends;
        this.activity = activity;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        //inflate your layout and pass it to view holder
        LayoutInflater inflater = activity.getLayoutInflater();
        View view = inflater.inflate(android.R.layout.simple_list_item_1, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder viewHolder, int position) {

        viewHolder.item.setText(friends.get(position));
    }

    @Override
    public int getItemCount() {
        return (null != friends ? friends.size() : 0);
    }

    /**
     * View holder to display each RecylerView item
     */
    protected class ViewHolder extends RecyclerView.ViewHolder {
        private TextView item;

        public ViewHolder(View view) {
            super(view);
            item = (TextView) view.findViewById(android.R.id.text1);
        }
    }

}

MyGetContact class:

/**
 * 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(MainActivity.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 {
                // Getting JSON Array node
                JSONArray jsonArray = new JSONArray(jsonStr);

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

                    String id = c.getString("id");
                    String name = c.getString("name");
                    String description = c.getString("description");
                    String video_url = c.getString("video_url");
                    String platform = c.getString("platform");
                    String avaible = c.getString("avaible");
                    String release_at = c.getString("release_at");

                    // tmp hash map for single contact
                    HashMap<String, String> data = new HashMap<>();

                    // adding each child node to HashMap key => value
                    data.put("id", id);
                    data.put("name", name);
                    data.put("description", description);
                    data.put("video_url", video_url);
                    data.put("platform", platform);
                    data.put("release_at", release_at);

                    // adding contact to contact list
                    contactList.add(data);
                }
            } 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(
            MainActivity.this, contactList,
            R.layout.list_item, new String[]{"name", "description",
            "release_at", "details" }, new int[]{R.id.name,
            R.id.description, R.id.release_at});

    lv.setAdapter(adapter);
}
utdev
  • 3,168
  • 5
  • 31
  • 58
  • You have to create your own adapter class – OneCricketeer Nov 26 '16 at 17:51
  • I have an adapter clas but I do not know how to proceed, shall I add it to my question aswell? – utdev Nov 26 '16 at 17:51
  • Yes please. Looks like you have a SimpleAdapter, though, not your own adapter class . Also show the json data. And the class definition of `GetContacts` because if that's an Activity, you shouldn't `new` it – OneCricketeer Nov 26 '16 at 17:53
  • Your question is not using `RecyclerAdapter`... Why do you need to reassign a button ID anyway? You cannot findViewById for it anymore if you do that. I think you instead want to setTag into the button for the JSON id value. You can later getTag from that button – OneCricketeer Nov 26 '16 at 17:59
  • @cricket_007 ok I added the Adapter and the GetContacts class, my json data should be fine on the first page(activity) it is printed successfully, do ou still want to look at 1-2lines of it? – utdev Nov 26 '16 at 18:00
  • Let me describe me idea differently(since I think my approache is wrong), I am basically displaying data from my json in my view each data has its unique id (name, description ...), my idea was to click on one button and show in a new Activity its realted data(description in my case) – utdev Nov 26 '16 at 18:02
  • @cricket_007 I went through a tutorial that is why I use that :), whops sorry I forgot to copy the onPostExecute I used it – utdev Nov 26 '16 at 18:03
  • @cricket_007 I updated my question with the onPostExecute method – utdev Nov 26 '16 at 18:09
  • Basically 1) I'd suggest trying to use Retrofit & Gson to handle the network request 2) you should try to build the button click process using static data before handling JSON. That'll get a better understanding of what you need 3) what you're describing is called master-detail flow, and I'm sure there's lots of tutorials on that – OneCricketeer Nov 26 '16 at 18:11

2 Answers2

1

I don't really think assigning button view ids from parsed Json data is a good idea.

How about this:

  1. Get json data, parse it, and design the data structure to hold that data, something like JsonDataMode in my exmaple.

  2. Parse json data and add it to list data structure, something like List.

  3. Design and implement your adapter for the ListView. Init the adapter with the data list.

  4. Setup child view's tag to make the child view able to contain the data.

  5. Have one OnclickListener for this listview to react when child view item is clicked.

Full ListView Example

Alright, guys. Now you can click ▲.

shanwu
  • 1,585
  • 6
  • 24
  • 40
  • But how can I Show the related Data on the other Activity this Way?Could you Show me an example? – utdev Nov 27 '16 at 11:52
  • @utdev alright, I got you the full example. If you have more questions, please let me know. By the way, If this answer is helpful, please select "this answer is useful" by clicking the triangle icon. ▲ :D – shanwu Nov 27 '16 at 15:10
  • Would you like to move into a chat? – utdev Nov 27 '16 at 17:35
  • I somehow understood it but I got a couple of question mind having a quick chat with me? – utdev Nov 27 '16 at 19:58
  • No problem, but it's CST time zone here...@utdev – shanwu Nov 28 '16 at 00:19
  • It it Utc timezone here what would fit yiu the best(day and time) I from monady to tuesday I am online from 20:00 - 24:00 and on fridays to saturday from 20:00-02:00 maybe Even later – utdev Nov 28 '16 at 13:18
  • are you currently online? – utdev Nov 28 '16 at 14:52
0

I think there are better ways on how to approach your problem. But if you really want to change ID of a view (in this case button) then there is some nice explanation on this

How can I assign an ID to a view programmatically?

Community
  • 1
  • 1
P.C. Blazkowicz
  • 489
  • 1
  • 4
  • 11