Issue
I have a class constructor. inside that I want to use string resources using getResources. when I want to run the app it produces an error tells "Unfortunately myProject has stopped".
public EhsanAdapter(Context c) {
context = c;
size = 5;
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
}
What's wrong with this? when I comment the line with getresource command, I have no error.
This is whole class:
package com.example.listviewba;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
class SingleRow{
String title;
String description;
int image;
public SingleRow(String title,String description,int image) {
this.title = title;
this.description=description;
this.image=image;
}
}
public class EhsanAdapter extends BaseAdapter{
Context context;
int size;
ArrayList<SingleRow> list;
public EhsanAdapter(Context c) {
context = c;
size = 5;
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
}
@Override
public int getCount() {
return size;
}
@Override
public Object getItem(int arg0) {
return null;
}
@Override
public long getItemId(int arg0) {
return 0;
}
public void addView(){
size++;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
RowView view = null;
if (convertView == null){
view = new RowView(this.context);
}
else{
view = (RowView) convertView;
}
view.setLeftText("Shit");
view.setRightText("Fuck");
return view;
}
}
and this is how I'm calling the class:
package com.example.listviewba;
public class MainActivity extends Activity {
EhsanAdapter adapter = new EhsanAdapter(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView lv = (ListView) findViewById(R.id.listview1);
lv.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Solution
Move EhsanAdapter adapter = new EhsanAdapter(this);
down like this:
final ListView lv = (ListView) findViewById(R.id.listview1);
EhsanAdapter adapter = new EhsanAdapter(this);
lv.setAdapter(adapter);
You can't declare it before onCreate
because your Context
will be null
at this time.
Or if you want your EhsanAdapter
to be an instance variable, you can declare it in the class like private EhsanAdapter adapter;
and in onCreate
you initiate like adapter = new EhsanAdapter(this);
Answered By - Carnal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.