Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

android - java.lang.InstantiationException: class com.e has no zero argument constructor

I am getting this error

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

This is the below class :

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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to define a no-args constructor, just as the error says:

public Search() {
    // No args constructor
}

The context that you need for your adapter is the Activity itself, you don't need to get it via the constructor. Just use this, since you are already in the context of an activity:

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

And then you can drop the overloaded constructor that you defined for your custom activity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...