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;
}
public class InstantiationException extends ReflectiveOperationException Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to:
A non-static inner class cannot be registered via the AndroidManifest.xml. You can either: Register it dynamically as outlined in this thread, and remove the empty constructor. Make your inner class static, and register it in the AndroidManifext.xml. Aha, turns out that is the problem.
The instantiation can fail for a variety of reasons including but not limited to: Constructs an InstantiationException with no detail message. Constructs an InstantiationException with the specified detail message.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With