在导致空指针的活动中使用共享首选项,这让我起了作用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在导致空指针的活动中使用共享首选项,这让我起了作用相关的知识,希望对你有一定的参考价值。

所以我在尝试在我的登录活动之外的任何其他活动中调用共享首选项值时遇到问题,这是我最初声明它的地方。我需要能够将这些值调用到文本编辑窗口以识别聊天客户端。我已成功存储用户名和电子邮件地址,并在登录活动中的创业公司之间保持不变。但那就是我遇到障碍的地方。我需要调用我的联系人视图适配器中的值并在屏幕上显示用户名,以下是两个活动:

     public class LoginActivity extends AppCompatActivity {
            SharedPreferences.Editor editor;
            SharedPreferences pref; //Variable to initialize shared pref instance
            TextView txtName, txtEmail; //Identifiers for ui
            public final String Name = "nameKey";//Objects to hold values
            public final String Email = "emailKey";

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login_activity);


            //Code to make sure the right values are stored
            txtName = (EditText) findViewById(R.id.name);
            txtEmail = (EditText) findViewById(R.id.email);

            // creating an shared Preference file for the information to be stored
            // first argument is the name of file and second is the mode.


            pref = getApplicationContext().getSharedPreferences("cheese", 0);
            // get editor to edit in file
            editor = pref.edit();

            // as now we have information in string. Lets store them with the help of editor
            editor.putString("Name", Name);
            editor.putString("Email", Email);
            editor.commit();
            // commit the values


            //This logic block checks if there is a stored value upon app start.
            if (pref.contains(Name)) {
                txtName.setText(pref.getString(Name, ""));

            }
            if (pref.contains(Email)) {
                txtEmail.setText(pref.getString(Email, ""));
            }
            View submitButton = findViewById(R.id.btn_login);

    //8
            submitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Context context = getApplicationContext();
                    Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
                    startActivity(intent);
                    //this logic stores the values when the user logs in
                    String n = txtName.getText().toString();
                    String e = txtEmail.getText().toString();
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putString(Name, n);
                    editor.putString(Email, e);
                    editor.commit();




                    //firebase integration phase
                    // Write a message to the database
                    FirebaseDatabase database = FirebaseDatabase.getInstance();
                    DatabaseReference myRef = database.getReference();
                    myRef.push().setValue(e);

                    //myRef.setValue(email.getText().toString());

                    // Read from the database
                    myRef.addValueEventListener(new ValueEventListener() {
                        private static final String TAG = "poop";
                        //logs
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // This method is called once with the initial value and again
                            // whenever data at this location is updated.
                            String value = dataSnapshot.getValue(String.class);
                            Log.d(TAG, "Value is: " + value);
                        }
                        //in case there is a problem
                        @Override
                        public void onCancelled(DatabaseError error) {
                            // Failed to read value
                            Log.w(TAG, "Failed to read value.", error.toException());
                        }
                    });


                }


            });

        }



    }















    package com.dysrupts.atom;

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import java.util.Map;

    public class ContactViewAdapter extends BaseAdapter {
        private Context context;
        private Map<String, Store> stores;
        private LayoutInflater inflater = null;
        private View.OnTouchListener onTouchListener;



        public ContactViewAdapter(Context context, Map<String, Store> stores, View.OnTouchListener onTouchListener) {

            this.context = context;
            this.stores = stores;
            this.onTouchListener = onTouchListener;
        }

        protected LayoutInflater getInflater() {

            if (inflater == null) {
                inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }

            return inflater;
        }

        protected Context getContext() {

            return context;
        }

        protected Map<String, Store> getStores() {

            return stores;
        }

        @Override
        public int getCount() {

            return stores.size();
        }

        @Override
        public Object getItem(int position) {

            // This way of getting ordered stores is an overkill, but that's not the point of this demo
            return getStores().values().toArray()[position];
        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View vi = convertView;

            if (vi == null)
                vi = getInflater().inflate(R.layout.contact_cell_view, null);

            Store store = (Store)getItem(position);

            TextView displayName = (TextView)vi.findViewById(R.id.number_name);
            ImageView contentIndicator = (ImageView)vi.findViewById(R.id.new_content);
            TextView UserName = (TextView)vi.findViewById(R.id.UserName);

             //this is the method i need to call to----------------------------------------
            UserName.setText();


            displayName.setText(store.getInstance().getStringIdentifier());

            contentIndicator.setVisibility(store.hasNewMessages() ? View.VISIBLE : View.INVISIBLE);

            vi.setOnTouchListener(getOnTouchListener());

            return vi;
        }

        protected View.OnTouchListener getOnTouchListener() {

            return onTouchListener;
        }





    }

感谢您的时间

编辑-----继承异常进程:com.dysrupts.atom,PID:9009 java.lang.RuntimeException:无法启动活动ComponentInfo {com.dysrupts.atom / com.dysrupts.atom.ContactActivity}:java.lang .NullPointerException:尝试在android.app.ActivityThread.performLaunchActivity(ActivityThread)上的空对象引用上调用接口方法'java.lang.String android.content.SharedPreferences.getString(java.lang.String,java.lang.String)' .java:2697)在Android.app.A活动中的android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)android.app.ActivityThread $ 6.handleMessage(ActivityThread.java:1509)的android.app.ActivityThread.-wrap12(ActivityThread.java) )在android.os.Handler.dispatchMessage(Handler.java:102)的android.app.Looper.loop(Looper.java:163)在android.app.ActivityThread.main(ActivityThread.java:6228)的java.lang上位于com.android.internal.os.ZygoteInit.m的com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)的.reflect.Method.invoke(Native Method) ain(ZygoteInit.java:776)引起:java.lang.NullPointerException:尝试调用接口方法'java.lang.String android.content.SharedPreferences.getString(java.lang.String,java.lang.String)'on com.dysrupts.atom.ContactViewAdapter。(ContactViewAdapter.java:48)的空对象引用,位于android.app.Activity.performCreate(Activity.java)的com.dysrupts.atom.ContactActivity.onCreate(ContactActivity.java:110)。 6742)在android.app.Anstrumentation.callActivityOnCreate(Instrumentation.java:1122)的android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2650)android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)。在Android.os.Looper的android.os.Handler.dispatchMessage(Handler.java:102)的android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1509)上的app.ActivityThread.-wrap12(ActivityThread.java)。循环(Looper.java:163)在android.app.ActivityThread.main(ActivityThread.java:6228)java.lang.reflect.Method.invoke(本地方法)com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)D / NetworkSecurityConfig:No Network Security使用平台默认W / SyncTree指定Config:侦听/失败:DatabaseError:权限被拒绝

答案

我认为你复杂的事情。

只需添加一些键值对:

SharedPreferences.Editor editor = getSharedPreferences("user_data", MODE_PRIVATE).edit();
editor.putString("name", name)
editor.apply();

然后阅读他们想要的任何地方:

SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
String name = prefs.getString("name", default_value);
另一答案

我会创建另一个类来保存用户详细信息:

public class UserSession {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context context;

String username;

public UserSession(Context context){
    this.context= context;
    prefs = context.getSharedPreferences("whatever", Context.MODE_PRIVATE);
    editor = prefs.edit();
}

public void SetLoggedIn(boolean loggedin, String username){
    editor.putBoolean("loggedinmode", loggedin);
    editor.putString("username", username);
    editor.commit();
}

public boolean loggedin(){
    return prefs.getBoolean("loggedinmode", false);
}

public String username(){
    return prefs.getString("username", username);
}

}

在这里,您只需传递2个值,无论是激活usersession还是用户名。然后在任何活动中,您可以调用username方法并获取当前用户详细信息。如果需要,您可以添加更多值。然后,您只需在活动中将其添加到您传递详细信息的位置:

private UserSession userSession = new UserSession(this);
userSession.SetLoggedIn(true, stringContainingUsername);
另一答案

您的错误消息表明您在尝试访问共享首选项时收到空指针异常:

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object 

您还没有发布您的ContactActivity代码(您只发布了与活动不同的ContactAdapter类),但是从错误消息中我可以猜到您在尝试访问之前没有初始化您的sharedPrefs对象。请注意,initialize意味着实际将某些内容放入变量中,而不仅仅是声明它。

您需要以下内容:

    SharedPreferences pref; // declare the object
    pref = getApplicationContext().getSharedPreferences("cheese", 0); // initialize the object
    String name = prefs.get("nameKey");
    String email = prefs.get("emailKey");

我还注意到,当您单击提交按钮时,在执行该块的任何逻辑之前调用startActivity(intent);。当调用startActivity()时,它就是这样:启动一个新活动,我相信会跳过以下所有代码。即,editor.putString();甚至没有运行,因此没有任何价值投入到这种偏好中。移动

    Context context = getApplicationContext();
    Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
    startActivity(intent);

到onClick()方法的底部。

以上是关于在导致空指针的活动中使用共享首选项,这让我起了作用的主要内容,如果未能解决你的问题,请参考以下文章

Android:在JUnit中传递上下文并使用共享首选项

在每个活动中使用共享首选项

使用服务中的地理位置更新活动时的时序问题(使用共享首选项将地理位置从服务传输到活动)

即使在应用关闭时,共享首选项也会永久传递给另一个活动

公共共享首选项导致应用程序崩溃

将Bundle对象保存到共享首选项中[重复]