1

I have an app which uses listview to show data received from a JSON.Now, I want an onItemclick listener in the listview so that, after displaying the listview users can click on any row to start a new activity. But the onclicklistener is not working.I am a new developer so am unable to make it work. Kindly help me so that I can implement the onclick Listener. Thanks in advance.

Edited:- Another problem I am facing is that switch case doesnt seem to work because I don't know how many ids will be added to the rows i.e the rows are unknown to me, it may be anything. So what should I use instead of switch case?

Thanks in advance

This is my StatementsActivity.java which displays the listview

public class StatementsActivity extends AppCompatActivity {

    SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(OpeningScreenActivity.getContextOfApplication());
    String token = myPrefs.getString("GCMTOKEN", "");
    String JSON_URL = "http://xyz.in/view_json.php?device_id=" + token;

    private ListView listView;



    private GoogleApiClient client;

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


        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            R.layout.list_view_layout, ParseJSON.ids);
        listView = (ListView) findViewById(R.id.listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                            @Override
                                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                                switch (position) {
                                                    case 0:
                                                        Intent newActivity = new Intent(StatementsActivity.this, MainActivity.class);
                                                        startActivity(newActivity);
                                                        break;
                                            }
                                        }
           @SuppressWarnings("unused")
           public void onClick(View v){
           }
        });
        sendRequest();

        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

 private void sendRequest() {
        StringRequest stringRequest = new StringRequest(JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(StatementsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}



private void showJSON(String json) {
    ParseJSON pj = new ParseJSON(json);
    pj.parseJSON();
    CustomList cl = new CustomList(this, ParseJSON.ids,ParseJSON.mem_codes,ParseJSON.created_ons);
    listView.setAdapter(cl);
    }
}

This is my CustomList.java class

public class CustomList extends ArrayAdapter<String> {
private String[] ids;
private String[] mem_codes;
private String[] created_ons;
private Activity context;



public CustomList(Activity context, String[] ids, String[] mem_codes, String[] created_ons) {
    super(context, R.layout.list_view_layout, ids);
    this.context = context;
    this.ids = ids;
    this.mem_codes = mem_codes;
    this.created_ons = created_ons;


}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
    TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
    TextView textViewMemCode = (TextView) listViewItem.findViewById(R.id.textViewMem_code);
    TextView textViewCreatedOn = (TextView) listViewItem.findViewById(R.id.textViewCreated_on);
    textViewId.setText(ids[position]);
    textViewMemCode.setText(mem_codes[position]);
    textViewCreatedOn.setText(created_ons[position]);
    return listViewItem;
   }
}

And this is my ParseJSON.java class

public class ParseJSON {
public static String[] ids;
public static String[] mem_codes;
public static String[] created_ons;

public static final String KEY_ID = "id";
public static final String KEY_MEM_CODE = "mem_code";
public static final String KEY_CREATED_ON = "created_on";
public static final String JSON_ARRAY = "result";

private JSONArray users = null;

private String json;

public ParseJSON(String json){
    this.json = json;
}

protected void parseJSON(){
    JSONObject jsonObject=null;
    try {
        jsonObject = new JSONObject(json);
        users = jsonObject.getJSONArray(JSON_ARRAY);

        ids = new String[users.length()];
        mem_codes = new String[users.length()];
        created_ons = new String[users.length()];

        for(int i=0;i<users.length();i++){
            JSONObject jo = users.getJSONObject(i);
            ids[i] = jo.getString(KEY_ID);
            mem_codes[i] = jo.getString(KEY_MEM_CODE);
            created_ons[i] = jo.getString(KEY_CREATED_ON);
        }
    } catch (JSONException e) {
        e.printStackTrace();
      }
   }
}

This is my activity_statements.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/buttonColor" tools:context=".StatementsActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:layout_alignParentTop="true"
    android:layout_marginTop="50dp"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView1" />
</LinearLayout>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        layout="@layout/toolbar_layout"/>
</LinearLayout>


 </RelativeLayout>

And this is my list_view_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/buttonColor">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textViewId"
    android:layout_alignParentStart="true"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textViewMem_code"
    android:layout_centerHorizontal="true"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textViewCreated_on"
    android:layout_alignParentEnd="true"/>

</RelativeLayout>
Janki Gadhiya
  • 4,492
  • 2
  • 29
  • 59
BabiSter
  • 27
  • 8

2 Answers2

2

I have built an android application which displays in Listview style and on clicking on them, shows their respective cost.

Below is the code of that. Hope, it helps you...

public class ListViewActivity extends AppCompatActivity {

   private static ListView lv;
   private static String[] prod_names = new String[] {"E", "G", "E2", "G2", "X"};
   private static int[] cost = new int[] {6500, 13000, 7500, 16000, 25000};


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

       Listener();
  }

public void Listener(){
    lv = (ListView)findViewById(R.id.listView);
    ArrayAdapter <String> adp = new ArrayAdapter<String>(this, R.layout.products_list, prod_names);
    lv.setAdapter(adp);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String val = (String)lv.getItemAtPosition(position);
            Toast.makeText(ListViewActivity.this, " Release# : "+ (position+1)+"\n Model : "+val+"\n Cost : Rs "+cost[position], Toast.LENGTH_LONG).show();

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_list_view, menu);
    return true;
}

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
       // Handle action bar item clicks here. The action bar will
       // automatically handle clicks on the Home/Up button, so long
       // as you specify a parent activity in AndroidManifest.xml.
       int id = item.getItemId();

       //noinspection SimplifiableIfStatement
       if (id == R.id.action_settings) {
           return true;
       }

       return super.onOptionsItemSelected(item);
   }
}
Vickyexpert
  • 3,147
  • 5
  • 21
  • 34
  • Goodish answer. However you need to explain what is different between your code and OP's to really help OP and future people understand the issue. – basic Jul 14 '16 at 12:56
  • The difference can be easily understood by referring my code. Since he is also a coder, understanding this difference is not a problem – Yashaswi Bharadwaj Jul 15 '16 at 07:16
  • My issue was not with OP understanding primarily it was more so that if someone in the future has a similar issue who may not be quite as well versed, a good explanation can go a long way. – basic Jul 15 '16 at 12:48
  • @YashaswiBharadwaj My question is little different, I even edited it. – BabiSter Jul 16 '16 at 04:58
0

Do it like this in your onItemClick:

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


        Intent newActivity = new Intent(StatementsActivity.this, MainActivity.class);
        // Adding your variable to intent
        newActivity.putExtra("position",position);
        startActivity(newActivity);
        break;

    }

});

In your MainActivity.java :

public class MainActivity extends Activity
{
    int position;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // Receiving your variable in another activity
        position = getIntent().getIntExtra("position",0);

    }
}

And kindly refer this : How do I pass data between Activities in Android application?

Edit :

Check this out

  1. OnItemCLickListener not working in listview
  2. ListView OnItemClickListener Not Responding?
  3. OnItemClickListener and OnClickListener not working for ListView
  4. ListView.onItemClick not working
  5. Listview itemclick not work
Community
  • 1
  • 1
Janki Gadhiya
  • 4,492
  • 2
  • 29
  • 59