Android Unable to instantiate Activity(Using File Inputs) - java

Info: I am a decent java developer, I know my way around it pretty well I think, so I decided to give android a chance, and it hasn't been the smoothest road for me. I mess up very often. Anyway to my question if anyone would be so kind to help me out with this error I would very much appreciate it! Thank you.
Main Class
package dev.shaw.MyShoppingPlanner;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private String m_Text = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if(firstTime()){
GenerateNeededFiles();
}
else{
//do nothing
}
ActionBar.TabListener tablistener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch(tab.getText().toString()){
case "Lists":
openLists();
break;
case "Store":
openStore();
case "Home":
openTab();
}
}
private void openTab() {
}
private void openStore() {
View v = new View(MainActivity.this);
v.setVisibility(1);
v.clearFocus();
v.bringToFront();
}
private void openLists() {
Intent intent = new Intent(MainActivity.this,List_Activity.class);
startActivity(intent);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
};
actionbar.addTab(actionbar.newTab().setText("Home").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Store").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Lists").setTabListener(tablistener));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
private boolean firstTime() {
File storelist = new File(this.getFilesDir() + "\\StoreList.txt");
File listnames = new File(this.getFilesDir() + "\\ListNames.txt");
if(storelist.exists() && listnames.exists()){
return false;
}
else{
return true;
}
}
private void GenerateNeededFiles() {
Intent intent = new Intent(MainActivity.this,Install_Activity.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
default:
return super.onOptionsItemSelected(item);
}
}
private void openSettings() {
}
private void openSearch() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Search");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
The Class that gets an error when called
package dev.shaw.MyShoppingPlanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class List_Activity extends ListActivity {
String ListNames[] = getListNames();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem , ListNames));
}
protected void onListItemClick(ListView lv, View v, int pos,long id){
this.onListItemClick(lv, v, pos, id);
ShoppingList list = new ShoppingList(ListNames[pos]);
try {
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list.toArray(list.getFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String[] getListNames() {
File file = new File(this.getFilesDir() + "\\listnames.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStreamReader is = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(is);
String line;
String names[] = new String[100];
int i = 0;
try {
while(true){
line = br.readLine();
if(line == null){
break;
}
else{
try{
names[i] = line;
}
catch(NullPointerException e){
e.printStackTrace();
}
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return names;
}
}
and here is the printStack
03-23 04:58:16.523: D/dalvikvm(3710): GC_FOR_ALLOC freed 151K, 18% free 2770K/3356K, paused 2ms, total 7ms
03-23 04:58:16.531: D/dalvikvm(3710): GC_FOR_ALLOC freed 100K, 19% free 2988K/3680K, paused 1ms, total 4ms
03-23 04:58:16.535: I/dalvikvm-heap(3710): Grow heap (frag case) to 4.414MB for 1127532-byte allocation
03-23 04:58:16.539: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 3ms, total 3ms
03-23 04:58:16.555: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 1ms, total 1ms
03-23 04:58:16.587: I/dalvikvm-heap(3710): Grow heap (frag case) to 6.833MB for 2536932-byte allocation
03-23 04:58:16.599: D/dalvikvm(3710): GC_FOR_ALLOC freed 0K, 10% free 6567K/7264K, paused 2ms, total 2ms
03-23 04:58:16.615: D/HardwareRenderer(3710): Profiling hardware renderer
03-23 04:58:16.647: D/libEGL(3710): loaded /system/lib/egl/libEGL_genymotion.so
03-23 04:58:16.651: D/(3710): HostConnection::get() New Host Connection established 0xb85b3b40, tid 3710
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv2_genymotion.so
03-23 04:58:16.711: W/EGL_genymotion(3710): eglSurfaceAttrib not implemented
03-23 04:58:16.711: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from GradienCache
03-23 04:58:16.723: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
03-23 04:58:16.723: D/OpenGLRenderer(3710): Enabling debug mode 0
03-23 04:58:18.015: D/AndroidRuntime(3710): Shutting down VM
03-23 04:58:18.015: W/dalvikvm(3710): threadid=1: thread exiting with uncaught exception (group=0xa4bae648)
03-23 04:58:18.015: E/AndroidRuntime(3710): FATAL EXCEPTION: main
03-23 04:58:18.015: E/AndroidRuntime(3710): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{dev.shaw.MyShoppingPlanner/dev.shaw.MyShoppingPlanner.List_Activity}: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Looper.loop(Looper.java:137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invoke(Method.java:525)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dalvik.system.NativeStart.main(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): Caused by: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.content.ContextWrapper.getFilesDir(ContextWrapper.java:199)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.getListNames(List_Activity.java:38)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.<init>(List_Activity.java:16)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstanceImpl(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstance(Class.java:1130)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
03-23 04:58:18.015: E/AndroidRuntime(3710): ... 11 more

Related

Sending String to PHP file via android application

I am developing an app which includes the upload of all contacts to my server what i am doing is displaying all the contacts and sending them to my server as a string.Here is my code:
package com.example.core.freemusic;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MainActivity extends Activity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
LoadContactsAyscn lca = new LoadContactsAyscn();
lca.execute();
}
class LoadContactsAyscn extends AsyncTask < Void, Void, String > {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Please Wait","");
}
#Override
protected String doInBackground(Void...params) {
String contacts = "";
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts += contactName + ":" + phNumber + "\n";
}
c.close();
return contacts;
}
#Override
protected void onPostExecute(String contacts) {
super.onPostExecute(contacts);
pd.cancel();
TextView a = (TextView) findViewById(R.id.textView);
a.setText(contacts);
doInBackground(contacts);
}
protected void doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
try {
httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Actually the code shows no error but on running it in emulator it crashes.
the error on logcat is:
05-24 14:00:57.989 2488-2500/com.example.core.freemusic W/art﹕ Suspending all threads took: 5.841ms
05-24 14:00:57.992 2488-2500/com.example.core.freemusic I/art﹕ Background partial concurrent mark sweep GC freed 1888(115KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 6.923ms total 95.188ms
05-24 14:00:58.073 2488-2488/com.example.core.freemusic I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
05-24 14:00:58.080 2488-2488/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
05-24 14:00:58.102 2488-2488/com.example.core.freemusic D/AndroidRuntime﹕ Shutting down VM
05-24 14:00:58.103 2488-2488/com.example.core.freemusic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.core.freemusic, PID: 2488
java.lang.IllegalArgumentException: Illegal character in query at index 43: http://192.168.2.30/b.php?username=Sd:(546) 456-4826
Sad:486-44
at java.net.URI.create(URI.java:730)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:64)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 14:01:01.259 2488-2488/com.example.core.freemusic I/Process﹕ Sending signal. PID: 2488 SIG: 9
05-24 15:24:12.790 2685-2685/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
As error code state, you need to encode the query:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
need to changed into:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+java.net.URLEncoder.encode(params[0], "UTF-8"));

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.

Application crashing because of NullPointerException

I'm working with a listview which on click opens a dialog box which contains an edittext and a button. On button click, the value entered in the editText is saved in a textView from listview item which had been pressed before. The problem is that the value wasn't saved anymore if I reopened the application. I tried to make it save using sharedPrefences but it's crashing and shows 3 nullpointerexception and can't deal with them.
Here is my:
Carnet.java
package com.cngcnasaud.orar;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
#SuppressWarnings("deprecation")
public class Carnet extends TabActivity {
// TabSpec Names
private static final String NOTA_SPEC = "Note";
private static final String ABSENTE_SPEC = "Absente";
private static final String MEDII_SPEC = "Medii";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carnet);
TabHost tabHost = getTabHost();
TabSpec NotaSpec = tabHost.newTabSpec(NOTA_SPEC);
// Tab Icon
NotaSpec.setIndicator(NOTA_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent notaIntent = new Intent(this, Note.class);
// Tab Content
NotaSpec.setContent(notaIntent);
TabSpec AbsenteSpec = tabHost.newTabSpec(ABSENTE_SPEC);
AbsenteSpec.setIndicator(ABSENTE_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent absenteIntent = new Intent(this, Absente.class);
AbsenteSpec.setContent(absenteIntent);
TabSpec MediiSpec = tabHost.newTabSpec(MEDII_SPEC);
AbsenteSpec.setIndicator(MEDII_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent mediiIntent = new Intent(this, MediiL.class);
AbsenteSpec.setContent(mediiIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(NotaSpec);
tabHost.addTab(AbsenteSpec);
tabHost.addTab(MediiSpec);
}
}
Note.java
package com.cngcnasaud.orar;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Note extends Activity {
private static final ListAdapter NoteAdapter = null;
ListView lv;
Context context;
ArrayList<?> prgmName;
TextView text;
public static String[] prgmNameList = { "Romana - ", "Matematica - ",
"Lb. Engleza - ", "Lb. Germana/Franceza - ", "Istorie - ",
"Geografie - ", "Biologie - ", "Fizica - ", "Ed. Fizica - " };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_listview);
text = (TextView) findViewById(R.id.textView2);
context = this;
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
// Variable is public for clarity.
String toSave = EncodeDecode.encode(adapter.savedEntries);
SharedPreferences.Editor editor = getSharedPreferences("LV Data",
MODE_PRIVATE).edit();
editor.putString("TVEntries", toSave);
editor.commit();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
String encoded = prefs.getString("TVEntries", "");
String[] entries;
if (encoded.equals(""))
entries = null;
else
entries = EncodeDecode.decode(encoded);
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
adapter.savedEntries = entries;
lv.setAdapter(adapter);
super.onResume();
}
}
And NoteAdapter.java:
package com.cngcnasaud.orar;
import java.util.Arrays;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class NoteAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
private Dialog dialog;
String[] savedEntries;
String[] saved = null;
public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
// TODO Auto-generated constructor stub
result = prgmNameList;
context = note;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (saved == null) {
savedEntries = new String[result.length];
Arrays.fill(savedEntries, "");
} else
savedEntries = saved;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return savedEntries[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
public TextView text;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.note_items, null);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.text = (TextView) rowView.findViewById(R.id.textView2);
holder.text.setText(savedEntries[position]);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Materie:" + result[position]);
final EditText txtMode = (EditText) dialog
.findViewById(R.id.dialog);
Button btnSave = (Button) dialog.findViewById(R.id.bsave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = txtMode.getText().toString();
holder.text.setText(data);
savedEntries[position] = data;
dialog.dismiss();
Log.d("data", data);
}
});
dialog.show();
}
});
return rowView;
}
}
logcat:
04-18 19:27:28.558: E/AndroidRuntime(1419): FATAL EXCEPTION: main
04-18 19:27:28.558: E/AndroidRuntime(1419): Process: com.cngcnasaud.orar, PID: 1419
04-18 19:27:28.558: E/AndroidRuntime(1419): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Carnet}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.os.Handler.dispatchMessage(Handler.java:102)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.os.Looper.loop(Looper.java:136)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-18 19:27:28.558: E/AndroidRuntime(1419): at java.lang.reflect.Method.invokeNative(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): at java.lang.reflect.Method.invoke(Method.java:515)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-18 19:27:28.558: E/AndroidRuntime(1419): at dalvik.system.NativeStart.main(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2035)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost.setCurrentTab(TabHost.java:413)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost.addTab(TabHost.java:240)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.Carnet.onCreate(Carnet.java:45)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419): ... 11 more
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.NoteAdapter.getCount(NoteAdapter.java:46)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.ListView.setAdapter(ListView.java:480)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.Note.onCreate(Note.java:34)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419): ... 21 more
Carnet.java line 45:
tabHost.addTab(NotaSpec);
NoteAdapter.java line 46:
return result.length;
Note.java line 34:
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
Your String array in null here:
NoteAdapter.java line 46:
return result.length;
because is a class field, you populate in the constructor from a parameter:
public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
// TODO Auto-generated constructor stub
result = prgmNameList;
that you pass as null here (passed as second parameter, it should be third):
Note.java line 34:
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
There is no point in passing that as a parameter as it is a public constant (public static final).

On button click uri intent works in android 4.1.2, but does not work on android 2.3.7

I have the following Activity:
package com.example.myapp;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.Toast;
public class HomeActivity extends Activity implements AnimationListener {
// Animation
Animation animFadein;
Animation animFadeout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_start);
// load the animation
animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in);
animFadeout = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_out);
// set animation listener
animFadein.setAnimationListener(this);
ImageButton homepage =(ImageButton)findViewById(R.id.homepage);
ImageButton new_b =(ImageButton)findViewById(R.id.new_b);
ImageButton view_b =(ImageButton)findViewById(R.id.view_b);
ImageButton home_b =(ImageButton)findViewById(R.id.home_b);
ImageButton info_b =(ImageButton)findViewById(R.id.info_b);
Button back_b =(Button)findViewById(R.id.back_b);
Button site =(Button)findViewById(R.id.site);
homepage.startAnimation(animFadein);
//Click on screen to start
homepage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View homepage = (View)findViewById(R.id.homepage);
View startpage = (View)findViewById(R.id.startpage);
homepage.setVisibility(View.GONE);
homepage.startAnimation(animFadeout);
startpage.setVisibility(View.VISIBLE);
startpage.setAnimation(animFadein);};});
new_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences values = getSharedPreferences("valoar", 0);
SharedPreferences.Editor editor = values.edit();
editor.clear();
editor.commit();
View startpage = (View)findViewById(R.id.startpage);
startpage.setAnimation(animFadeout);
Intent intent = new Intent(HomeActivity.this,QuestionsActivity.class);
startActivity(intent);}});
home_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View homepage = (View)findViewById(R.id.homepage);
View startpage = (View)findViewById(R.id.startpage);
homepage.setVisibility(View.VISIBLE);
homepage.startAnimation(animFadein);
startpage.startAnimation(animFadeout);
startpage.setVisibility(View.GONE);};});
info_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View startpage = (View)findViewById(R.id.startpage);
View infopage = (View)findViewById(R.id.infopage);
ScrollView info_s = (ScrollView)findViewById(R.id.info_s);
infopage.setVisibility(View.VISIBLE);
info_s.setVisibility(View.VISIBLE);
infopage.startAnimation(animFadein);
startpage.startAnimation(animFadeout);
startpage.setVisibility(View.GONE);};});
back_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View startpage = (View)findViewById(R.id.startpage);
View infopage = (View)findViewById(R.id.infopage);
ScrollView info_s = (ScrollView)findViewById(R.id.info_s);
infopage.setVisibility(View.GONE);
info_s.setVisibility(View.GONE);
infopage.startAnimation(animFadeout);
startpage.startAnimation(animFadein);
startpage.setVisibility(View.VISIBLE);};});
**site.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent internetIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.i-amapp.com"));
internetIntent.setComponent(new ComponentName("com.android.browser","com.android.browser.BrowserActivity"));
internetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(internetIntent);};});**
}
#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 void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
/**
* Back button listener.
* Will close the application if the back button pressed twice.
*/
#Override
public void onBackPressed()
{
int backButtonCount = 0;
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this, "Press the x button to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}
It works very well in android 4.1.2, but in android 2.3.7 it crashes, and Logcat displays:
D/AndroidRuntime(2172): Shutting down VM
W/dalvikvm(2172): threadid=1: thread exiting with uncaught exception (group=0x40018560)
E/AndroidRuntime(2172): FATAL EXCEPTION: main
E/AndroidRuntime(2172): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.HomeActivity}: java.lang.NullPointerException
E/AndroidRuntime(2172): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
E/AndroidRuntime(2172): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
E/AndroidRuntime(2172): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
E/AndroidRuntime(2172): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
E/AndroidRuntime(2172): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(2172): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(2172): at android.app.ActivityThread.main(ActivityThread.java:3835)
E/AndroidRuntime(2172): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2172): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(2172): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
E/AndroidRuntime(2172): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
E/AndroidRuntime(2172): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(2172): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2172): at com.example.myapp.HomeActivity.onCreate(HomeActivity.java:107)
E/AndroidRuntime(2172): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(2172): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
E/AndroidRuntime(2172): ... 11 more
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 61K, 50% free 2724K/5379K, external 0K/0K, paused 44ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 4K, 50% free 2730K/5379K, external 507K/513K, paused 43ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 1K, 50% free 2736K/5379K, external 1068K/1524K, paused 43ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 1K, 50% free 2741K/5379K, external 1669K/2086K, paused
This is all that logcat is displaying. I can't figure out what is the problem!
Why does it crash in android 2.3?

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.

Categories

Resources