0

I am trying to pass position of listview index to one user define function. That function is for click event of button in listview. Here is my code: public class Vegetables extends Activity {

ProgressDialog pDialog;
ListView mListView;
SimpleAdapter adapter;
private Activity activity;  
AQuery aq;
public int idx;

private JSONArray mComments = null;

private ArrayList<HashMap<String, Object>> mCommentList;

ArrayList<HashMap<String, Object>> searchResults;
public Activity context;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.vegetables);   
    aq=new AQuery(this);

    String strUrl = "http://gaubharat.in/gaubharat/first.php";

    DownloadTask downloadTask = new DownloadTask();


    downloadTask.execute(strUrl);


    mListView = (ListView) findViewById(R.id.lv_vegetable);       
}



private String downloadUrl(String strUrl) throws IOException{
    String data = "";

    InputStream iStream = null;
    try{
            URL url = new URL(strUrl);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

    }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
    }finally{
            iStream.close();
    }

    return data;
}

private class DownloadTask extends AsyncTask<String, Integer, String>{
    String data = null;
            @Override
            protected String doInBackground(String... url) {
                    try{
                        data = downloadUrl(url[0]);

                    }catch(Exception e){
                        Log.d("Background Task",e.toString());
                    }
                    return data;
            }

            @Override
            protected void onPostExecute(String result) {

                    ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

                    listViewLoaderTask.execute(result);                        

            }
}


private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
    /*LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.vegetables, null, true);*/

    JSONObject jObject;

    @Override
    protected  SimpleAdapter doInBackground(String... strJson) {
        try{

            jObject = new JSONObject(strJson[0]);
            CountryJSONParser countryJsonParser = new CountryJSONParser();
            countryJsonParser.parse(jObject);

        }
        catch(Exception e){
            Log.d("JSON Exception1",e.toString());
        }       

        // Instantiating json parser class
        CountryJSONParser countryJsonParser = new CountryJSONParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> countries = null;

        try{
            // Getting the parsed data as a List construct
            countries = countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("Exception",e.toString());
        }          

        String[] from = {"product_name","product_memberprice","product_minquantity","product_image"};

        // Ids of views in listview_layout
        int[] to = { R.id.product_name,R.id.unitprice,R.id.minqty,R.id.img};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item         
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.productlayout, from, to);  
    return adapter;

    }


    /** Invoked by the Android on "doInBackground" is executed */
    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        mListView.setAdapter(adapter);


        for(int i=0;i<adapter.getCount();i++){
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
            String imgUrl = (String) hm.get("flag_path");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("flag_path",imgUrl);
            hm.put("position", i);

            // Starting ImageLoaderTask to download and populate image in the listview 
            imageLoaderTask.execute(hm); 


            //addtocart(mListView,i);

             idx = i;

        }

    }       
}

public void addtocart(View v){

    //final int index = i;
     mListView = (ListView) findViewById(R.id.lv_vegetable);

    LinearLayout vwParentRow = (LinearLayout)v.getParent();

    TextView child = (TextView)vwParentRow.getChildAt(0);
    ImageView img = (ImageView)vwParentRow.getChildAt(1);
    TextView qty = (TextView)vwParentRow.getChildAt(2);
    TextView pr = (TextView)vwParentRow.getChildAt(3);
    Button btnChild = (Button)vwParentRow.getChildAt(4);


    btnChild.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

    Toast.makeText(Vegetables.this,"Index" + idx ,Toast.LENGTH_LONG ).show();
        }
    });

    vwParentRow.refreshDrawableState();
}

/** AsyncTask to download and load an image in ListView */
 private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

        InputStream iStream=null;

        String imgUrl = (String) hm[0].get("flag_path");
        int position = (Integer) hm[0].get("position");

        URL url;

        try {
            url = new URL(imgUrl);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            iStream = urlConnection.getInputStream();

            File cacheDirectory = getBaseContext().getCacheDir();

            File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");               

            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            Bitmap b = BitmapFactory.decodeStream(iStream); 

            b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);                      

           /* fOutStream.flush();

            fOutStream.close();   */          

            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

            hmBitmap.put("product_image",tmpFile.getPath());

            hmBitmap.put("position",position);              

            return hmBitmap;                

        }
        catch (Exception e) {               
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(HashMap<String, Object> result) {

      String path = (String) result.get("product_image");           

        int position = (Integer) result.get("position");

        SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

        HashMap<String, Object> hm = (HashMap<String, Object>)adapter.getItem(position);    

        hm.put("product_image",path);

        adapter.notifyDataSetChanged(); 
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, 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();
    if (id == R.id.action_settings) {
        return true;

   }

    return super.onOptionsItemSelected(item);
}      
}

I received idx value on button click but that is last value from for loop. Kindly help me.

4
  • 1
    Use OnItemClickListener. Here in your code idx is being set by i in each loop iteration so you are getting only last value. For loop won't wait for you. learn to use OnItemClickListener in ListView. No need to ask another question. There are a lot of resources already available in SO Commented Dec 29, 2015 at 10:59
  • Adding a sample code in answer. it would be helpful. Commented Dec 29, 2015 at 11:05
  • @Rohit5k2 thanks for your support but I already had done with OnItemClickListener in ListView. But as I read many articles, according to that OnItemClickListener is not working in ListView. Commented Dec 29, 2015 at 11:08
  • @ru-23 I don't see any reason why it wont work for ListView. I have always used it (and using in current work too). Commented Dec 29, 2015 at 11:10

1 Answer 1

1

Here in your code idx is being set by i in each loop iteration so you are getting only last value. For loop won't wait for you.

You need to use OnItemClickListener on the ListView like this.

listView.setOnItemClickListener(new OnItemClickListener() 
{
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
    {
        idx = position;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Its showing me error: The method setOnClickListener(View.OnClickListener) in the type AdapterView<ListAdapter> is not applicable for the arguments (new OnItemClickListener(){})
I also tried with getview() function. But click event didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.