0

I am developing an app, It reads data from a JSON Object file online. I have successfully gotten the data into the app and reading fine into the listview. How would I implement an OnclickListener for the listview so when a user clicks the heading they are taken to a new activity which then displays all the data for that item in textViews. My code to get the data is below with my layout.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

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

private ProgressDialog pDialog;
private ListView lv;

// URL to get Android Version Data JSON
private static String url = "http://codetest.cobi.co.za/androids.json";

ArrayList<HashMap<String, String>> androidversions;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    androidversions = new ArrayList<>();

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

    new GetVersions().execute();
}

private class GetVersions 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 {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray versions = jsonObj.getJSONArray("versions");

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

                    String name = c.getString("name");
                    //String version = c.getString("version");
                    //String released = c.getString("released");
                    //String api = c.getString("api");
                    //String image = c.getString("image");

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

                    // adding each child node to HashMap key => value
                    Version.put("name", name);
                    //Version.put("version", version);
                    //Version.put("released", released);


                    // adding Data to version list
                    androidversions.add(Version);
                }
            } 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, androidversions,
                R.layout.list_item, new String[]{"name", "version",
                "released"}, new int[]{R.id.name,
                R.id.version, R.id.released});

        lv.setAdapter(adapter);
      }

   }
}

Listview

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="www.cobi.co.za.cobiinteractive.MainActivity">

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</RelativeLayout>

The app looks like this enter image description here

Pooveshin
  • 203
  • 5
  • 13

5 Answers5

2

Try this inside the onPostExecute,

@Override
protected void onPostExecute(Void result) {

    ...
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
            HashMap<String, String> selected = androidversions.get(position);
            // pass HashMap using intent
        }
    });
  }
}
K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
  • thank you so much, how would I now pass the data which is String name = c.getString("name"); String version = c.getString("version"); String released = c.getString("released"); String api = c.getString("api"); to now display in this new activity. – Pooveshin Feb 07 '17 at 12:31
  • @Pooveshin you can use the extras bundle for that: http://stackoverflow.com/questions/768969/passing-a-bundle-on-startactivity# – nbokmans Feb 07 '17 at 12:39
0

Use itemclicklistener of listview and fetch object of spefic item from hashmap list and pass this object vai intent to next activity and get data vai bundle in next activity.

Jd Prajapati
  • 1,953
  • 13
  • 24
0

As I understands, you want to set onClickListener on the whole row of the listview, right?

you can do as follows after setting the adapter in onPostExecute:

   lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //You want here to pass the data to another activity
            Intent intent = new Intent(YOUR_1ST_ACTIVITY_NAME.this, YOUR_2ND_ACTIVITY_NAME.class);
            intent.putExtra("name",name);
            intent.putExtra("version",version);
            intent.putExtra("released",released);
            intent.putExtra("api",api);
            YOUR_1ST_ACTIVITY_NAME.this.startActivity(intent);
        }
    });

and then in YOUR_2ND_ACTIVITYE, in onCreate

 Intent intent = getIntent();
    if (intent != null) {
        String name = intent.getStringExtra("name");
        String version = intent.getStringExtra("version");
        String released = intent.getStringExtra("released");
        String api = intent.getStringExtra("api");
        //....
    }

But if you want to assign onClickListener for components inside the row's view, you might want to read about ListView with custom adpater link

Community
  • 1
  • 1
Atef Hares
  • 4,715
  • 3
  • 29
  • 61
  • hank you so much, how would I now pass the data which is String name = c.getString("name"); String version = c.getString("version"); String released = c.getString("released"); String api = c.getString("api"); to now display in this new activity. – Pooveshin Feb 07 '17 at 12:37
  • When I try to do this it gets an error with the names of the items I want to take across. – Pooveshin Feb 07 '17 at 13:34
  • @Pooveshin, Update the question with your current problem, and put the current code and the error log or the error hint – Atef Hares Feb 07 '17 at 13:37
0

Change your oncreate method with this

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    androidversions = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        // create intent and start your second activity
    }

});
    new GetVersions().execute();
}
Muhammed GÜNEŞ
  • 304
  • 2
  • 15
0

Use a modal class like this can help

      public class Version implements Serializable{

    public Version(String name, String version, String released) {
        this.name = name;
        this.version = version;
        this.released = released;
    }

    private String name;
    private String version;
    private String released;
    private String api;
    private String image;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getReleased() {
        return released;
    }

    public void setReleased(String released) {
        this.released = released;
    }

    public String getApi() {
        return api;
    }

    public void setApi(String api) {
        this.api = api;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

}

and get and set all value using constructor as

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

HashMap<String, String> selected = androidversions.get(position);
                    Version verison = new Version(selected.getString("name"),selected.getString("version"),selected.getString("released"))
                    Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                    intent.putExtra("verisonDetails", verison);
                    startActivity(intent);
                }
            });

In Details Activity you could get as

        version = (Version) getIntent().getExtras().getSerializable("verisonDetails");

in oncreate() and get each value as version.get..

g7pro
  • 817
  • 1
  • 6
  • 11