java.lang.InstantiationException:类com.e没有零参数构造函数

时间:2016-02-13 13:06:48

标签: android

我收到此错误

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.e.www.i/com.e.www.i.Search}: java.lang.InstantiationException: class com.e.www.i.Search has no zero argument constructor

这是以下课程:

public class Search extends Activity {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;

    private RecyclerView mRecyclerView1;
    private RecyclerView.Adapter mAdapter1;
    Context mContext;

    public Search(Context context) {

        mContext = context; // I guess the error is here, but I need to define context for below MyAdapter
    }
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(
                new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false));
        mAdapter = new MyAdapter(getDataSet(),mContext);
        mRecyclerView.setAdapter(mAdapter);

      }

private ArrayList<String> getDataSet() {
        ArrayList results = new ArrayList<DataObject>();
        for (int index = 0; index < 5; index++) {
            String obj = new String("User " + index);
            results.add(index, obj);
        }
        return results;
    }

4 个答案:

答案 0 :(得分:6)

您需要定义 no-args 构造函数,就像错误所示:

public Search() {
    // No args constructor
}

适配器所需的contextActivity本身,您无需通过构造函数获取它。只需使用this,因为您已经在活动的上下文中:

mAdapter = new MyAdapter(getDataSet(), this);

然后您可以删除为自定义活动定义的重载构造函数。

答案 1 :(得分:2)

删除Search(..) constructor,然后将conetext传递给adapter,如

 mAdapter = new MyAdapter(getDataSet(),Search.this);

您已经在Search Activity

答案 2 :(得分:2)

在搜索中,您创建了构造函数

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

现在,由于你有一个用户定义的构造函数,你的编译器不会为你提供任何默认的构造函数,所以你也需要自己定义一个无参数的构造函数。

public Search() {
    // Constructor body
}

答案 3 :(得分:0)

如果参数是必须的,例如IntentService

public BaseIntentService() {
    super("IntentService");
}

否则

public Search() {
    // Constructor body
}