使用ID在setOnClickListener上设置ListView

时间:2014-11-05 18:29:50

标签: android listview android-listview

我有listView显示来自MySQL DB的图像和文本。到目前为止还可以,但现在我想知道如果点击某个项目从数据库中打开该ID,该如何制作。示例ListView 1与数据库中的id=1一致。ListView 2id=2一样,依此类推。当我单击第2项以从DB打开该ID时。知道我该怎么办? 这是加载listview的xml

<?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:minHeight="50dp"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/buttons" 
    android:layout_marginTop="10dp"
    >

    <ImageView
        android:id="@+id/image"
        android:layout_width="50dp"
        android:layout_height="50dp"
         />

    <TextView
        android:id="@+id/name"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingLeft="5dp"
        android:paddingTop="15dp"
        android:text="" />

</LinearLayout>

</LinearLayout>

这是我认为需要解决的代码部分

public class Restaurants extends Activity {

ListView listView;
TextView textView, textView1;
private StockAdaptor stockAdaptor;
String jsonResult = null;
ImageView image;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.restaurants); //Just a listView, shown below
    listView = (ListView) findViewById(android.R.id.list);
    textView = (TextView) findViewById(R.id.name);
    image = (ImageView) findViewById(R.id.image);
    new JsonReadTask().execute("http://link/GetRestaurants.php");



    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(listView.getLayoutParams());
    lp.setMargins(10, 10, 0, 0);
    listView.setLayoutParams(lp);

    textView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Restaurants.this, RestaurantInformation.class);
            startActivity(intent);

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true; //No options
}

public void onStart() {
    super.onStart();

    stockAdaptor = new StockAdaptor(this); //Create a new StockAdaptor
}

public static String strFromStream(InputStream in) throws IOException { //Simple function, getting a String from an InputStream
    StringBuilder out = new StringBuilder();
    BufferedReader breader = new BufferedReader(new InputStreamReader(in));
    String cline;
    String newLine = System.getProperty("line.separator");
    while ((cline = breader.readLine()) != null) {
        out.append(cline);
        out.append(newLine);
    }
    return out.toString();
}

private class StockAdaptor extends BaseAdapter { //The stocks list adaptor

    class ViewHolder {
        TextView name;
        //TextView menu;
        ImageView image; 
    }

    private LayoutInflater layoutInflater;
    private RestaurantStrings[] stocks = null; //Array of stocks
    private ListView stocksListView = null;

    public StockAdaptor(Context context) {
        super();
        layoutInflater = LayoutInflater.from(context);
    }

    public void setStockList(RestaurantStrings[] stocksinfo) {
        this.stocks = stocksinfo;// //////////////LITERALLY THIS

    }

    @Override
    public int getCount() {
        return stocks.length;
    }

    @Override
    public Object getItem(int position) {
        return stocks[position];
    }
    public RestaurantStrings[] getAll() { //Return the array of stocks
        return stocks;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder; //New holder
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.restaurant_second, null);
            holder = new ViewHolder();
            // Creates the new viewHolder define above, storing references to the children
            holder.name = (TextView) convertView.findViewById(R.id.name);
            //holder.menu = (TextView) convertView.findViewById(R.id.menu);
            holder.image = (ImageView) convertView.findViewById(R.id.image);



            if (holder.image != null) {
                if (holder.image.getDrawable() == null) {
                    new ImageDownloaderTask(holder.image, null)                                 
                    .execute(stocks[position].image); //Download the image using the image

                }
            }
            convertView.setTag(holder);
        } else {

            holder = (ViewHolder) convertView.getTag();
        }

        holder.name.setText(stocks[position].name);
        //holder.menu.setText(stocks[position].menu);

        return convertView;
    }
}

private class JsonReadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        if (URLUtil.isValidUrl(params[0])) {
            final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            final HttpGet getRequest = new HttpGet(params[0]);
            try {
                HttpResponse response = client.execute(getRequest);
                final HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    InputStream inputStream = null;
                    try {
                        inputStream = httpentity.getContent();
                        jsonResult = strFromStream(inputStream);
                        Log.i("", jsonResult);
                        return jsonResult;
                    } catch (IllegalArgumentException e) {
                        //
                    } finally {
                        httpentity.consumeContent();
                    }
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                client.close();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

        ListDrwaer();
    }

}// end async task

// build hash set for list view
public void ListDrwaer() {
    //Log.d("data from server", "data: " + jsonResult.toString());
    try {
        if (jsonResult!=null) {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
            Vector<RestaurantStrings> vstocks = new Vector<RestaurantStrings>();

            if(jsonMainNode == null)
            {
                Log.e("If is null", "jsonMainNode is null");
                return;
            }

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                RestaurantStrings stock = new RestaurantStrings();

                stock.image = jsonChildNode.getString("image");
                stock.name = jsonChildNode.optString("name");
                //stock.menu = jsonChildNode.optString("menu");

                //stock.imgPath = jsonChildNode.getString("imgPath");

               Log.e("err", stock.image + " " + stock.name);
               vstocks.add(stock);
            }

            RestaurantStrings[] stocks = new RestaurantStrings[jsonMainNode.length()];

            int stockscount = jsonMainNode.length();
            for (int n = 0; n < stockscount; n++) 
            {               
                stocks[n] = vstocks.get(n);
            }
            stockAdaptor.setStockList(stocks);
            listView.setAdapter(stockAdaptor);
        } else {
            Toast.makeText(getApplicationContext(), "Error; jsonResult null",
                    Toast.LENGTH_SHORT).show();
        }
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                Toast.LENGTH_SHORT).show();
    }
}

private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;

    public ImageDownloaderTask(ImageView imageView, View view) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params) {
        // params comes from the execute() call: params[0] is the url.
        return downloadBitmap(params[0]);
    }

    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {

                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                } else {
                    //
                }
            }

        }

    }

    Bitmap downloadBitmap(String url) {
        if(URLUtil.isValidUrl(url)){

            final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            final HttpGet getRequest = new HttpGet(url);
            try {
                HttpResponse response = client.execute(getRequest);
                final int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    Log.w("ImageDownloader", "Error " + statusCode
                            + " while retrieving bitmap from " + url);
                    return null;
                }

                final HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = null;
                    try {
                        inputStream = entity.getContent();
                        try {
                            byte[] buffer = new byte[8192];
                            int bytesRead;
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                output.write(buffer, 0, bytesRead);
                            }   
                            return BitmapFactory.decodeByteArray(output.toByteArray(), 0, output.toByteArray().length);
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();

                            return null;
                        }
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        entity.consumeContent();
                    }
                }
            } catch (Exception e) {
                getRequest.abort();
                Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
            } finally {
                if (client != null) {
                    client.close();
                }
            }
            return null;

        }
        return null;
    }

}
}

如果我尝试输入onCreate()一个setOnClickListener,您可以看到该应用提供"Unfortunately your app has stopped"

更新

<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"
tools:context=".Activity" 
android:background="#D3D3D3">

<ImageView
    android:id="@+id/image"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true" 
    />

<ListView
    android:id="@id/android:list"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:layout_toRightOf="@+id/image"

    android:layout_alignParentTop="true" 
    android:divider="@android:color/transparent"
    android:dividerHeight="5dp" >

</ListView>

</RelativeLayout>

错误

11-05 13:37:26.498: E/AndroidRuntime(1493): FATAL EXCEPTION: main
11-05 13:37:26.498: E/AndroidRuntime(1493): Process: com.reserveme, PID: 1493
11-05 13:37:26.498: E/AndroidRuntime(1493): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.reserveme/com.reserveme.Restaurants}: java.lang.NullPointerException
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.os.Handler.dispatchMessage(Handler.java:102)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.os.Looper.loop(Looper.java:136)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.app.ActivityThread.main(ActivityThread.java:5017)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at java.lang.reflect.Method.invoke(Method.java:515)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at dalvik.system.NativeStart.main(Native Method)
11-05 13:37:26.498: E/AndroidRuntime(1493): Caused by: java.lang.NullPointerException
11-05 13:37:26.498: E/AndroidRuntime(1493):     at com.reserveme.Restaurants.onCreate(Restaurants.java:69)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.app.Activity.performCreate(Activity.java:5231)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-05 13:37:26.498: E/AndroidRuntime(1493):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
11-05 13:37:26.498: E/AndroidRuntime(1493):     ... 11 more

1 个答案:

答案 0 :(得分:3)

我也在我的一个项目中使用ListView。要在listview中获取触摸/单击的位置,我已将ClickHandler注册到ListView(而不是列表中的项目)。 在你的例子中,ID等于位置,所以我认为你也可以这样做。

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            Intent intent = new Intent(Restaurants.this, RestaurantInformation.class);
            intent.putExtra("myID", position);
            startActivity(intent);
        }

    });

在新的活动中,您可以调用以下内容来获取ID:

Intent intent = getIntent();
if (intent.getExtras() != null) {
        myID = (Integer) intent.getExtras().get("myID");
    }