I'm new to coding so while trying to make the an application which accepts values in one Layout "My Profile" and replaces the edittext fields in another layout "Booking form".
I.e. at My profile it will store Name, Email, Phone. So at Booking page it should fill in these values from sharedpreference.
I am able to store these values to shared preference but unable to display them. The code is as follows , have been at it for over 13hrs not able to get through the NPE at the very first section where it tried to setText.
My Activity File
package com.buses;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class DetailActivity extends FragmentActivity {
//Variables for Storing Message & Button objects
/*final EditText name= (EditText)findViewById(R.id.prof_uname);
final EditText phone= (EditText)findViewById(R.id.prof_mob_num);
final EditText email= (EditText)findViewById(R.id.prof_email);
final EditText dob= (EditText)findViewById(R.id.prof_dob);
final EditText bname= (EditText)findViewById(R.id.uname);
final EditText bphone= (EditText)findViewById(R.id.mob_num);
final EditText bemail= (EditText)findViewById(R.id.email);*/
// EditText from_loc= null;
// EditText to_loc= null;
CheckBox today, tomorrow;
TimePicker pickup;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
public static final String DOB = "dobKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cab_detail);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
// Profile Layout Display
/*
* name = (EditText)findViewById(R.id.prof_uname); phone =
* (EditText)findViewById(R.id.prof_mob_num); email =
* (EditText)findViewById(R.id.prof_email); dob =
* (EditText)findViewById(R.id.prof_dob);
*/
sharedpreferences = this.getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
// Value below prints on logcat output
System.out.println(sharedpreferences.getString(Name, ""));
// NPE error is shown as Caught at the line below
((EditText) findViewById(R.id.prof_uname))
.setText(sharedpreferences.getString(Name, null));
}
if (sharedpreferences.contains(Phone)) {
((EditText) findViewById(R.id.prof_mob_num))
.setText(sharedpreferences.getString(Phone, ""));
}
if (sharedpreferences.contains(Email)) {
((EditText) findViewById(R.id.prof_email))
.setText(sharedpreferences.getString(Email, ""));
}
if (sharedpreferences.contains(DOB)) {
((EditText) findViewById(R.id.prof_dob)).setText(sharedpreferences
.getString(DOB, ""));
}
// Book Layout
/*
* bname = (EditText)findViewById(R.id.uname); bphone =
* (EditText)findViewById(R.id.mob_num); bemail =
* (EditText)findViewById(R.id.email);
*/
if (sharedpreferences.contains(Name)) {
((EditText) findViewById(R.id.uname)).setText(sharedpreferences
.getString(Name, ""));
}
if (sharedpreferences.contains(Phone)) {
((EditText) findViewById(R.id.mob_num)).setText(sharedpreferences
.getString(Phone, ""));
}
if (sharedpreferences.contains(Email)) {
((EditText) findViewById(R.id.email)).setText(sharedpreferences
.getString(Email, ""));
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(CabDetailFragment.ARG_ITEM_ID, getIntent()
.getStringExtra(CabDetailFragment.ARG_ITEM_ID));
CabDetailFragment fragment = new CabDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.cab_detail_container, fragment).commit();
}
}
void onCreateContextMenu() {}
@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.navigateUpTo(this, new Intent(this, ListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
// When Book Button is clicked
public void send(View v) {
new SendEmailAsyncTask().execute();
}
class SendEmailAsyncTask extends AsyncTask<Void, Void, Boolean> {
// Email Code
// if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(),
// "SendEmailAsyncTask()");
// email Code
@Override
protected Boolean doInBackground(Void... params) {
if (BuildConfig.DEBUG)
Log.v(SendEmailAsyncTask.class.getName(), "doInBackground()");
try {
m.send();
return true;
} catch (AuthenticationFailedException e) {
Log.e(SendEmailAsyncTask.class.getName(), "Bad account details");
e.printStackTrace();
return false;
} catch (MessagingException e) {
Log.e(SendEmailAsyncTask.class.getName(), m.getTo(null)
+ "failed");
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
// Save Option use here
public void save(View v) {
new SaveEmailAsyncTask().execute();
}
class SaveEmailAsyncTask extends AsyncTask<Void, Void, Boolean> {
// Email Code
// if (BuildConfig.DEBUG) Log.v(SaveEmailAsyncTask.class.getName(),
// "SaveEmailAsyncTask()");
// email code
// }
@Override
protected Boolean doInBackground(Void... params) {
if (BuildConfig.DEBUG)
Log.v(SaveEmailAsyncTask.class.getName(), "doInBackground()");
try {
m.send();
return true;
} catch (AuthenticationFailedException e) {
Log.e(SaveEmailAsyncTask.class.getName(), "Bad account details");
e.printStackTrace();
return false;
} catch (MessagingException e) {
Log.e(SaveEmailAsyncTask.class.getName(), m.getTo(null)
+ "failed");
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
}
Log.cat file
Note all layouts open perfectly when no values are present in sharedpreferences because "if (sharedpreferences.contains(Name))" is not called
E/Trace(2222): error opening trace file: No such file or directory (2)
D/dalvikvm(2222): GC_FOR_ALLOC freed 86K, 8% free 2670K/2880K, paused 73ms, total 77ms
I/dalvikvm-heap(2222): Grow heap (frag case) to 3.329MB for 635812-byte allocation
D/dalvikvm(2222): GC_FOR_ALLOC freed 3K, 7% free 3288K/3504K, paused 198ms, total 198ms
D/dalvikvm(2222): GC_CONCURRENT freed <1K, 7% free 3289K/3504K, paused 14ms+92ms, total 162ms
D/libEGL(2222): loaded /system/lib/egl/libEGL_emulation.so
D/(2222): HostConnection::get() New Host Connection established 0x2a147768, tid 2222
D/libEGL(2222): loaded /system/lib/egl/libGLESv1_CM_emulation.so
D/libEGL(2222): loaded /system/lib/egl/libGLESv2_emulation.so
W/EGL_emulation(2222): eglSurfaceAttrib not implemented
D/OpenGLRenderer(2222): Enabling debug mode 0
I/Choreographer(2222): Skipped 174 frames! The application may be doing too much work on its main thread.
I/System.out(2222): Jasneet
D/AndroidRuntime(2222): Shutting down VM
W/dalvikvm(2222): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
E/AndroidRuntime(2222): FATAL EXCEPTION: main
E/AndroidRuntime(2222): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.primecabs/com.primecabs.CabDetailActivity}: java.lang.NullPointerException
E/AndroidRuntime(2222): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
E/AndroidRuntime(2222): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(2222): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(2222): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(2222): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(2222): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2222): at android.app.ActivityThread.main(ActivityThread.java:5041)
E/AndroidRuntime(2222): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2222): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2222): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2222): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2222): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(2222): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2222): at com.primecabs.CabDetailActivity.onCreate(CabDetailActivity.java:110)
E/AndroidRuntime(2222): at android.app.Activity.performCreate(Activity.java:5104)
E/AndroidRuntime(2222): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
E/AndroidRuntime(2222): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
E/AndroidRuntime(2222): ... 11 more