【发布时间】:2014-02-13 07:05:04
【问题描述】:
我是编码新手,因此在尝试制作一个接受一个布局“我的个人资料”中的值并替换另一个布局“预订表单”中的编辑文本字段的应用程序时。
即在我的个人资料中,它将存储姓名、电子邮件、电话。所以在预订页面它应该从 sharedpreference 中填写这些值。
我可以将这些值存储到共享偏好中,但无法显示它们。代码如下,在它尝试设置文本的第一部分已经超过 13 小时无法通过 NPE。
我的活动档案
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 文件
请注意,当 sharedpreferences 中不存在任何值时,所有布局都会完美打开,因为未调用“if (sharedpreferences.contains(Name))”
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
【问题讨论】:
-
试试这个
((EditText)findViewById(R.id.prof_uname)).setText(sharedpreferences.getString(Name, "") -
设置这个:your_edittext.setText(sharedpreferences.getString(Name, ""));
-
检查
R.id.prof_uname是否存在 -
全部完成.. 您将在评论块中找到 your_edittext 各个对象。最初 getString(Name,null) 仅设置为 getString(Name,"")。事实上,即使将第一行放在 if 块中,注释块之外的 SetText 的第一行也会通过 NPE R.id.prof_uname 存在..
-
您在共享偏好中将数据保存在哪里?
标签: java android android-layout android-activity sharedpreferences