runnable ListViewAdapter导致“无法转换为android.content.Context”错误

时间:2014-09-22 03:21:05

标签: java android listview adapter

我目前正在创建一个Android GoogleMaps应用,并在在线服务器上的数据库中存储了一个Locations列表。我已成功完成它们,现在我想使用Actionbar搜索视图创建一个用户可以搜索的列表视图,它会将当前加载的数据更改为仅显示链接到当前所选位置的数据。

然而,由于我在调用它的位置,在将ListViewAdapter代码更改为runnable之后尝试将arraylist放入适配器时,我遇到了无法转换为android.content.Context的错误。我的主要活动代码如下:

TownSelector ts;
ListView townList;
ListViewAdapter townAdapter;  <---set variable for adapter here
String[] townID;    
String[] townName;
ArrayList<TownSelector> arraylist = new ArrayList<TownSelector>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //setContentView(R.layout.search);
    setUpMapIfNeeded();

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

    // Locate the ListView in listview_main.xml
    townList = (ListView) findViewById(R.id.listview);

}

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

    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> paramsLocations = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject jsonLocations = jParser.makeHttpRequest(url_all_locations, "GET", paramsLocations);


        //Get all offer
        if(jsonLocations != null)
        {
            // Check your log cat for JSON reponse
            Log.d("All Locations: ", jsonLocations.toString());
            try {

                // Checking for SUCCESS TAG
                int success = jsonLocations.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Offers
                    locations = jsonLocations.getJSONArray(TAG_LOCATIONS);

                    // looping through All Offers
                    for (int i = 0; i < locations.length(); i++) {
                        JSONObject c = locations.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_LID);
                        String locationName = c.getString(TAG_LNAME);

                        // creating new HashMap
                        HashMap<String, String> locationsListMap = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        locationsListMap.put(TAG_LID, id);
                        locationsListMap.put(TAG_LNAME, locationName);

                        // adding HashList to ArrayList
                        locationList.add(locationsListMap);

                    }
                }                   
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return null;            
    }

    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 map marker
                 * */

               //TODO setMapMarkers

                townID = new String[locationList.size()];
                townName = new String[locationList.size()];
                for(int l = 0; l <= (locationList.size() - 1); l++)
                {
                    Log.d("Hello", "location loop");
                    Log.d("Hello", locationList.get(l).toString().split("Location_ID=")[1].split(",")[0]);                      
                    townID[l] = locationList.get(l).toString().split("Location_ID=")[1].split(",")[0];

                    Log.d("Hello", locationList.get(l).toString().split("Location_Name=")[1].split(",")[0].replace("}",""));
                    townName[l] = locationList.get(l).toString().split("Location_Name=")[1].split(",")[0].replace("}","");
                }

                for (int i = 0; i < townID.length; i++) 
                {
                    ts = new TownSelector(townID[i], townName[i]);
                    // Binds all strings into an array
                    arraylist.add(ts);                      
                }

                // Pass results to ListViewAdapter Class
                townAdapter = new ListViewAdapter(this, arraylist);  <--Create new instant of adapter here
                // Binds the Adapter to the ListView
                townList.setAdapter(townAdapter); //This is the line that causes a crash

            }
        }); 
    }    
}

ListViewAdapter代码:

// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<TownSelector> locationlist = null;
private ArrayList<TownSelector> arraylist;

public ListViewAdapter(Runnable runnable, List<TownSelector> locationlist) {
    mContext = (Context) runnable;
    this.locationlist = locationlist;
    inflater = LayoutInflater.from(mContext);
    this.arraylist = new ArrayList<TownSelector>();
    this.arraylist.addAll(locationlist);
}

我在找到此stackflow问题后将ListViewAdapter代码更改为以下内容android callback fails in fragment fails cannot be cast to android.content.Context

public ListViewAdapter(Context context,Runnable runnable, List<TownSelector> locationlist) {
    mContext = context;
    this.runnable =  runnable;
    this.locationlist = locationlist;
    inflater = LayoutInflater.from(mContext);
    this.arraylist = new ArrayList<TownSelector>();
    this.arraylist.addAll(locationlist);
}

错误callstack:

    09-22 03:58:03.467: E/AndroidRuntime(15586): FATAL EXCEPTION: main
    09-22 03:58:03.467: E/AndroidRuntime(15586): Process: biz.nickbullcomputing.bevnav, PID: 15586
    09-22 03:58:03.467: E/AndroidRuntime(15586): java.lang.ClassCastException: biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo$1 cannot be cast to android.content.Context
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at biz.nickbullcomputing.bevnav.ListViewAdapter.<init>(ListViewAdapter.java:25)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo$1.run(MainActivity.java:409)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at android.app.Activity.runOnUiThread(Activity.java:4794)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo.onPostExecute(MainActivity.java:376)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo.onPostExecute(MainActivity.java:1)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at android.os.AsyncTask.finish(AsyncTask.java:632)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at android.os.Handler.dispatchMessage(Handler.java:102)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at android.os.Looper.loop(Looper.java:157)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at android.app.ActivityThread.main(ActivityThread.java:5867)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at java.lang.reflect.Method.invokeNative(Native Method)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at java.lang.reflect.Method.invoke(Method.java:515)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
    09-22 03:58:03.467: E/AndroidRuntime(15586):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:4)

asyncTask townAdapter = new ListViewAdapter(this, arraylist);中的这一部分不正确。你的编辑应该显示错误。你需要传递YourActivityName.this这就是发送LoadAllInfo作为错误的上下文