2014-11-25 33 views
0

我都是新来的java和android。我试图创建一个简单的Android应用程序使用MySQL作为后端数据库。我用下面的教程链接在两个地方该方法setListAdapter(ListAdapter)是undefined的类型

ListView lv = getListView(); and setListAdapter(adapter) 

错误说的方法并不为这种类型定义创建一个

http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

但在底部,我看到错误的类。我无法弄清楚如何解决它。任何人都可以在这里帮我解决这个问题。由于

AllProductsActivity.java 
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.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 

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://api.androidhive.info/android_connect/get_all_products.php"; 

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

// products JSONArray 
JSONArray products = null; 

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

    // Hashmap for ListView 
    productsList = new ArrayList<HashMap<String, String>>(); 

    // Loading products in Background Thread 
    new LoadAllProducts().execute(); 

    // HERE I SEE THE ERROR for not defined for this type 
    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); 
    } 

} 

/** 
* 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 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, "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) { 
       // products found 
       // Getting Array of Products 
       products = json.getJSONArray(TAG_PRODUCTS); 

       // 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); 
        String name = c.getString(TAG_NAME); 

        // 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_NAME, name); 

        // adding HashList to ArrayList 
        productsList.add(map); 
       } 
      } 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_NAME}, 
         new int[] { R.id.pid, R.id.name }); 
       // HERE I SEE THE ERROR FOR NOT DEFINED 
       setListAdapter(adapter); 
      } 
     }); 
    } 

} 
+0

你不需要'runOnUiThread'在'onPostExecute',如果删除您的代码将正常工作 – 2014-11-25 06:06:16

回答

0

setListAdapter(适配器)是ListActivity不Asyank任务

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.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 

public class AllProductsActivity extends ListActivity { 

ListAdapter adapter; 
// 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://api.androidhive.info/android_connect/get_all_products.php"; 

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

// products JSONArray 
JSONArray products = null; 

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

    productsList = new ArrayList<HashMap<String, String>>(); 
    ListView lv = getListView(); 
    adapter = new SimpleAdapter(
         AllProductsActivity.this, productsList, 
         R.layout.list_item, new String[] { TAG_PID, 
           TAG_NAME}, 
         new int[] { R.id.pid, R.id.name }); 
    setListAdapter(adapter); 

    // Loading products in Background Thread 
    new LoadAllProducts().execute(); 

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

} 

/** 
* 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 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, "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) { 
       // products found 
       // Getting Array of Products 
       products = json.getJSONArray(TAG_PRODUCTS); 

       // 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); 
        String name = c.getString(TAG_NAME); 

        // 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_NAME, name); 

        // adding HashList to ArrayList 
        productsList.add(map); 
       } 
      } 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(); 
     adapter.notifyDataSetChanged(); 

    } 

} 
+0

感谢Naveen,我更新了像您提供的一些setListAdapter(适配器)的修改代码;到lv.setListAdapter(适配器)来删除它的错误。但是,它显示错误在线执行后的adapter.notifyDataSetChanged(); “(无法解析适配器” – 2014-11-25 11:12:42

+0

)的消息我更新了我的代码,请检查代码 – 2014-11-25 11:16:54

+0

必须在postexecute方法((BaseAdapter)适配器)中进行以下修改.notifyDataSetChanged();去除错误。 – 2014-11-25 16:55:20

0

不要使用getListView(),你必须实例化这样的 -

ListView lv = new ListView(YourActivityName.this); 

ListView lv = (ListView)findViewById(R.id.yourListView); 

如果你已经在xml布局中声明了这样的listveiw。

其次,

为什么你正在使用runOnUIthread?无论如何,在UI线程上运行OnPostExecute。所以这应该解决你的问题。

+0

你好Darpan,谢谢你提供正确的语法。我读过这个适配器必须在UI线程上运行,但发现自Jelli Bean开始,它是由OS自动完成的。我删除了runOnUIthread块。 – 2014-11-25 11:15:03

+0

这是否解决了您的问题? – Darpan 2014-11-25 13:04:02

+0

不完全,但它的一部分:) – 2014-11-25 17:52:53

0

Donot编写runonUiThread(),因为作用域仍处于异步任务中,可能可以调用另一个方法并将代码放入该块。

`onPostExecute(字符串结果){

someOtherMethod(结果);

}`

` 私人无效someOtherMethod(字符串URL){

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

    setListAdapter(adapter); 

} `

相关问题