Shutting down VM - java

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.

Related

How to fix Application force closes issue when device is turned on?

I have developed simple android imageview that uses viewpager, and it plays music in background. It also stops music when last image is reached and it will resume the music when user slides back to the images. However, my main problem is that when device goes to sleep music stops and when device starts again instead of resuming music again and displaying image..It force closes... Any suggestion on how to fix this issue...Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0);
oursong.start();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos == adapter.getCount() - 1)
{
oursong.pause();
} else if (!oursong.isPlaying())
{
oursong.start();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause() {
super.onPause();
oursong.release();
}
}
ImageAdapter.java
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private final int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Logcat errors.... (Following Logcat was taken when app was running on actual device)
08-29 02:48:21.051: I/dalvikvm(2880): Could not find method android.widget.ShareActionProvider.setShareIntent, referenced from method com.manishkpr.viewpagerimagegallery.MainActivity.setShareIntent
08-29 02:48:21.051: W/dalvikvm(2880): VFY: unable to resolve virtual method 3259: Landroid/widget/ShareActionProvider;.setShareIntent (Landroid/content/Intent;)V
08-29 02:48:21.051: D/dalvikvm(2880): VFY: replacing opcode 0x6e at 0x0006
08-29 02:48:21.066: I/dalvikvm(2880): Could not find method android.view.MenuItem.getActionProvider, referenced from method com.manishkpr.viewpagerimagegallery.MainActivity.onCreateOptionsMenu
08-29 02:48:21.066: W/dalvikvm(2880): VFY: unable to resolve interface method 2912: Landroid/view/MenuItem;.getActionProvider ()Landroid/view/ActionProvider;
08-29 02:48:21.066: D/dalvikvm(2880): VFY: replacing opcode 0x72 at 0x0010
08-29 02:48:21.066: D/dalvikvm(2880): VFY: dead code 0x0013-0019 in Lcom/manishkpr/viewpagerimagegallery/MainActivity;.onCreateOptionsMenu (Landroid/view/Menu;)Z
08-29 02:48:21.230: W/MediaPlayer-cpp(2880): info/warning (802, 0)
08-29 02:48:21.348: I/MediaPlayer(2880): Info (802,0)
08-29 02:48:21.434: D/dalvikvm(2880): GC_EXTERNAL_ALLOC freed 1117 objects / 212256 bytes in 71ms
08-29 02:48:36.644: D/dalvikvm(2880): GC_EXTERNAL_ALLOC freed 553 objects / 29584 bytes in 32ms
08-29 02:50:00.566: D/AndroidRuntime(2880): Shutting down VM
08-29 02:50:00.566: W/dalvikvm(2880): threadid=1: thread exiting with uncaught exception (group=0x4001d8a8)
08-29 02:50:00.605: E/AndroidRuntime(2880): FATAL EXCEPTION: main
08-29 02:50:00.605: E/AndroidRuntime(2880): java.lang.RuntimeException: Unable to resume activity {com.manishkpr.viewpagerimagegallery/com.manishkpr.viewpagerimagegallery.MainActivity}: java.lang.IllegalStateException
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3128)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3143)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2059)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.os.Handler.dispatchMessage(Handler.java:99)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.os.Looper.loop(Looper.java:123)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-29 02:50:00.605: E/AndroidRuntime(2880): at java.lang.reflect.Method.invokeNative(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): at java.lang.reflect.Method.invoke(Method.java:521)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-29 02:50:00.605: E/AndroidRuntime(2880): at dalvik.system.NativeStart.main(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): Caused by: java.lang.IllegalStateException
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.media.MediaPlayer.seekTo(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.manishkpr.viewpagerimagegallery.MainActivity.onResume(MainActivity.java:86)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.Activity.performResume(Activity.java:3823)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3118)
08-29 02:50:00.605: E/AndroidRuntime(2880): ... 10 more
08-29 02:50:10.371: I/Process(2880): Sending signal. PID: 2880 SIG: 9
Have you tried moving your music playback to onResume() Activity lifecycle with fragments won't call onCreate() again until you activity is 're created. So the playback won't be resumed without closing your app.
Something like this
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
ImageAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0);
oursong.start();
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(MyViewPagerListener);
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause() {
super.onPause();
if(oursong != null){
oursong.release();
}
}
#Override
protected void onResume(){
super.onResume();
/*
* This is the important part, basically since your releasing the song
* in onPause() you are getting rid of its reference, in this case check
* if your song is null then if it is re-create it, else you can reuse the
* the original, but i suspect that calling release() in onPause() allows the
* song to get cleaned up by Java's Garbage Collector.
*/
if(oursong == null){
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0); // You will probably want to save an int to restore here
oursong.start();
}else{
oursong.seekTo();
oursong.start();
}
}
/*
* May want to add two methods here: onSaveInstanceState(Bundle outstate) &
* onRestoreInstanceState(Bundle savedInstanceState) to maintain playback position
* in onResume instead of just restarting the song.
*/
private final OnPageChangeListener MyViewPagerListener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos == adapter.getCount() - 1){
// adding null checks for safety
if(oursong != null){
oursong.pause();
}
} else if (!oursong.isPlaying()){
// adding null check for safety
if(oursong != null){
oursong.start();
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
};
}
Hope this helps you resolve your problem.

Android, Navigation Drawer NullPointerException, No ActionBar

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.

Unfortunately, (App Name) has stopped Android, Eclipse

I am able to compile, build, and install the project successfully And the project is running well in portrait, But In landscape mode, When I click in button, the app says: Unfortunately has stopped. Could you please help me figure this out?
This is The app Logcat In Landscape mode:
01-24 09:58:19.936: W/dalvikvm(6847): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-24 09:58:19.986: E/AndroidRuntime(6847): FATAL EXCEPTION: main
01-24 09:58:19.986: E/AndroidRuntime(6847): java.lang.NullPointerException
01-24 09:58:19.986: E/AndroidRuntime(6847): at com.Divani.Marzieh.ExamActivity.addItemList(ExamActivity.java:79)
01-24 09:58:19.986: E/AndroidRuntime(6847): at com.Divani.Marzieh.ExamActivity$1.onClick(ExamActivity.java:71)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.view.View.performClick(View.java:3511)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.view.View$PerformClick.run(View.java:14105)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.os.Handler.handleCallback(Handler.java:605)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.os.Handler.dispatchMessage(Handler.java:92)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.os.Looper.loop(Looper.java:137)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-24 09:58:19.986: E/AndroidRuntime(6847): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 09:58:19.986: E/AndroidRuntime(6847): at java.lang.reflect.Method.invoke(Method.java:511)
01-24 09:58:19.986: E/AndroidRuntime(6847): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-24 09:58:19.986: E/AndroidRuntime(6847): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-24 09:58:19.986: E/AndroidRuntime(6847): at dalvik.system.NativeStart.main(Native Method)
This is The examActivity Code:
public class ExamActivity extends Activity {
private EditText etInput1;
private EditText etInput2;
private Button btnAdd;
private ListView lvItem;
private ArrayList<Item> itemArrey;
private ArrayAdapter<Item> itemAdapter;
private static TabHost tabHost;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabHost=(TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabSpec spec1=tabHost.newTabSpec("Tab 1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("LIST");
TabSpec spec2=tabHost.newTabSpec("Tab 2");
spec2.setIndicator("DETAILS");
spec2.setContent(R.id.tab2);
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.setCurrentTab(id.tab1);
setUpView();
}
public static TabHost getCurrentTabHost(){
return tabHost;
}
private void setUpView() {
// TODO Auto-generated method stub
etInput1 = (EditText)this.findViewById(R.id.editText1);
etInput2 = (EditText)this.findViewById(R.id.editText2);
btnAdd = (Button)this.findViewById(R.id.button1);
lvItem = (ListView)this.findViewById(R.id.list);
itemArrey = new ArrayList<Item>();
itemArrey.clear();
itemAdapter = new CustomlistActivity(this, android.R.layout.simple_list_item_1,R.id.textView1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
if (isInputValid(etInput1) && isInputValid(etInput2)) {
if(((RadioButton)findViewById(R.id.radio0)).isChecked())
itemArrey.add(new Item(R.drawable.t,etInput1.getText().toString()+"\n"+etInput2.getText().toString()));
else if(((RadioButton)findViewById(R.id.radio1)).isChecked())
itemArrey.add(new Item(R.drawable.s,etInput1.getText().toString()+"\n"+etInput2.getText().toString()));
else if(((RadioButton)findViewById(R.id.radio2)).isChecked())
itemArrey.add(new Item(R.drawable.d,etInput1.getText().toString()+"\n"+etInput2.getText().toString()));
itemAdapter.notifyDataSetChanged();
ExamActivity.getCurrentTabHost().setCurrentTab(0);
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Please Enter Item");
return false;
} else {
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater .inflate(R.menu.mymenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
EditText e = (EditText)findViewById(R.id.editText3);
switch (item.getItemId()) {
case R.id.item1:
Toast toast = Toast.makeText(ExamActivity.this, e.getText().toString(), 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
whenever you change the orientation of the screen the activity gets restarted after that the onStart() method is called.
Initialize your code that you are using at ExamActivity.addItemList(ExamActivity.java:79) in your onStart() method ex: your list or array
go through the site http://www.vogella.com/tutorials/AndroidLifeCycle/article.html#configurationchange
Do you have a separate layout main.xml for landscape, ie layout/main.xml and layout-land/main.xml ? If so then check that layout-land/main.xml is not missing some or all of the radio buttons radio0/1/2.

Why does my fragment crash when switching to landscape?

Well to be more specific I have made a create account fragment and a login fragment. When switching to landscape in the create account fragment it actually goes back to the login fragment. And then if you try to switch back into portrait then the app crashes. I've looked at similar questions but I couldnt make anything out from them. I really appreciate the help guys!
CreateAccountFragment
package com.keyconsultant.parse.logintutorial;
/**
* Create an Account. Username is the primary method of login. Email is used for forgotten password recovery.
*
* #author Trey Robinson
*
*/
public class CreateAccountFragment extends BaseFragment implements OnClickListener {
protected static final String EXTRA_EMAIL = "com.keyconsultant.parse.logintutorial.fragment.extra.EMAIL";
protected static final String EXTRA_USERNAME = "com.keyconsultant.parse.logintutorial.fragment.extra.USERNAME";
protected static final String EXTRA_PASSWORD = "com.keyconsultant.parse.logintutorial.fragment.extra.PASSWORD";
protected static final String EXTRA_CONFIRM = "com.keyconsultant.parse.logintutorial.fragment.extra.CONFIRMPASSWORD";
private EditText mUserNameEditText;
private EditText mEmailEditText;
private EditText mPasswordEditText;
private EditText mConfirmPasswordEditText;
private Button mCreateAccountButton;
private String mEmail;
private String mUsername;
private String mPassword;
private String mConfirmPassword;
/**
* Factory method for creating fragment instances.
* #return
*/
public static CreateAccountFragment newInstance(){
return new CreateAccountFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_create_account, container, false);
mUserNameEditText = (EditText)view.findViewById(R.id.etUsername);
mEmailEditText = (EditText)view.findViewById(R.id.etEmail);
mPasswordEditText = (EditText)view.findViewById(R.id.etPassword);
mConfirmPasswordEditText = (EditText)view.findViewById(R.id.etPasswordConfirm);
mCreateAccountButton = (Button)view.findViewById(R.id.btnCreateAccount);
mCreateAccountButton.setOnClickListener(this);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null){
mEmailEditText.setText(savedInstanceState.getString(EXTRA_EMAIL));
mUserNameEditText.setText(savedInstanceState.getString(EXTRA_USERNAME));
mPasswordEditText.setText(savedInstanceState.getString(EXTRA_PASSWORD));
mConfirmPasswordEditText.setText(savedInstanceState.getString(EXTRA_CONFIRM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(EXTRA_EMAIL, mEmailEditText.getText().toString());
outState.putString(EXTRA_USERNAME, mUserNameEditText.getText().toString());
outState.putString(EXTRA_PASSWORD, mPasswordEditText.getText().toString());
outState.putString(EXTRA_CONFIRM, mConfirmPasswordEditText.getText().toString());
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnCreateAccount:
createAccount();
break;
default:
break;
}
}
/**
* Some front end validation is done that is not monitored by the service.
* If the form is complete then the information is passed to the service.
*/
private void createAccount(){
clearErrors();
boolean cancel = false;
View focusView = null;
// Store values at the time of the login attempt.
mEmail = mEmailEditText.getText().toString();
mUsername = mUserNameEditText.getText().toString();
mPassword = mPasswordEditText.getText().toString();
mConfirmPassword = mConfirmPasswordEditText.getText().toString();
// Check for a valid confirm password.
if (TextUtils.isEmpty(mConfirmPassword)) {
mConfirmPasswordEditText.setError(getString(R.string.error_field_required));
focusView = mConfirmPasswordEditText;
cancel = true;
} else if (mPassword != null && !mConfirmPassword.equals(mPassword)) {
mPasswordEditText.setError(getString(R.string.error_invalid_confirm_password));
focusView = mPasswordEditText;
cancel = true;
}
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordEditText.setError(getString(R.string.error_field_required));
focusView = mPasswordEditText;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordEditText.setError(getString(R.string.error_invalid_password));
focusView = mPasswordEditText;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {
mEmailEditText.setError(getString(R.string.error_field_required));
focusView = mEmailEditText;
cancel = true;
} else if (!mEmail.contains("#")) {
mEmailEditText.setError(getString(R.string.error_invalid_email));
focusView = mEmailEditText;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
UserManager.getInstance().signUp(mUsername.toLowerCase(Locale.getDefault()), mEmail, mPassword);
}
}
/**
* Remove error messages from all fields.
*/
private void clearErrors(){ mEmailEditText.setError(null);
mUserNameEditText.setError(null);
mPasswordEditText.setError(null);
mConfirmPasswordEditText.setError(null);
}
#Subscribe
public void onSignInError(AuthenticateUserErrorEvent event){
clearErrors();
switch (event.getErrorCode()) {
case ParseException.INVALID_EMAIL_ADDRESS:
mEmailEditText.setError(getString(R.string.error_invalid_email));
mEmailEditText.requestFocus();
break;
case ParseException.EMAIL_TAKEN:
mEmailEditText.setError(getString(R.string.error_duplicate_email));
mEmailEditText.requestFocus();
break;
case ParseException.USERNAME_TAKEN:
mUserNameEditText.setError(getString(R.string.error_duplicate_username));
mUserNameEditText.requestFocus();
break;
default:
UnknownErrorDialogFactory.createUnknownErrorDialog(this.getActivity()).show();
break;
}
}
}
LoginFragment
package com.keyconsultant.parse.logintutorial;
/**
* Fragment for logging in. Includes button for loading the Create account view.
*
* #author Trey Robinson
*
*/
public class LoginFragment extends BaseFragment {
public static final String EXTRA_USERNAME = "com.keyconsultant.parse.logintutorial.activity.extra.USERNAME";
public static final String EXTRA_PASSWORD = "com.keyconsultant.parse.logintutorial.activity.extra.PASSWORD";
// UI references.
private EditText mUserNameEditText;
private EditText mPasswordEditText;
/**
* Factory method for creating new fragments
*
* #return
*/
public static LoginFragment newInstance() {
return new LoginFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
mUserNameEditText = (EditText) view.findViewById(R.id.username);
mPasswordEditText = (EditText) view.findViewById(R.id.password);
mPasswordEditText
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
view.findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
view.findViewById(R.id.register_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
createAccount();
}
});
view.findViewById(R.id.forgot_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
forgotPassword();
}
});
return view;
}
/**
* Open the forgotPassword dialog
*/
private void forgotPassword() {
FragmentManager fm = getActivity().getSupportFragmentManager();
ForgotPasswordDialogFragment forgotPasswordDialog = new ForgotPasswordDialogFragment();
forgotPasswordDialog.show(fm, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mUserNameEditText.setText(savedInstanceState
.getString(EXTRA_USERNAME));
mPasswordEditText.setText(savedInstanceState
.getString(EXTRA_PASSWORD));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(EXTRA_USERNAME, mUserNameEditText.getText()
.toString());
outState.putString(EXTRA_PASSWORD, mPasswordEditText.getText()
.toString());
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
clearErrors();
// Store values at the time of the login attempt.
String username = mUserNameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(password)) {
mPasswordEditText
.setError(getString(R.string.error_field_required));
focusView = mPasswordEditText;
cancel = true;
} else if (password.length() < 4) {
mPasswordEditText
.setError(getString(R.string.error_invalid_password));
focusView = mPasswordEditText;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(username)) {
mUserNameEditText
.setError(getString(R.string.error_field_required));
focusView = mUserNameEditText;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// perform the user login attempt.
UserManager.getInstance().authenticate(
username.toLowerCase(Locale.getDefault()), password);
}
}
/**
* Load the create account view.
*/
private void createAccount() {
FragmentManager fragmentManager = getActivity()
.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.replace(
((ViewGroup) getView().getParent()).getId(),
CreateAccountFragment.newInstance());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/**
* Remove all edit text errors
*/
private void clearErrors() {
mUserNameEditText.setError(null);
mPasswordEditText.setError(null);
}
#Subscribe
public void onSignInError(AuthenticateUserErrorEvent event) {
clearErrors();
switch (event.getErrorCode()) {
case ParseException.OBJECT_NOT_FOUND:
mPasswordEditText
.setError(getString(R.string.error_incorrect_password));
mPasswordEditText.requestFocus();
break;
default:
UnknownErrorDialogFactory.createUnknownErrorDialog(
this.getActivity()).show();
break;
}
}
}
Just in case you need it here is my LoginActivity
package com.keyconsultant.parse.logintutorial;
/**
* Activity which displays a login screen to the user, offering registration as
* well. Based loosley on the default Login template.
*
* #author Trey Robinson
*/
public class LoginActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Parse.initialize(this, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction
.replace(R.id.main_view, LoginFragment.newInstance());
fragmentTransaction.commit();
parseCache();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_forgot_password:
forgotPassword();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Open the forgotPassword dialog
*/
private void forgotPassword() {
FragmentManager fm = getSupportFragmentManager();
ForgotPasswordDialogFragment forgotPasswordDialog = new ForgotPasswordDialogFragment();
forgotPasswordDialog.show(fm, null);
}
#Subscribe
public void onSignInStart(AuthenticateUserStartEvent event) {
showProgress(true, getString(R.string.login_progress_signing_in));
}
#Subscribe
public void onSignInSuccess(AuthenticateUserSuccessEvent event) {
showProgress(false, getString(R.string.login_progress_signing_in));
Intent loginSuccess = new Intent(this, MainActivity.class);
startActivity(loginSuccess);
finish();
}
#Subscribe
public void onSignInError(AuthenticateUserErrorEvent event) {
showProgress(false, getString(R.string.login_progress_signing_in));
}
#Subscribe
public void onForgotPasswordStart(UserForgotPasswordStartEvent event) {
showProgress(true, getString(R.string.login_progress_signing_in));
}
#Subscribe
public void onForgotPasswordSuccess(UserForgotPasswordSuccessEvent event) {
showProgress(false, getString(R.string.login_progress_signing_in));
Toast toast = Toast.makeText(this,
"A password reset email has been sent.", Toast.LENGTH_LONG);
toast.show();
}
#Subscribe
public void onForgotPasswordError(UserForgotPasswordErrorEvent event) {
showProgress(false, getString(R.string.login_progress_signing_in));
Toast toast = Toast.makeText(this,
"An error has occured. Please try again.", Toast.LENGTH_LONG);
toast.show();
}
private void parseCache() {
Intent intent;
if (ParseUser.getCurrentUser() != null) {
intent = new Intent(this, MainActivity.class);
startActivity(intent);
this.finish();
}
}
}
Here is the logcat
01-10 16:09:05.796: I/Process(1923): Sending signal. PID: 1923 SIG: 9
01-10 17:00:57.513: I/Choreographer(1975): Skipped 111 frames! The application may be doing too much work on its main thread.
01-10 17:00:57.513: D/gralloc_goldfish(1975): Emulator without GPU emulation detected.
01-10 17:00:58.363: I/Choreographer(1975): Skipped 36 frames! The application may be doing too much work on its main thread.
01-10 17:00:58.833: I/Choreographer(1975): Skipped 37 frames! The application may be doing too much work on its main thread.
01-10 17:00:59.163: I/Choreographer(1975): Skipped 32 frames! The application may be doing too much work on its main thread.
01-10 17:01:11.253: D/dalvikvm(1975): GC_FOR_ALLOC freed 74K, 5% free 5533K/5820K, paused 2ms, total 3ms
01-10 17:01:11.253: I/dalvikvm-heap(1975): Grow heap (frag case) to 7.992MB for 2500620-byte allocation
01-10 17:01:11.263: D/dalvikvm(1975): GC_FOR_ALLOC freed 2K, 4% free 7972K/8264K, paused 2ms, total 3ms
01-10 17:01:11.273: D/dalvikvm(1975): GC_FOR_ALLOC freed <1K, 4% free 7972K/8264K, paused 3ms, total 4ms
01-10 17:01:11.273: I/dalvikvm-heap(1975): Grow heap (frag case) to 10.696MB for 2838540-byte allocation
01-10 17:01:11.283: D/dalvikvm(1975): GC_FOR_ALLOC freed 0K, 3% free 10744K/11040K, paused 4ms, total 4ms
01-10 17:01:15.953: D/dalvikvm(1975): GC_FOR_ALLOC freed 5268K, 45% free 6880K/12360K, paused 0ms, total 3ms
01-10 17:01:15.953: I/dalvikvm-heap(1975): Grow heap (frag case) to 8.489MB for 1642512-byte allocation
01-10 17:01:15.973: D/dalvikvm(1975): GC_FOR_ALLOC freed <1K, 32% free 8483K/12360K, paused 13ms, total 13ms
01-10 17:01:16.053: I/Choreographer(1975): Skipped 42 frames! The application may be doing too much work on its main thread.
01-10 17:01:17.473: I/Choreographer(1975): Skipped 58 frames! The application may be doing too much work on its main thread.
01-10 17:01:18.043: I/Choreographer(1975): Skipped 57 frames! The application may be doing too much work on its main thread.
01-10 17:01:23.363: D/AndroidRuntime(1975): Shutting down VM
01-10 17:01:23.363: W/dalvikvm(1975): threadid=1: thread exiting with uncaught exception (group=0xb0f2e648)
01-10 17:01:23.363: E/AndroidRuntime(1975): FATAL EXCEPTION: main
01-10 17:01:23.363: E/AndroidRuntime(1975): java.lang.NullPointerException
01-10 17:01:23.363: E/AndroidRuntime(1975): at com.keyconsultant.parse.logintutorial.LoginFragment.onSaveInstanceState(LoginFragment.java:119)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.support.v4.app.Fragment.performSaveInstanceState(Fragment.java:1607)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1587)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1655)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:527)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.Activity.performSaveInstanceState(Activity.java:1147)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1223)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3714)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.ActivityThread.access$700(ActivityThread.java:141)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.os.Handler.dispatchMessage(Handler.java:99)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.os.Looper.loop(Looper.java:137)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-10 17:01:23.363: E/AndroidRuntime(1975): at java.lang.reflect.Method.invokeNative(Native Method)
01-10 17:01:23.363: E/AndroidRuntime(1975): at java.lang.reflect.Method.invoke(Method.java:525)
01-10 17:01:23.363: E/AndroidRuntime(1975): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-10 17:01:23.363: E/AndroidRuntime(1975): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-10 17:01:23.363: E/AndroidRuntime(1975): at dalvik.system.NativeStart.main(Native Method)
Your logcat shows you have problems in LoginFragment.onSaveInstanceState()
First, make super.onSaveInstanceState() the last line instead of the first line as it is now.
Then make sure you don't have mUserName and mPassword and their texts as nulls
Initialize mUserName and password texts to "" somewhere and the error should be gone, I think.

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