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);
Related
I wanted to test my code on another device than my physical one, so I launched the app in GenyMotion emulator with a Samsung Galaxy S3 (API 18), but it keeps throwing a NoClassDefFoundError Exception in my class "SlidingMenuUtil" (a customized drawer menu) which is called on startup by my MainActivity.
Here is code from my onCreate in MainActivity:
#Bind(R.id.viewContentFullScreen) RelativeLayout viewContentFullScreen;
#Bind(R.id.viewContentTopBar) RelativeLayout viewContentTopBar;
#Bind(R.id.topBarWrapper) RelativeLayout topbarView;
private ViewContainer viewContainer;
private SlidingMenuUtil leftMenu;
private Bundle bundle;
private MessageHandler messageHandler;
private GoBackFunction currentGoBackFunction;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = savedInstanceState;
setContentView(R.layout.activity_main);
leftMenu = new SlidingMenuUtil(this, SlidingMenuUtil.MenuType.LEFT, R.layout.drawer_menu, (int)(LayoutUtil.getScreenWidth(this) * 0.75), false);
populateMenu();
ButterKnife.bind(this);
messageHandler = new MessageHandler(this, findViewById(R.id.spinner));
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
The problem occurs in the SlidingMenuUtil class on line: 67. Here is the constructor for the class:
public SlidingMenuUtil(Activity activity, MenuType menuType, int menuLayout, int shownMenuWidth, boolean fadeEffectOn) {
this.activity = activity;
this.menuType = menuType;
this.shownMenuWidth = shownMenuWidth;
this.fadeEffectOn = fadeEffectOn;
this.screenWidth = LayoutUtil.getScreenWidth(activity);
this.rootView = (ViewGroup)((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
this.activityWrapper = new RelativeLayout(activity);
this.activityWrapper.setLayoutParams(this.rootView.getLayoutParams());
this.overlay = new RelativeLayout(activity);
this.overlay.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
this.overlay.setBackgroundColor(Color.parseColor("#000000"));
this.overlay.setAlpha(0.0F);
this.overlay.setVisibility(View.GONE);
this.overlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (menuOpen) {
toggle(new ToggleMenu() {
#Override
public void animationDone() {
}
});
}
}
});
this.rootView.addView(this.overlay);
this.menu = (LinearLayout)activity.getLayoutInflater().inflate(menuLayout, (ViewGroup) null, false);
this.menu.setLayoutParams(new ViewGroup.LayoutParams(shownMenuWidth, -1));
if (menuType == MenuType.LEFT) {
this.menu.setTranslationX((float)(-shownMenuWidth));
} else {
this.menu.setTranslationX((float)(screenWidth));
}
this.rootView.addView(this.menu);
this.menuOpen = false;
}
lin 67 is:
this.overlay.setOnClickListener(new View.OnClickListener() {
As mentioned before the problem only occurs in the emulator.
Here is the log:
812-812/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: nightout.dk.nightoutandroid.utils.SlidingMenuUtil$1
at nightout.dk.nightoutandroid.utils.SlidingMenuUtil.<init>(SlidingMenuUtil.java:67)
at nightout.dk.nightoutandroid.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
I hope somone can help me out.
Any help will be gratly appreciated
I m learning android please help me. It gives me following errors in logcat.
02-27 14:14:42.455: D/dalvikvm(1655): GC_FOR_ALLOC freed 46K, 5% free 2891K/3020K, paused 152ms, total 156ms
02-27 14:14:42.465: I/dalvikvm-heap(1655): Grow heap (frag case) to 3.668MB for 810016-byte allocation
02-27 14:14:42.545: D/dalvikvm(1655): GC_FOR_ALLOC freed 2K, 4% free 3680K/3812K, paused 76ms, total 77ms
02-27 14:14:43.425: I/Choreographer(1655): Skipped 35 frames! The application may be doing too much work on its main thread.
02-27 14:14:43.645: D/gralloc_goldfish(1655): Emulator without GPU emulation detected.
02-27 14:14:48.395: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:49.725: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:52.355: I/Choreographer(1655): Skipped 61 frames! The application may be doing too much work on its main thread.
02-27 14:14:55.195: D/AndroidRuntime(1655): Shutting down VM
02-27 14:14:55.195: W/dalvikvm(1655): threadid=1: thread exiting with uncaught exception (group=0xb3aaaba8)
02-27 14:14:55.275: E/AndroidRuntime(1655): FATAL EXCEPTION: main
02-27 14:14:55.275: E/AndroidRuntime(1655): Process: com.example.dreamhome, PID: 1655
02-27 14:14:55.275: E/AndroidRuntime(1655): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dreamhome/com.example.dreamhome.LoginFormActivity}: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Looper.loop(Looper.java:136)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invoke(Method.java:515)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-27 14:14:55.275: E/AndroidRuntime(1655): at dalvik.system.NativeStart.main(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): Caused by: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.example.dreamhome.LoginFormActivity.onCreate(LoginFormActivity.java:45)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Activity.performCreate(Activity.java:5231)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-27 14:14:55.275: E/AndroidRuntime(1655): ... 11 more
02-27 14:15:03.295: I/Process(1655): Sending signal. PID: 1655 SIG: 9
HomeActivity.java
public class HomeActivity extends Activity
{
Button search_property, log_in, exit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
search_property=(Button)findViewById(R.id.homebutton1);
log_in=(Button)findViewById(R.id.homebutton2);
exit=(Button)findViewById(R.id.homebutton3);
search_property.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main1=new Intent(HomeActivity.this,EndUserSearchPropertyActivity.class);
startActivity(main1);
}
});
log_in.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2 = new Intent(HomeActivity.this,LoginFormActivity.class);
startActivity(main2);
}
});
exit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
finish();
System.exit(0);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
this is LoginFormActivity.java
public class LoginFormActivity extends Activity
{
private Button sign_up = null;
private Button btnSignIn = null;
LoginDataBaseAdapter loginDataBaseAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
final Dialog dialog = new Dialog(LoginFormActivity.this);
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.login_editText1);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.login_editText2);
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// get The User name and Password
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(LoginFormActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(LoginFormActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
sign_up = (Button)findViewById(R.id.login_form_button2);
sign_up.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2=new Intent(LoginFormActivity.this,SignupFormActivity.class);
startActivity(main2);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
final Dialog dialog = new Dialog(LoginFormActivity.this);
Merely instantiating a dialog doesn't inflate/create its layout. All the subsequent dialog.findViewById() calls return null and you'll get the NPE here attempting to call a method on null reference:
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
You probably need to set a content view to your dialog with all the views you want to reference. The views are available with findViewById() after the dialog is showing.
I'm trying to make a Navigation Bar by using the example provided from android.
I've downloaded the code and implemented it into my project. I don't know why it doesn't work, it's a sample.
Here my logcat and my jar.
01-30 13:26:51.958: D/AndroidRuntime(580): Shutting down VM
01-30 13:26:51.958: W/dalvikvm(580): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
01-30 13:26:51.969: E/AndroidRuntime(580): FATAL EXCEPTION: main
01-30 13:26:51.969: E/AndroidRuntime(580): java.lang.RuntimeException: Unable to start activity ComponentInfo{ch.antum.antumapp/ch.antum.antumapp.MainActivity}: java.lang.NullPointerException
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.access$600(ActivityThread.java:122)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.os.Handler.dispatchMessage(Handler.java:99)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.os.Looper.loop(Looper.java:137)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-30 13:26:51.969: E/AndroidRuntime(580): at java.lang.reflect.Method.invokeNative(Native Method)
01-30 13:26:51.969: E/AndroidRuntime(580): at java.lang.reflect.Method.invoke(Method.java:511)
01-30 13:26:51.969: E/AndroidRuntime(580): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-30 13:26:51.969: E/AndroidRuntime(580): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-30 13:26:51.969: E/AndroidRuntime(580): at dalvik.system.NativeStart.main(Native Method)
01-30 13:26:51.969: E/AndroidRuntime(580): Caused by: java.lang.NullPointerException
01-30 13:26:51.969: E/AndroidRuntime(580): at ch.antum.antumapp.MainActivity.onCreate(MainActivity.java:93)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.Activity.performCreate(Activity.java:4465)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-30 13:26:51.969: E/AndroidRuntime(580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
01-30 13:26:51.969: E/AndroidRuntime(580): ... 11 more
MainActivity.java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.items)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
I have the right imports and package name.
It is a NullPointerException but I can't find anything missing. Also the logcat doesn't really specify in which file or on which line an error occurred. I had no problem debugging my projects when I wrote java applications. But, with android I can't really use the logcat usefully, any tips?
PS: I'm not using the ActionBar, but the code does, so may this be a problem? I've simply deleted the parts which where commented as ActionBar.
Thank you for your time.
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.
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.