将asynctask值传递给mainactivity时出现上下文错误

时间:2015-10-17 09:15:20

标签: android android-asynctask android-gridview

在我的主要活动中,如果我应用此代码,我收到错误gridviewadapter() cannot be applied,这是上下文中的问题。

  GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, result);

如果我这样申请:

public MainActivity (Context context) {
        mContext = context;

    }
      GridViewAdapter adapter = new GridViewAdapter(mContext, R.layout.grid_item_layout, result);

我在logcat中遇到了这个错误

java.lang.InstantiationException: can't instantiate class com.justedhak.www.i.MainActivity; no empty constructor

我试图将asynctask arraylist值传递给mainactivity ..如何解决?

5 个答案:

答案 0 :(得分:3)

GridViewAdapter adapter = new GridViewAdapter(MainActivity.this, R.layout.grid_item_layout, result);

答案 1 :(得分:2)

删除此构造函数

public MainActivity (Context context) {
    mContext = context;
}

onCreate()

MainActivity内添加此内容
mContext = this;

答案 2 :(得分:2)

GridViewAdapter adapter = new GridViewAdapter(this,R.layout.grid_item_layout,Listitem);

答案 3 :(得分:2)

如果要传递mContext变量,请按以下方式初始化此变量:

public class MainActivity extends AppCompatActivity {
     private final Context mContext = this;

     ... // other codes such as onCreate...
}

希望这有帮助!

答案 4 :(得分:1)

不应该为MainActivity类使用构造函数。 请使用:

GridViewAdapter adapter = new GridViewAdapter(getApplicationContext(), R.layout.grid_item_layout, result);

而不是:

GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, result);