2016-02-13 47 views
0

我收到此错误java.lang.InstantiationException:类COM.E没有无参数的构造

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; 
    } 
+1

尝试创建一个无参数的构造函数的 –

+0

可能的复制[java.lang.InstantiationException:类没有无参数的构造函数(http://stackoverflow.com/questions/29947038/java-lang-instantiationexception-class -has-no-zero-argument-constructor) – sud007

+0

其旧问题 – Moudiz

回答

3

您需要定义一个没有-args构造,就像错误说:

public Search() { 
    // No args constructor 
} 

context你需要的适配器是Activity本身,你不需要通过构造函数来获取它。只要使用this,因为你已经在一个活动的背景下:

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

然后你就可以丢弃您的自定义活动中定义的重载构造函数。

+0

如何定义上下文以将其过滤到myAdapter? – Moudiz

+0

@Moudiz检查我的更新。 –

+0

啊..我正在这样做'(getDataset(),this.Search)'我虽然'这,搜索'是一样的'这个' – Moudiz

2

删除Search(..) constructor,只是通过conetextadapter

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

因为你已经在Search Activity

1

在搜索时,您所创建的构造

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

现在,既然你有用户定义的构造函数,你的编译器不提供任何默认的构造函数,所以你需要定义ap你自己也没有参数的构造函数。

public Search() { 
    // Constructor body 
} 
相关问题