簡體   English   中英

可運行的ListViewAdapter導致“無法轉換為android.content.Context”錯誤

[英]runnable ListViewAdapter causes a “cannot be cast to android.content.Context” error

我目前正在創建一個Android GoogleMaps應用,並且已在在線服務器上的數據庫中存儲了位置列表。 我成功地完成了這些操作,現在我想使用操作欄搜索視圖創建一個列表視圖,用戶可以搜索該列表視圖,它將更改當前加載的數據以僅顯示鏈接到當前所選位置的數據。

但是我遇到錯誤,由於我在哪里將ListViewAdapter代碼更改為可運行之后,嘗試將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);
}

找到此堆棧流問題后,我將ListViewAdapter代碼更改為以下內容android回調在片段中失敗無法將失敗轉換為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);
}

錯誤的調用棧:

    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)

您asyncTask中的這一部分townAdapter = new ListViewAdapter(this, arraylist); 是不正確的。 您的編輯器應該顯示錯誤。 您需要傳遞YourActivityName.this只是將LoadAllInfo作為上下文發送,這是錯誤的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM