Custom list starting new activity? - java

I have built a customized list item to replace the android's simple list item by inflating each list item. The customized list is working and it consists of an image view and a text view.
My problem is, when I try to launch a new activity after a list item is clicked nothing happens even the app wont crash. So, is there a way to launch an activity using list view???
public class activityone extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitylayout);
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, R.id.textView1,
getResources().getStringArray(R.array.names)));
}
public void onListItemClick(ListView l, View v, int position,
long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
if(getSelectedItemPosition() == 0){
Intent intent = new Intent(activityone.this,no1.class);
startActivity(intent);
}
.
.
.
.
}
private class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, parent, false);
String[] items = getResources().getStringArray(R.array.names);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("john")){
iv.setImageResource(R.drawable.john);
}
.
.
.
.
return row;
}
}
}
And here is the no1 class
public class no1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.name_profile);
CharSequence t1 = "Name: john";
CharSequence t2 = "Age: 31";
CharSequence t3 = "Nationality: Saudi";
CharSequence t4 = "Number: 765646454";
ImageView iv = (ImageView) findViewById(R.drawable.imageView1);
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
TextView tv3 = (TextView) findViewById(R.id.textView3);
TextView tv4 = (TextView) findViewById(R.id.textView4);
iv.setImageResource(R.drawable.john);
tv1.setText(t1);
tv2.setText(t2);
tv3.setText(t3);
tv4.setText(t4);
}
}
And yes my activities are added to the manifest xml file.
Thanks for your help.
#Vineet Shukla I don't know how to do this i placed a break point but I couldn't debug i am new to eclipse environment could you explain more please
#Divyesh
I edited the code and the app now crashes when i press a list item here is the Logcat trace
09-17 10:10:57.686: ERROR/AndroidRuntime(365): FATAL EXCEPTION: main
09-17 10:10:57.686: ERROR/AndroidRuntime(365): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abc.act/com.abc.act.no1}: java.lang.NullPointerException
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.os.Looper.loop(Looper.java:123)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at java.lang.reflect.Method.invokeNative(Native Method)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at java.lang.reflect.Method.invoke(Method.java:521)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at dalvik.system.NativeStart.main(Native Method)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): Caused by: java.lang.NullPointerException
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at com.abc.act.no1.onCreate(no1.java:31)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): ... 11 more

You're not effectively using this API, you should switch to SimpleAdapter because handles more complex List Item layouts and data bindings. Instead of creating intractable branch statements you need to use the underlying data of the list effectively.

Related

Android CursorAdapter giving java.lang.NullPointerException error

I am having a few issues running my custom CursorAdapter in my application. According to my logcat, the error I get:
11-08 06:41:03.228 6109-6109/? W/System.err? java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
11-08 06:41:03.229 6109-6109/? W/System.err? at com.app.name.MyActivity.onCreate(MyActivity.java:71)
11-08 06:41:03.231 6109-6109/? E/AndroidRuntime? FATAL EXCEPTION: main
occurs at line 71 which sets the adapter (obj.setAdapter(myAdapter)). Initially I thought my database data retrieve function (Cursor chatCursor = mydb.selectConversation(msgId);) did not return any data but after testing it with the chatCursor.getCount() function, I realized that was not the case. Kindly assist me in solving this issue. Below are the codes for my activity, adapter and logcat. Thanks in advance.
MyAdapter.java
public class MyAdapter extends CursorAdapter {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public MyAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.chat_left, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView user = (TextView) view.findViewById(R.id.reply_user);
TextView msg = (TextView) view.findViewById(R.id.reply_msg);
String theTime = cursor.getString(cursor.getColumnIndexOrThrow("message_id"));
String theMessage = cursor.getString(cursor.getColumnIndexOrThrow("message"));
user.setText(theTime);
msg.setText(String.valueOf(theMessage));
}
}
MyActivity.java
public class MyActivity extends ListActivity {
//Utils Class
Utils util;
final Context context = this;
private ProgressBar dialog;
ListView obj;
DBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
util = new Utils(this);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
final Integer msgId = extras.getInt("id");
obj = (ListView) findViewById(R.id.list);
Cursor chatCursor = mydb.selectConversation(msgId);
MyAdapter myAdapter = new MyAdapter(this, chatCursor);
obj.setAdapter(myAdapter);
}
}
logcat
11-08 06:41:03.228 6109-6109/? W/System.err? java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
11-08 06:41:03.229 6109-6109/? W/System.err? at com.app.name.MyActivity.onCreate(MyActivity.java:71)
11-08 06:41:03.231 6109-6109/? E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.name/com.app.name.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2351)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.app.name.MyActivity.onCreate(MyActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1150)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
11-08 06:41:03.238 559-832/? W/ActivityManager? Force finishing activity com.app.name/.MyActivity
11-08 06:41:03.742 559-574/? W/ActivityManager? Activity pause timeout for ActivityRecord{42e71938 u0 com.app.name/.MyActivity}
Take a look to your activity_view.xml. Probably the listview ID isn't "list" as you state when you try to find it with findViewById(R.layout.list).

listview row color dependent on value from DB

Ok, I have app that store data about Items in SQLite database.
Items are listed by name and presented on main activity. Every item has some details and there is detail about owner. I want set 2 colors of rows on list. 1 color when i'm owner (i get true from DB), and 2nd color for other case.
public class BHItemsAdapter extends ArrayAdapter<BHItem> {
private Activity context;
private List<BHItem> bhItems;
private MainActivity cbOwn ;
public BHItemsAdapter(Activity context, List<BHItem> bhItems) {
super(context, R.layout.bhitems_list_item, bhItems);
this.context = context;
this.bhItems = bhItems;
}
static class ViewHolder {
public TextView tvBHItemDescription;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
View rowView = convertView;
if(rowView == null) {
LayoutInflater layoutInflater = context.getLayoutInflater();
rowView = layoutInflater.inflate(R.layout.bhitems_list_item, null, true);
viewHolder = new ViewHolder();
viewHolder.tvBHItemDescription = (TextView) rowView.findViewById(R.id.tvBHItemDescription);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
BHItem task = bhItems.get(position);
/*line 49*/ if (cbOwn.onCheckboxClicked1())
{
rowView.setBackgroundColor(0x30ff2020);
}
else {
rowView.setBackgroundColor(0x30aaffff);
}
viewHolder.tvBHItemDescription.setText(task.getItem());
return rowView;
}
}
Even when I'm sending true or false i'm getting nullpointerexeption
//this is from main activity
public boolean onCheckboxClicked1() {
return true;
}
private void fillListViewData() {
bhDbAdapter = new DbAdapter(getApplicationContext());
bhDbAdapter.open();
getUncompletedTasks();
getCompletedTasks();
bhItemsAdapter = new BHItemsAdapter(this, bhItemList);
lvTodos.setAdapter(bhItemsAdapter);
}
private void initUiElements() {
etItem = (EditText) findViewById(R.id.etItem);
etDescription = (EditText) findViewById(R.id.etDescription);
etOwner = (EditText) findViewById(R.id.etOwner);
etBorrower = (EditText) findViewById(R.id.etBorrower);
tvItem = (TextView) findViewById(R.id.tvItem);
tvDescription = (TextView) findViewById(R.id.tvDescription);
tvOwner = (TextView) findViewById(R.id.tvOwner);
tvBorrower = (TextView) findViewById(R.id.tvBorrower);
tvCategory = (TextView) findViewById(R.id.tvCategory);
tvReturndate = (TextView) findViewById(R.id.tvReturndate);
lvTodos = (ListView) findViewById(R.id.lvTodos);
lvArchive = (ListView) findViewById(R.id.lvArchive);
llItemAdder = (LinearLayout) findViewById(R.id.llItemAdder);
llIAButtons = (LinearLayout) findViewById(R.id.llIAButtons);
llIAEditButtons = (LinearLayout) findViewById(R.id.llIAEditButtons);
llControlButtons = (LinearLayout) findViewById(R.id.llControlButtons);
llNewTaskButtons = (LinearLayout) findViewById(R.id.llNewTaskButtons);
llItemDetails = (LinearLayout) findViewById(R.id.llItemDetails);
dpReturndate = (DatePicker) findViewById(R.id.dpReturndate);
ivEditImage = (ImageView) findViewById(R.id.ivEditImage);
ivDetailImage = (ImageView) findViewById(R.id.ivDetailImage);
cbReturned = (CheckBox) findViewById(R.id.cbReturned);
spCategory = (Spinner) findViewById(R.id.spCategory);
cbOwn = (CheckBox) findViewById(R.id.cbOwn);}
// this is how i get my value (owner or not)
logcat
09-11 18:30:15.201 5825-5825/szub.borrowinghelper D/AndroidRuntime﹕ Shutting down VM
09-11 18:30:15.201 5825-5825/szub.borrowinghelper W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a99ba8)
09-11 18:30:15.211 5825-5825/szub.borrowinghelper E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: szub.borrowinghelper, PID: 5825
java.lang.NullPointerException
at soulflier.borrowinghelper.BHItemsAdapter.getView(BHItemsAdapter.java:49)
at android.widget.AbsListView.obtainView(AbsListView.java:2263)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
at android.widget.ListView.onMeasure(ListView.java:1175)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
I have no idea how send the value to that adapter.
I'm newbe in programing
thx for any help

Setting OnClickListener throws an exception?

I want to know why my application is throwing a runtime exception when I run it? I used to the code in the following link for my application,
dynamically add and remove view to viewpager.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ab=getActionBar();
pagerAdapter = new MainPagerAdapter();
pager = (ViewPager) findViewById (R.id.pager);
pager.setAdapter (pagerAdapter);
inflater = (LayoutInflater)getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
v0 = (FrameLayout) inflater.inflate (R.layout.listlayout, null);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(this);
pagerAdapter.addView (v0, 0);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button1)
{
pagerAdapter.addView (v0);
pagerAdapter.notifyDataSetChanged();
}
}
LogCat:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.todolistworkable/com.example.todolistworkable.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)Caused by: java.lang.NullPointerException
at com.example.todolistworkable.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
the object on line 43 of your code within your onCreate method is null. Most likely the target of one of your findViewById calls is not returning what you expect it to.
See this for more info.
How to interpret Logcat

Show GridView images from JSON Android

I have a problem when displaying images from JSON to GridView could help me .
GalleryActivity.java
public class GalleryActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_layout);
Intent i = getIntent();
String tempid = i.getStringExtra("tempid");
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(this,tempid));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public String[] mThumbIds;
private static String KEY_SUCCESS = "success";
private static String KEY_IMAGES = "images";
private static String KEY_IMAGE = "url_img";
// Constructor
public ImageAdapter(Context c,String tempID){
mContext = c;
final DealerFunctions dealerFunction = new DealerFunctions();
JSONObject json = dealerFunction.getImages(tempID);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
JSONArray imagesFields = json
.getJSONArray(KEY_IMAGES);
for (int i = 0; i < imagesFields.length(); i++) {
JSONObject x = imagesFields.getJSONObject(i);
mThumbIds[i] = x.getString(KEY_IMAGE);
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView==null){
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
}else{
imageView = (ImageView) convertView;
}
imageView.setBackgroundDrawable(Drawable.createFromPath(mThumbIds[position]));
return imageView;
}
}
Don't Work...
when I run the application, closes immediately assume that the problem comes in imageView.setBackgroundDrawable (Drawable.createFromPath (mThumbIds [position]));
I need your help guys
Logcat Errors as follows.
03-27 10:50:12.658: D/AndroidRuntime(1782): Shutting down VM
03-27 10:50:12.658: W/dalvikvm(1782): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
03-27 10:50:12.678: E/AndroidRuntime(1782): FATAL EXCEPTION: main
03-27 10:50:12.678: E/AndroidRuntime(1782): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.montalvo.dealer/com.montalvo.dealer.GalleryActivity}: java.lang.NullPointerException
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.os.Handler.dispatchMessage(Handler.java:99)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.os.Looper.loop(Looper.java:123)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-27 10:50:12.678: E/AndroidRuntime(1782): at java.lang.reflect.Method.invokeNative(Native Method)
03-27 10:50:12.678: E/AndroidRuntime(1782): at java.lang.reflect.Method.invoke(Method.java:521)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-27 10:50:12.678: E/AndroidRuntime(1782): at dalvik.system.NativeStart.main(Native Method)
03-27 10:50:12.678: E/AndroidRuntime(1782): Caused by: java.lang.NullPointerException
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.montalvo.dealer.ImageAdapter.<init>(ImageAdapter.java:57)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.montalvo.dealer.GalleryActivity.onCreate(GalleryActivity.java:25)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-27 10:50:12.678: E/AndroidRuntime(1782): ... 11 more
03-27 10:50:15.501: I/Process(1782): Sending signal. PID: 1782 SIG: 9
You are mixing things up here, use this
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
imageView.setBackgroundDrawable(Drawable.createFromPath(mThumbIds[position]));
return imageView;
}
The pattern you have used is that of the ViewHolder but you are not creating any views. If you do want to use the ViewHolder model then,
first create an xml with an ImageView.
Create a ViewHolder class in your ImageAdapter with an ImageView.
In the getView() method, inflate the xml.
create the viewholder for the case of convertview == null
set the viewholder as the TAG of the convertview.
in the else condtion, assign the previously created viewholder to the convertview.

Android gallery view in dialog results in nullpointerexception

So I've used the below code elsewhere and it has worked fine but now I'd like to use it in an alert dialog. Problem is that whenever I set the adapter it results in a nullpointerexception. The code (minus the alertdialog) is pretty much all right from the dev tutorial here:
http://developer.android.com/resources/tutorials/views/hello-gallery.html
If I comment out the line:
gallery.setAdapter(new ImageAdapter(this));
the dialog opens fine but the moment I set adapter results in error. Any ideas?
Here is the code for my alertdialog:
private void statusbarCustom() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = LayoutInflater.from(this).inflate(R.layout.custom_icon, null);
final EditText cTitle = (EditText)view.findViewById(R.id.search_term);
Gallery gallery = (Gallery) findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this));
builder.setView(view);
builder.setPositiveButton("Continue", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.setTitle("Statusbar");
alertDialog.show();
}
And here is the imageadapter code:
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
R.drawable.attach,
R.drawable.bell,
R.drawable.book_addresses,
R.drawable.book,
R.drawable.cake,
R.drawable.calculator,
R.drawable.calendar,
R.drawable.camera,
R.drawable.car,
R.drawable.cart,
R.drawable.chart_curve,
R.drawable.chart_pie_edit,
R.drawable.clock_,
R.drawable.computer,
R.drawable.controller,
R.drawable.cup,
R.drawable.date,
R.drawable.emotion_evilgrin,
R.drawable.emotion_grin,
R.drawable.emotion_happy,
R.drawable.emotion_smile,
R.drawable.emotion_suprised,
R.drawable.emotion_tongue,
R.drawable.emotion_unhappy,
R.drawable.emotion_waii,
R.drawable.emotion_wink,
R.drawable.exclamation,
R.drawable.film,
R.drawable.folder,
R.drawable.group,
R.drawable.heart,
R.drawable.house,
R.drawable.key,
R.drawable.lightbulb,
R.drawable.lightning,
R.drawable.lock,
R.drawable.lorry,
R.drawable.map,
R.drawable.money_euro,
R.drawable.money_pound,
R.drawable.money_yen,
R.drawable.money,
R.drawable.shop,
R.drawable.compass,
R.drawable.sofa,
R.drawable.gift,
R.drawable.smartphone,
R.drawable.accept,
R.drawable.add,
R.drawable.sound_none,
R.drawable.newspaper,
R.drawable.painbrush,
R.drawable.rainbow,
R.drawable.report,
R.drawable.ruby,
R.drawable.shield,
R.drawable.sport_8ball,
R.drawable.sport_basketball,
R.drawable.sport_football,
R.drawable.sport_raquet,
R.drawable.sport_shuttlecock,
R.drawable.sport_soccer,
R.drawable.sport_tennis,
R.drawable.star,
R.drawable.stop,
R.drawable.table_icon,
R.drawable.telephone,
R.drawable.television,
R.drawable.facebook
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray attr = mContext.obtainStyledAttributes(R.styleable.GalleryTheme);
mGalleryItemBackground = attr.getResourceId(
R.styleable.GalleryTheme_android_galleryItemBackground, 0);
attr.recycle();
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setBackgroundResource(mGalleryItemBackground);
return imageView;
}
}
And here is logcat output:
02-21 10:40:29.317: E/AndroidRuntime(3347): FATAL EXCEPTION: main
02-21 10:40:29.317: E/AndroidRuntime(3347): java.lang.NullPointerException
02-21 10:40:29.317: E/AndroidRuntime(3347): at com.flufflydelusions.app.enotesclassic.NoteEdit.statusbarCustom(NoteEdit.java:1954)
02-21 10:40:29.317: E/AndroidRuntime(3347): at com.flufflydelusions.app.enotesclassic.NoteEdit.access$67(NoteEdit.java:1949)
02-21 10:40:29.317: E/AndroidRuntime(3347): at com.flufflydelusions.app.enotesclassic.NoteEdit$25.onClick(NoteEdit.java:1835)
02-21 10:40:29.317: E/AndroidRuntime(3347): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:935)
02-21 10:40:29.317: E/AndroidRuntime(3347): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
02-21 10:40:29.317: E/AndroidRuntime(3347): at android.widget.ListView.performItemClick(ListView.java:3746)
02-21 10:40:29.317: E/AndroidRuntime(3347): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1981)
02-21 10:40:29.317: E/AndroidRuntime(3347): at android.os.Handler.handleCallback(Handler.java:587)
02-21 10:40:29.317: E/AndroidRuntime(3347): at android.os.Handler.dispatchMessage(Handler.java:92)
02-21 10:40:29.317: E/AndroidRuntime(3347): at android.os.Looper.loop(Looper.java:130)
02-21 10:40:29.317: E/AndroidRuntime(3347): at android.app.ActivityThread.main(ActivityThread.java:3691)
02-21 10:40:29.317: E/AndroidRuntime(3347): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 10:40:29.317: E/AndroidRuntime(3347): at java.lang.reflect.Method.invoke(Method.java:507)
02-21 10:40:29.317: E/AndroidRuntime(3347): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
02-21 10:40:29.317: E/AndroidRuntime(3347): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
02-21 10:40:29.317: E/AndroidRuntime(3347): at dalvik.system.NativeStart.main(Native Method)
Check if your gallery is null.
Was missing "view" in
view.findViewById for gallery
At this line:
Gallery gallery = (Gallery) findViewById(R.id.gallery);
The gallery has to be in the view set via setContentView. setContentView also has to come before the findViewByID. Otherwise you need to use a layout inflater and get the gallery view as such:
View view = activityContext.getLayoutInflater().inflate(R.layout.gallery_xml, null);
Gallery gallery = (Gallery)view.findViewById(R.id.gallery);

Categories

Resources