android - 尝试在 AsyncTask 中填充 ListView 时出现 ClassCastException

标签 android listview android-asynctask

出现错误:java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity

当尝试在 AsyncTaskonPostExecute() 中填充 ListView 时。

为什么我会收到这个?

Activity

public class NotificationsActivity extends Activity {

private static final String FILENAME_NOTIFICATIONS = "notifications.json";

ListView listView;
NotificationsAdapter adapter;
private JSONReader reader;
private ArrayList<Notification> notificationsArray;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notifications);
    getActionBar().setTitle("");

    reader = new JSONReader(getApplicationContext());

    notificationsArray = new ArrayList<Notification>();

    listView = (ListView)findViewById(R.id.notifications_listview);

    if (Utilities.isNetworkAvailable(getApplicationContext())) { 
        new UpdateNotifications().execute();
    }
    else {
        Toast.makeText(getApplicationContext(), "Network Error: No Connectivity", Toast.LENGTH_SHORT).show();

        if (Utilities.checkIfFileExists(getApplicationContext(), FILENAME_NOTIFICATIONS)) {
            createNotificationsArray();
        }
        else {
            Toast.makeText(getApplicationContext(), "No files found locally. Please connect to the internet and try again.", Toast.LENGTH_LONG).show();
        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.notifications, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_update:
        if (Utilities.isNetworkAvailable(this)) {
            new UpdateNotifications().execute();
        }
        else {
            Toast.makeText(getApplicationContext(), "Network Error: No Connectivity", Toast.LENGTH_SHORT).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

private void createNotificationsArray() {
    try { 
        reader.readFromInternal(FILENAME_NOTIFICATIONS);
        notificationsArray = reader.getNotificationsArray();
    } 
    catch (IOException e) { e.printStackTrace(); }
}

private class UpdateNotifications extends AsyncTask<Void, Void, Void> {

    ProgressDialog progressDialog;

    protected void onPreExecute() {
        progressDialog = new ProgressDialog(NotificationsActivity.this);
        progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("Updating notifications. Please wait.");
        progressDialog.show();
        progressDialog.setCanceledOnTouchOutside(false);
    }

    protected Void doInBackground(Void... params) {
        HTTPGetRequest getRequest = new HTTPGetRequest();
        JSONWriter writer = new JSONWriter(getApplicationContext());

        // Updates local JSON file containing notifications
        String notificationsJsonString = "";
        notificationsJsonString = getRequest.getNotifications();

        try { writer.writeToInternal(FILENAME_NOTIFICATIONS, notificationsJsonString); } 
        catch (IOException e) { e.printStackTrace(); }

        createNotificationsArray();

        Log.v("SIZE", Integer.toString(notificationsArray.size()));

        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        progressDialog.dismiss();

        listView = (ListView)findViewById(R.id.notifications_listview);
        adapter = new NotificationsAdapter(getApplicationContext(), R.layout.listview_notification_row, notificationsArray);
        listView.setAdapter(adapter);

        return;
    }
}

数组适配器

public class NotificationsAdapter extends ArrayAdapter<Notification> {

private Context context;
private int layoutResourceId;
private ArrayList<Notification> notifications;

public NotificationsAdapter(Context context, int layoutResourceId, ArrayList<Notification> notifications) {
    super(context, layoutResourceId, notifications);
    this.context = context;
    this.layoutResourceId = layoutResourceId;
    this.notifications = notifications;
}

private static class ViewHolder {
    private TextView notifyName;
    private TextView checklist;
    private TextView stepName;
    private TextView note;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        convertView = inflater.inflate(layoutResourceId, parent, false);

        holder = new ViewHolder();
        holder.notifyName = (TextView)convertView.findViewById(R.id.notify_name);
        holder.checklist = (TextView)convertView.findViewById(R.id.checklist_name);
        holder.stepName = (TextView)convertView.findViewById(R.id.step_name);
        holder.note = (TextView)convertView.findViewById(R.id.notification_note);

        convertView.setTag(holder);
    } 
    else {
        holder = (ViewHolder)convertView.getTag();
    }

    String notifyName = notifications.get(position).getNotifyName();
    String checklist = notifications.get(position).getChecklist();
    String stepName = notifications.get(position).getStepName();
    String note = notifications.get(position).getNote();

    holder.notifyName.setText(notifyName);
    holder.checklist.setText(checklist);
    holder.stepName.setText(stepName);
    holder.note.setText(note);

    return convertView;
}

堆栈跟踪

02-04 21:13:01.713: E/AndroidRuntime(30652): java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
02-04 21:13:01.713: E/AndroidRuntime(30652):    at com.medusa.checkit.android.NotificationsAdapter.getView(NotificationsAdapter.java:38)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.AbsListView.obtainView(AbsListView.java:2453)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.ListView.makeAndAddView(ListView.java:1775)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.ListView.fillDown(ListView.java:678)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.ListView.fillFromTop(ListView.java:739)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.ListView.layoutChildren(ListView.java:1628)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.AbsListView.onLayout(AbsListView.java:2288)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.View.layout(View.java:13957)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewGroup.layout(ViewGroup.java:4374)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1655)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1513)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1426)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.View.layout(View.java:13957)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewGroup.layout(ViewGroup.java:4374)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.View.layout(View.java:13957)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewGroup.layout(ViewGroup.java:4374)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1655)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1513)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1426)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.View.layout(View.java:13957)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewGroup.layout(ViewGroup.java:4374)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.View.layout(View.java:13957)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewGroup.layout(ViewGroup.java:4374)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2003)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1824)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4553)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.Choreographer.doFrame(Choreographer.java:525)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.os.Handler.handleCallback(Handler.java:615)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.os.Handler.dispatchMessage(Handler.java:92)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.os.Looper.loop(Looper.java:137)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at android.app.ActivityThread.main(ActivityThread.java:4950)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at java.lang.reflect.Method.invokeNative(Native Method)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at java.lang.reflect.Method.invoke(Method.java:511)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
02-04 21:13:01.713: E/AndroidRuntime(30652):    at dalvik.system.NativeStart.main(Native Method)

最佳答案

在适配器的 getView() 中,更改此代码

LayoutInflater inflater = ((Activity) context).getLayoutInflater();

LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

关于android - 尝试在 AsyncTask 中填充 ListView 时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21569159/

相关文章:

java - Volley JSONObject POST 请求没有响应

android - 更改工具栏中汉堡包图标的大小?

java - 在android中的 ListView 中对连接的wifi进行排序

java - 如何重用 Dagger2 注入(inject)的 AsyncTask?

android - 实现 AsyncTask 的技巧

android - 使用 asyncTask、接口(interface)和 fragment 时出现 NullPointerException

android - 法拉盛织物/Crashlytics 非致命和事件

c# - 我可以在 Xamarin Forms 上检查设备中的可用存储空间吗?

android - 如何显示/隐藏 ListView 元素?

android - 如何在android中的listview下方添加footbar按钮