Search code examples
androidjsonlistviewonclickclickable

Android clickable listview


I have a android code which that get some data in json format from php file, I successfully created a listview using those json now I want to create a second activity to show product details when I click on those items.

Here is the code :

public class MainActivity extends Activity {
    private String jsonResult;
    private String url = "xxxx/get_all_products.php";
    private ListView listView;

    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_FOUND = "found";
    private static final String TAG_DESCRIPTION = "description";

    ArrayList<HashMap<String, String>> productList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView1);
        productList = new ArrayList<HashMap<String, String>>();



        accessWebService();


        }




    // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            ListDrwaer();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[]{url});
    }

    // build hash set for list view
    public void ListDrwaer() {
        List<Map<String, String>> productList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("products");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("name");
                String price = jsonChildNode.optString("price");
                    String found = jsonChildNode.optString("found");
                //    String outPut = name + "-" + number;
           //     String outPut = name + "-" + price + "-" + found;
           //     productList.add(createProduct("products", outPut));
                HashMap<String, String> product = new HashMap<String, String>();

                product.put(TAG_NAME, name);
                product.put(TAG_FOUND, found);
                product.put(TAG_PRICE, price);

               productList.add(product);
            }
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                    Toast.LENGTH_SHORT).show();
        }




        SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
                R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
                TAG_FOUND }, new int[] { R.id.name,
                R.id.price, R.id.found });
        listView.setAdapter(simpleAdapter);

        }

        }

and also there are there are two xml layout files. I read many examples for doing this about setOnItemClickListener whit no success..... for example tried this with no success :

  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String selval = ((TextView) view).getText().toString();


                Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
                intnt.putExtra("selval ", selval);


            }

Here are the errors :

FATAL EXCEPTION: main
    java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
            at sig.example.com.sig00.MainActivity$1.onItemClick(MainActivity.java:59)

Here are xml files :

<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: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=".MainActivity" >
    <!-- Name Label -->
    <!--   android:id="@+id/listView1" -->
    <ListView
        android:id="@+id/listView1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="14dp">
   </ListView>

and the list_item.xml is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

    <!-- Name Label -->

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold"
        android:gravity="center"/>

    <!-- Email label -->
    <TextView
        android:id="@+id/price"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="#acacac" />

    <!-- Mobile number label -->
    <TextView
        android:id="@+id/found"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textColor="#5d5d5d"
        android:textStyle="bold" />



</LinearLayout>

Solution

  • Replace your code from your setOnItemClickListener() to this one :

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
         String selval = listview.getItemAtPosition(position).getText().toString();
         // Also I've found a solution on SO that a guy solved this problem doing soemthing like this : 
         // TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
         // String keyword = txt.getText().toString();
         Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
         intnt.putExtra("selval ", selval);
    

    EDIT

    Your error is that in your intent you are putting as extra "selval ", with an BLANK SPACE so if in your next activity you are doing this :

    Class SingleListItem extends Activity{ 
    @Override
    public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      this.setContentView(R.layout.productdetails); 
      TextView txtProduct = (TextView) findViewById(R.id.product_label); 
      Intent i = getIntent(); // getting attached intent data 
      String selval = i.getStringExtra("selval"); // displaying selected product name txtProduct.setText(selval); 
    }
    

    It never will return your selval string cause you are asking for "sevlal" not from "selval ".

    Just remove your unnecessary space and it will work :)