我使用以下代码从数据库中显示列表视图;但是,似乎某些布局元素无法识别..任何人都可以告诉我为什么? 这是Logcat消息: 您的内容必须具有列表视图,其id属性为android.R.id。
P.S:非常感谢任何帮助!! //以下是xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
//以下是代码
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.6.13.15/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PID= "name";
private static final String TAG_CATEGORY = "category";
private static final String TAG_CALORY = "calory";
/*private static final String TAG_UNIT = "unit";
private static final String TAG_CALORY = "calory";
private static final String TAG_CARBOHYDRATE = "carbohydrate";
private static final String TAG_CATEGORY = "category";*/
// the array was defined in PHP file
private static final String TAG_PRODUCT = "product";
// TO CONFIRM THE HASH INTO ARRAY
private ArrayAdapter<mItems> listAdapter;
private mItems[] itemss;
private ListView mainListView;
ArrayList<mItems> planetList = new ArrayList<mItems>();
// products JSONArray
JSONArray products = null;
ArrayList<String> checked = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
mainListView = (ListView)findViewById(R.id.list);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
mainListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mItems planet = listAdapter.getItem(position);
planet.toggleChecked();
SelectViewHolder viewHolder = (SelectViewHolder) view
.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
//*********** OUR CODE****************
// getting values from selected ListItem
/*String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);*/
//*********** OUR CODE****************
}
});
listAdapter = new SelectArralAdapter(this, planetList);
mainListView.setAdapter(listAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, 1, Menu.NONE, "Products");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case 1:
for (int i = 0; i < checked.size(); i++) {
Log.d("pos : ", "" + checked.get(i));
}
break;
}
return super.onOptionsItemSelected(item);
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
Log.d("NUN complete","tyt");
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading items. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
itemss = (mItems[]) getLastNonConfigurationInstance();
int ii=0;
while( ii < products.length()){
JSONObject c = products.getJSONObject(ii);
String category = c.getString(TAG_CATEGORY );
//Double dd =c.getDouble(TAG_CALORY);
String dd = c.getString(TAG_CALORY );
//itemss[ii]= dd;
planetList.add(new mItems(dd));
ii++;
// Log.d("d ", TextUtils.join(",", d));
}
// products found
// Getting Array of Products
Log.d("All Products: ", json.toString());
products = json.getJSONArray(TAG_PRODUCT);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID); // also name
String category = c.getString(TAG_CATEGORY );
// NO NEED FOR THEM !!
/*
String unit = c.getString(TAG_UNIT );
String category = c.getString(TAG_CATEGORY );
String calory = c.getString(TAG_CALORY );
String carbohydrate = c.getString(TAG_CARBOHYDRATE ); */
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_CATEGORY, category);
//map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
Log.d("All Products: ", json.toString());
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
/*
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
*
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_CATEGORY},
new int[] { R.id.pid, R.id.category});
// updating listview
setListAdapter(adapter);
}
});
}
*/
}
private static class mItems {
private String name = "";
private boolean checked = false;
private double calory = 0.0;
public mItems() {
}
public mItems(String name) {
this.name = name;
}
public mItems(String name, boolean checked) {
this.name = name;
this.checked = checked;
}
public String getName() {
return name;
}
public double getCalroy() {
return calory;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name;
}
public void toggleChecked() {
checked = !checked;
}
}
// New class
private static class SelectViewHolder {
private CheckBox checkBox;
private TextView textView;
public SelectViewHolder() {
}
public SelectViewHolder(TextView textView, CheckBox checkBox) {
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
// New class
private static class SelectArralAdapter extends ArrayAdapter<mItems> {
private LayoutInflater inflater;
public SelectArralAdapter(Context context, List<mItems> planetList) {
super(context, R.layout.list_item, R.id.rowTextView, planetList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Planet to display
mItems planet = (mItems) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
TextView here;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.rowTextView);
checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new SelectViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
mItems planet = (mItems) cb.getTag();
planet.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
SelectViewHolder viewHolder = (SelectViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Planet it is displaying, so that we can
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display planet data
checkBox.setChecked(planet.isChecked());
textView.setText(planet.getName());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return itemss;
}
}
答案 0 :(得分:2)
您使用的是ListActivity而不是普通的Activity,您的视图应该有默认的android:id/list:
。
将xml中的列表视图更改为
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
检查此ListActivity Tutorial以获取更多信息
答案 1 :(得分:0)
已成为
mainListView = (ListView)findViewById(R.id.list);
使用
mainListView = getListView()