0

我有三个值,我使用 JSON 从 mysql 数据库中提取它们并将它们显示在 ListView 中。我想要的是我想添加一个点击监听器。我调用了一个全局字符串变量urlPageNumHolder来保存单击的 ListView 中的 ID,因此当单击列表时,我希望loadPage()调用函数来显示在 ListVew 中单击的项目 ID 的 Toast。我试过了,但是每当我单击列表中的项目时,它只会显示 ListView 中最后一个项目的 ID。请问F1?下面是完整的代码。

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) *****/

}
4

3 回答 3

0

urlPageNumHolder仅设置在一行 urlPageNumHolder = MyArrList.get(position).get("ImageID").toString()中,与单击的项目无关。

修改public void loadPage() {...}

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

并将其调用为:

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

基本上,告诉您使用您最初忽略onItemClickListener的参数单击了哪个项目。id此参数应用于标识被单击的项目。

编辑: id 可能不足以为您识别数据。在这种情况下,可以修改 loadPage,如下所示。

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

注意:我的代码可能无法按原样工作,您可能需要进行一些 int 到 long 的转换(反之亦然)

于 2013-10-04T16:39:24.807 回答
0

看起来您在点击时调用 loadPage,您需要将点击的索引传递给 loadPage 方法,然后调用MyArrList.get(position);以获取您点击的位置,然后用它做任何您想做的事情。

于 2013-10-04T16:36:56.063 回答
0

我看到你发现 onitemclicklistner 很棒,但是按钮列表视图按钮消耗点击。简单的解决方案是用 textview 或图像图标替换按钮。另一个解决方案是,你不能使用 findviewbyid 因为你必须创建数组中每个按钮上的按钮数组和 onitemclick 侦听器。所以它将以编程方式完成而不是在 xml 中(无论如何都是按钮)我也不确定你的列表适配器所以 YouTube slidenerd 89 custombaseadapterhttp://m.youtube.com/watch?v=ka5Tk7J9rG0

于 2013-10-04T16:55:19.290 回答