2

我正在开发一个 android 应用程序,它将简单数据作为 NAME 发送到网络服务器,并且可以从服务器检索 NAMES。使用 php 和 mysql 进行 web 服务。目前我已经完成了从 web 到 android 的发送和接收数据。现在我想将我从我的网站数据库中获得的名称显示到我的 android listview 中。以下是我的代码

public class allProducts 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.0.2.2/dinein/Model/getName.php";

// JSON Node names

private static final String TAG_NAME = "name";
//private static final String TAG_SUCCESS = "success";
//private static final String TAG_PRODUCTS = "products";
//private static final String TAG_PID = "pid";

// products JSONArray
JSONArray products = null;
static ArrayList<String> listItems=new ArrayList<String>();

//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.products);


    // 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
   /* lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // 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);
        }
    });*/

}

// 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);
    }

}

 class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(allProducts.this);
        pDialog.setMessage("Loading products. 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, "POST", params);

        // Check your log cat for JSON reponse




            // Checking for SUCCESS TAG
            int success = 1;

            if (success == 1) {
                Iterator<String> iter = json.keys();
                Object value=null;
                while (iter.hasNext()) {
                    String key = iter.next();
                    try {
                         value = json.get(key);


                    } catch (JSONException e) {
                        // Something went wrong!
                    }
                }

              }



        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(
                        allProducts.this, productsList,
                        R.layout.name_list, new String[] {TAG_NAME},
                        new int[] { R.id.pid, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}

我想用列表视图在我的活动中显示我的数据。这是我的 xml 文件的样子

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

和另一个

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
    android:id="@+id/pid"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:visibility="gone" />

</RelativeLayout>
4

2 回答 2

1

如果您正在扩展,ListActivity那么 ListView id 必须是android:id="@+id/android:list"。将您的 xml 更改为:

<ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

因为onPostExecute总是执行Main UI Thread然后不需要用于从更改您的 onPostExecute 方法代码的方法runOnUiThread更新 UI为:onPostExecutedoInBackground

protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();

        ListAdapter adapter = new SimpleAdapter(
                        allProducts.this, productsList,
                        R.layout.name_list, new String[] {TAG_NAME},
                        new int[] { R.id.pid, R.id.name });

               ListView listview = allProducts.this.getListView();
                // updating listview
                listview.setListAdapter(adapter);
    }
于 2013-03-07T12:19:20.997 回答
0

我在您的代码中发现了两个错误。

首先,您无法在列表中看到任何内容,因为该行的 textview 可见性设置为 GONE。所以,改变它。

<TextView
     android:id="@+id/pid"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
    <!-- android:visibility="gone" -->
 />

其次,您的列表行只有一个 field(R.id.pid),并且您的代码正在尝试设置两个 fields(R.id.pid, R.id.name)。很快,您将有两个更改它,或者添加另一个带有android:id ="@+id/name"或删除适配器的 R.id.name 的文本视图。

这是一个仅使用您的 pid 字段的示例:

   List<Map<String, String>> productsList = new ArrayList<Map<String,String>>();
   HashMap<String, String> p1 = new HashMap<String, String>();
   p1.put("key", "product1");
   HashMap<String, String> p2 = new HashMap<String, String>();
   p2.put("key", "product2");
   HashMap<String, String> p3 = new HashMap<String, String>();
   p3.put("key", "product3");
   productsList.add(p1);
   productsList.add(p2);
   productsList.add(p3);


   ListAdapter adapter = new SimpleAdapter(this, productsList,
            R.layout.row, new String[] {"key"},
            new int[] { R.id.pid});

   ListView listview = getListView();
   listview.setAdapter(adapter);
于 2013-03-07T13:35:02.693 回答