0

I've three values which I extract them from mysql database using JSON and displayed them in a ListView. What I want is I wanna add a click listener. I've a global string variable called urlPageNumHolder to hold the ID from the clicked ListView, so when the list is clicked I want loadPage() function to be called to display Toast of the item ID clicked in the ListVew. I tried it, but whenever I clicked the item in the list, it only toasts ID of the last item in the ListView. Please F1? Below is the full code.

MainActivity.java

package com.myapp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

    private ListView lstView;
    private ImageAdapter imageAdapter;

    public int currentPage = 1;
    public int TotalPage = 0;

    public Button btnNext;
    public Button btnPre;

    public String urlPageNumHolder;

    public ProgressDialog dialog;

    ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // ListView and imageAdapter
        lstView = (ListView) findViewById(R.id.listView1);
        lstView.setClipToPadding(false);
        imageAdapter = new ImageAdapter(getApplicationContext());
        lstView.setAdapter(imageAdapter);

        // Next
        btnNext = (Button) findViewById(R.id.btnNext);
        // Perform action on click
        btnNext.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentPage = currentPage + 1;
                ShowData();
            }
        });

        // Previous
        btnPre = (Button) findViewById(R.id.btnPre);
        // Perform action on click
        btnPre.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentPage = currentPage - 1;
                ShowData();
            }
        });

        // Show first load
        ShowData();

        // OnClick
            lstView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    loadPage();
                }
            });

    }

    public void ShowData() {
        btnNext.setEnabled(false);
        btnPre.setEnabled(false);

        new LoadContentFromServer().execute();

        dialog = ProgressDialog.show(this, "News", "Loading...", true, false);
    }

    public void loadPage() {

            Toast.makeText(this, urlPageNumHolder, Toast.LENGTH_LONG).show();

    }


    class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {

        @Override
        protected Object doInBackground(Object... params) {

            String url = "http://10.0.2.2/android/Pagination/getAllData.php";

            JSONArray data;
            try {
                data = new JSONArray(getJSONUrl(url));

                MyArrList = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> map;

                int displayPerPage = 7; // Per Page
                int TotalRows = data.length();
                int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);

                if (TotalRows <= displayPerPage) {
                    TotalPage = 1;
                } else if ((TotalRows % displayPerPage) == 0) {
                    TotalPage = (TotalRows / displayPerPage);
                } else {
                    TotalPage = (TotalRows / displayPerPage) + 1;
                    TotalPage = (int) TotalPage;
                }
                int indexRowEnd = displayPerPage * currentPage;
                if (indexRowEnd > TotalRows) {
                    indexRowEnd = TotalRows;
                }

                for (int i = indexRowStart; i < indexRowEnd; i++) {
                    JSONObject c = data.getJSONObject(i);
                    map = new HashMap<String, Object>();
                    map.put("ImageID", (String) c.getString("ImageID"));
                    map.put("ItemID", (String) c.getString("ItemID"));

                    // Thumbnail Get ImageBitmap To Object
                    map.put("ImagePath", (String) c.getString("ImagePath"));
                    Bitmap newBitmap = loadBitmap(c.getString("ImagePath"));
                    map.put("ImagePathBitmap", newBitmap);


                    MyArrList.add(map);

                    publishProgress(i);

                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        public void onProgressUpdate(Integer... progress) {
            imageAdapter.notifyDataSetChanged();
        }

        @Override
        protected void onPostExecute(Object result) {

            // Disabled Button Next
            if (currentPage >= TotalPage) {
                btnNext.setEnabled(false);
            } else {
                btnNext.setEnabled(true);
            }

            // Disabled Button Previos
            if (currentPage <= 1) {
                btnPre.setEnabled(false);
            } else {
                btnPre.setEnabled(true);
            }

            // dismiss the progress dialog
            if(dialog != null)  dialog.dismiss();
        }
    }

    class ImageAdapter extends BaseAdapter {

        private Context mContext;

        public ImageAdapter(Context context) {
            mContext = context;
        }

        public int getCount() {
            return MyArrList.size();
        }

        public Object getItem(int position) {
            return MyArrList.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.activity_column, null);
            }

            // ColImagePath
            ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImagePath);
            imageView.getLayoutParams().height = 100;
            imageView.getLayoutParams().width = 100;
            imageView.setPadding(5, 5, 5, 5);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try {
                imageView.setImageBitmap((Bitmap) MyArrList.get(position).get("ImagePathBitmap"));
            } catch (Exception e) {
                // When Error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }

            // ColImageID
            TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImageID);
            txtImgID.setPadding(10, 0, 0, 0);
            txtImgID.setText(MyArrList.get(position).get("ImageID").toString());


            // ColItemID
            TextView txtItemID = (TextView) convertView.findViewById(R.id.ColItemID);
            txtItemID.setPadding(10, 0, 0, 0);
            txtItemID.setText(MyArrList.get(position).get("ItemID").toString());


            //Hold Detail's URL
            urlPageNumHolder = MyArrList.get(position).get("ImageID").toString();


            return convertView;

        }

    }

    /*** Get JSON Code from URL ***/
    public String getJSONUrl(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    /***** Get Image Resource from URL (Start) *****/
    private static final String TAG = "Image";
    private static final int IO_BUFFER_SIZE = 4 * 1024;

    public static Bitmap loadBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            // options.inSampleSize = 1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
                    options);
        } catch (IOException e) {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }

        return bitmap;
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
    /***** Get Image Resource from URL (End) *****/

}
B3738
  • 51
  • 1
  • 1
  • 10

3 Answers3

0

it looks like you're calling loadPage on click, you need to pass in the index clicked to the loadPage method, then call MyArrList.get(position); to get the location you clicked, then do whatever you want with it.

Eluvatar
  • 2,265
  • 19
  • 24
0

urlPageNumHolder is only being set in one line urlPageNumHolder = MyArrList.get(position).get("ImageID").toString(), which has nothing to with the item being clicked.

Modify public void loadPage() {...} to

public void loadPage(long id) {
  Toast.makeText(this, String.valueOf(id), Toast.LENGTH_LONG).show();
}

and invoke it as :

listView.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    loadPage(id);
  }
});

Basically, onItemClickListener tells you which item was clicked with the id parameter that you were originally ignoring. This parameter should be used to identify the item that was clicked.

EDIT: The id may not be enough to identify the data for you case. In that case, loadPage can be modified as shown below.

public void loadPage(long id) {
  Toast.makeText(this, MyArrList.get(position).get("ImageID").toString(), Toast.LENGTH_LONG).show();
}

NOTE: my code may not work as is, you might have to do some int to long conversions (or vice versa)

f2prateek
  • 2,034
  • 2
  • 20
  • 26
  • unfortunately the id in this case is coming from the adapter, which just returns the index currently, that should be fixed and then this will work just fine. – Eluvatar Oct 04 '13 at 16:42
  • Right, didn't see that. You can modify loadPage as I'll show above again. – f2prateek Oct 04 '13 at 16:43
  • **f2parteek** Thanks, you gave nice idea. But I'd a very hard time with this one: check it out please? [link](http://stackoverflow.com/questions/19182680/encoding-json-to-support-utf-8-characters-in-an-android-app) – B3738 Oct 07 '13 at 15:31
0

I see you found onitemclicklistner which is great but with a listview of buttons the buttons consume the click.the easy solution is replace buttons with textview or image icon.the other solution would be,and you can't use findviewbyid because you have to create an array of buttons and onitemclick listeners on each button in the array. So it would be done programaticly not in xml (the buttons anyway) Also I am not sure about your list adapter so YouTube slidenerd 89 custombaseadapterhttp://m.youtube.com/watch?v=ka5Tk7J9rG0