在SetText #android时抛出空指针的sharedpreferences

时间:2014-02-13 07:05:04

标签: java android android-layout android-activity sharedpreferences

我是新手编码所以在尝试创建一个接受一个布局“我的个人资料”中的值的应用程序并替换另一个布局“预订表单”中的edittext字段时。

即。在我的个人资料中,它将存储姓名,电子邮件,电话。因此,在预订页面,它应该从共享偏好中填写这些值。

我可以将这些值存储到共享首选项,但无法显示它们。代码如下,已经超过13小时,无法通过NPE尝试setText的第一部分。

我的活动档案

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

3 个答案:

答案 0 :(得分:0)

if (sharedpreferences.contains(Name))
          {
              System.out.println(sharedpreferences.getString(Name, "")); 
              ((EditText)findViewById(R.id.prof_uname)).setText(sharedpreferences.getString(Name, "")); <-------- NPE error is shown as Caught at this line

          }

MD和wqrahd给出的答案是正确的。但只是为了解释用于检索首选项的语法sharedpreferences.getString("KEY", "DEFAULT VALUE")的概念 如果“KEY”不存在则返回“DEFAULT VALUE”,否则返回首选项中保存的最新值

答案 1 :(得分:0)

由于sharedpreferences.getString(Name, null)不为null,因此唯一可以为null的其他内容是(EditText)findViewById(R.id.prof_uname)。打印出来:

EditText et = (EditText)findViewById(R.id.prof_uname);
Log.w("DetailActivity", "EditText: " + et); // null I bet

原因:您处于FragmentActivity中。显然这些元素属于尚未加载的片段?不确定,让我知道我是否正确,我们会解决它

此外,我没有看到R import


重要提示:您的格式是非常糟糕,而您提供的内容甚至没有编译(您在课程中间有一些ifs(?!))。我编辑了它,但下次你会得到-1。这种糟糕的格式化会导致错误并使调试变得困难。没有人愿意阅读你的代码或认真对待你,相信我。

尝试没有水平滚动条,代码越少越好 - 尝试仅发布重要部分。 避免空行。 Logcat时间很少有用。

答案 2 :(得分:0)

已解决,结合多个问题,来自@Mr_and_Mrs_D的输入

1)对象具有空值

EditText et = (EditText)findViewById(R.id.prof_uname);
Log.w("DetailActivity", "EditText: " + et); 

2)通过提供视图(当我在CabDetailActivity

时)来纠正它
EditText et = (EditText)v.findViewById(R.id.prof_uname);
Log.w("DetailActivity", "EditText: " + et);

虽然一切都有值,但SetText在应用程序执行时没有反映出来。后来我发现它膨胀的视图与正在使用的视图不同。

因此经过几次环顾四周,并重新分析流程。我得出结论,因为我的观点在片段中被夸大,即CabDetailFragment;哪个无法读取getSharePreferences,绕过该错误需要时间,最终我的CabDetailFragment

package com.primecabs;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import com.primecabs.home.Content;

/**
 * A fragment representing a single Cab detail screen. This fragment is either
 * contained in a {@link CabListActivity} in two-pane mode (on tablets) or a
 * {@link CabDetailActivity} on handsets.
 */
public class CabDetailFragment extends Fragment {

    /**
     * The fragment argument representing the item ID that this fragment
     * represents.
     */
    public static final String ARG_ITEM_ID = "item_id";
    // Variables for Storing Message & Button objects
    TextView name, from_loc, to_loc, phone, email, dob;
    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;
    /**
     * The dummy content this fragment is presenting.
     */
    private Content.Item mItem;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public CabDetailFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments().containsKey(ARG_ITEM_ID)) {
            // Load the content specified by the fragment
            // arguments. In a real-world scenario, use a Loader
            // to load content from a content provider.
            mItem = Content.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = null;
        sharedpreferences = this.getActivity().getSharedPreferences(
            MyPREFERENCES, Context.MODE_PRIVATE);
        if (mItem.id == "1") {
            rootView = inflater.inflate(R.layout.fragment_cab_detail_book,
                container, false);
            TextView bname = (TextView) rootView.findViewById(R.id.uname);
            TextView bphone = (TextView) rootView.findViewById(R.id.mob_num);
            TextView bemail = (TextView) rootView.findViewById(R.id.email);
            if (sharedpreferences.contains(Name)) {
                bname.setText(sharedpreferences.getString(Name, ""));
            }
            if (sharedpreferences.contains(Phone)) {
                bphone.setText(sharedpreferences.getString(Phone, ""));
            }
            if (sharedpreferences.contains(Email)) {
                bemail.setText(sharedpreferences.getString(Email, ""));
            }
        }
        if (mItem.id == "3") {
            rootView = inflater.inflate(R.layout.fragment_user_profile,
                container, false);
            // Profile Layout Display
            name = (TextView) rootView.findViewById(R.id.prof_uname);
            phone = (TextView) rootView.findViewById(R.id.prof_mob_num);
            email = (TextView) rootView.findViewById(R.id.prof_email);
            dob = (TextView) rootView.findViewById(R.id.prof_dob);
            if (sharedpreferences.contains(Name) == true) {
                name.setText(sharedpreferences.getString(Name, ""));
            }
            if (sharedpreferences.contains(Phone)) {
                (phone).setText(sharedpreferences.getString(Phone, ""));
            }
            if (sharedpreferences.contains(Email)) {
                (email).setText(sharedpreferences.getString(Email, ""));
            }
            if (sharedpreferences.contains(DOB)) {
                (dob).setText(sharedpreferences.getString(DOB, ""));
            }
        }
        if (mItem.id == "2") {
            rootView = inflater.inflate(R.layout.fragment_cab_detail_confirm,
                container, false);
            // Show the content as text in a TextView.
            // if (mItem != null) {
            // ((TextView) rootView.findViewById(R.id.cab_detail))
            // .setText(mItem.content);
        }
        return rootView;
    }
}

谢谢大家