【问题标题】:Shared preferences, where do they go?共享偏好,它们去哪儿了?
【发布时间】:2016-04-21 12:00:26
【问题描述】:

我知道共享首选项是如何工作的,但我只是不知道在下面的代码中的何处插入代码以保存用户数据。我有一个登录后台任务,可以完成所有工作和注册。我希望应用程序打开到用户登录时的启动页面。无法从其他答案中弄清楚

登录.java

Button bttnLogin;
EditText loginEmail, loginPassword;
TextView regLink;
AlertDialog.Builder alert;


@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginEmail = (EditText) findViewById(R.id.email);
    loginPassword = (EditText) findViewById(R.id.password);

    regLink = (TextView) findViewById(R.id.regLink);
    regLink.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivity(new Intent(Login.this, Register.class));

        }
    });


    bttnLogin = (Button) findViewById(R.id.bttnLogin);
    bttnLogin.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            if (loginEmail.getText().toString().equals("") || loginPassword.getText().toString().equals(""))
            {
                alert = new AlertDialog.Builder(Login.this);
                alert.setTitle("Login Failed");
                alert.setMessage("Try again");
                alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                        dialog.dismiss();
                    }

                });

                AlertDialog alertDialog = alert.create();
                alertDialog.show();
            } else  //if user provides proper data
            {
                BackgroundTask backgroundTask = new BackgroundTask(Login.this);
                backgroundTask.execute("login", loginEmail.getText().toString(), loginPassword.getText().toString());
            }

        }


    });

Register.java

        private Button regButton;
        public EditText regName;
        public EditText regEmail;
        public EditText regPassword;
        public EditText conPassword;
        private AlertDialog.Builder alert;



@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    regName = (EditText) findViewById(R.id.name);
    regEmail = (EditText) findViewById(R.id.email);
    regPassword = (EditText) findViewById(R.id.password);
    conPassword = (EditText) findViewById(R.id.conPassword);
    regButton = (Button) findViewById(R.id.regButton);
    regButton.setOnClickListener(this);
}


@Override
public void onClick(View v)
{

    if (regName.getText().toString().equals("") || regEmail.getText().toString().equals("") ||  regPassword.getText().toString().equals("") || conPassword.getText().toString().equals(""))
    {
        alert = new AlertDialog.Builder(Register.this);
        alert.setTitle("Something not quite right");
        alert.setMessage("Please fill in all the fields");
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {

            @Override
            public void onClick(DialogInterface dialog, int which)
            {

                dialog.dismiss();
            }

        });

        AlertDialog alertDialog = alert.create();
        alertDialog.show();

    } else if (!(regPassword.getText().toString().equals(conPassword.getText().toString())))
    {

        alert = new AlertDialog.Builder(Register.this);
        alert.setTitle("Passwords do not match");
        alert.setMessage("Try Again");
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {

            @Override
            public void onClick(DialogInterface dialog, int which)
            {

                dialog.dismiss();

                conPassword.setText("");
                regPassword.setText("");
            }

        });

        AlertDialog alertDialog = alert.create();
        alertDialog.show();


    }
    else //if user provides proper data
    {
        BackgroundTask backgroundTask = new BackgroundTask(Register.this);
        backgroundTask.execute("register", regName.getText().toString(), regEmail.getText().toString()
                , regPassword.getText().toString(), conPassword.getText().toString());
    }

BackgroundTask.java

 public class BackgroundTask extends AsyncTask<String,Void,String>
{

private Context context;
private Activity activity;
private String reg_url = "http://blaah.com/register.php";
private String login_url = "http://blaah.com/login.php";
private AlertDialog.Builder builder;
private ProgressDialog progressDialog;


public BackgroundTask(Context context)
{

    this.context = context;
    activity = (Activity) context;
}

@Override
protected void onPreExecute()
{
    builder = new AlertDialog.Builder(activity);
    progressDialog = new ProgressDialog(context);
    progressDialog.setTitle("Please wait");
    progressDialog.setMessage("Connecting to Server...");
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);
    progressDialog.show();
}

@Override
protected String doInBackground(String... params)
{

    String method = params[0];

    if (method.equals("register"))
    {

        try
        {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String name = params[1];
            String email = params[2];
            String username = params[3];
            String password = params[4];
            String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                    URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
                    URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null)
            {

                stringBuilder.append(line).append("\n");

            }


            httpURLConnection.disconnect();
            Thread.sleep(8000);
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }

    }
    else if (method.equals("login"))
    {
        try
        {
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));


            String username,password;

            username = params[1];
            password = params [2];
            String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" +
                    URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null)
            {

                stringBuilder.append(line + "\n");

            }


            httpURLConnection.disconnect();
            Thread.sleep(5000);
            return stringBuilder.toString().trim();


        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        } catch (ProtocolException e)
        {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    return null;
}

@Override
protected void onProgressUpdate(Void... values)
{
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String json)
{
   try
   {

       progressDialog.dismiss();


       Log.v("JSON", json);
       JSONObject jsonObject = new JSONObject(json);
       JSONArray jsonArray = jsonObject.getJSONArray("server_response");
       JSONObject jsonobject = jsonArray.getJSONObject(0);
       String code = jsonobject.getString("code");
       String message = jsonobject.getString("message");



       if(code.equals("reg_true"))
       {
           showDialog("Sucessful registration.Thank you.Enjoy_AS!", message, code);
       }

       else if (code.equals("reg_false"))
       {
           showDialog("User Already exists", message, code);
       }

       else if (code.equals("login_true"))
       {
           Toast.makeText(context, "You are logged in", Toast.LENGTH_LONG).show();
           Intent intent = new Intent(activity, SplashScreen.class);
           activity.startActivity(intent);


       } else if (code.equals("login_false"))
       {
           showDialog("Login Error", message, code);
       }


   } catch (JSONException e){
       e.printStackTrace();
   }


}

public void  showDialog(String title,String message,String code)
{

    builder.setTitle(title);
    if (code.equals("reg_true") || code.equals("reg_false"))
    {
        builder.setMessage(message);//message form server
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener()

        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                activity.finish();

            }
        });


    }

    else if (code.equals("login_false"))
    {


        builder.setMessage(message);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                EditText loginEmail, loginPassword;
                loginEmail = (EditText) activity.findViewById(R.id.email);
                loginPassword = (EditText) activity.findViewById(R.id.password);
                loginEmail.setText("");
                loginPassword.setText("");
                dialog.dismiss();

            }


        });


    }
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

}

我希望应用打开到的初始屏幕

 final String TAG = this.getClass().getName();
private static int SPLASH_TIME_OUT = 4000;
private TextView saying;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_splash_screen);

    saying = (TextView) findViewById(R.id.saying);
    Typeface mainHead =  Typeface.createFromAsset(getAssets(), "fonts/emporo.TTF");
    saying.setTypeface(mainHead);
    //Set text custom font for subhead text


    new Handler().postDelayed(new Runnable()
    {


        @Override
        public void run()
        {
            // This method will be executed once the timer is over
            // Start your app main activity
            Intent i = new Intent(SplashScreen.this, HomeScreen.class);
            startActivity(i);

            // close this activity
            finish();
        }
    }, SPLASH_TIME_OUT);

}
}

【问题讨论】:

    标签: android preferences shared


    【解决方案1】:

    这是我在每个 Android 应用程序中使用的 SharedPreferences

    import android.content.Context;
    import android.content.SharedPreferences;
    
    /**
     * Created by Jimit Patel on 30/07/15.
     */
    public class Prefs {
    
        private static final String TAG = Prefs.class.getSimpleName();
    
        private static final String MY_APP_PREFS = "my_app";
    
        /**
         * <p>Provides Shared Preference object</p>
         * @param context
         * @return
         */
        private static SharedPreferences getPrefs(Context context) {
            return context.getSharedPreferences(MY_APP_PREFS, Context.MODE_PRIVATE);
        }
    
        /**
         * <p>Saves a string value for a given key in Shared Preference</p>
         * @param context
         * @param key
         * @param value
         */
        public static void setString(Context context, String key, String value) {
            getPrefs(context).edit().putString(key, value).apply();
        }
    
        /**
         * <p>Saves integer value for a given key in Shared Preference</p>
         * @param context
         * @param key
         * @param value
         */
        public static void setInt(Context context, String key, int value) {
            getPrefs(context).edit().putInt(key, value).apply();
        }
    
        /**
         * <p>Saves float value for a given key in Shared Preference</p>
         * @param context
         * @param key
         * @param value
         */
        public static void setFloat(Context context, String key, float value) {
            getPrefs(context).edit().putFloat(key, value).apply();
        }
    
        /**
         * <p>Saves long value for a given key in Shared Preference</p>
         * @param context
         * @param key
         * @param value
         */
        public static void setLong(Context context, String key, long value) {
            getPrefs(context).edit().putLong(key, value).apply();
        }
    
        /**
         * <p>Saves boolean value for a given key in Shared Preference</p>
         * @param context
         * @param key
         * @param value
         */
        public static void setBoolean(Context context, String key, boolean value) {
            getPrefs(context).edit().putBoolean(key, value).apply();
        }
    
        /**
         * Provides string from the Shared Preferences
         * @param context
         * @param key
         * @param defaultValue
         * @return
         */
        public static String getString(Context context, String key, String defaultValue) {
            return getPrefs(context).getString(key, defaultValue);
        }
    
        /**
         * Provides int from Shared Preferences
         * @param context
         * @param key
         * @param defaultValue
         * @return
         */
        public static int getInt(Context context, String key, int defaultValue) {
            return getPrefs(context).getInt(key, defaultValue);
        }
    
        /**
         * Provides boolean from Shared Preferences
         * @param context
         * @param key
         * @param defaultValue
         * @return
         */
        public static boolean getBoolean(Context context, String key, boolean defaultValue) {
            return getPrefs(context).getBoolean(key, defaultValue);
        }
    
        /**
         * Provides float value from Shared Preferences
         * @param context
         * @param key
         * @param defaultValue
         * @return
         */
        public static float getFloat(Context context, String key, float defaultValue) {
            return getPrefs(context).getFloat(key, defaultValue);
        }
    
        /**
         * Provides long value from Shared Preferences
         * @param context
         * @param key
         * @param defaultValue
         * @return
         */
        public static long getLong(Context context, String key, long defaultValue) {
            return getPrefs(context).getLong(key, defaultValue);
        }
    
        public static void clearPrefs(Context context) {
            getPrefs(context).edit().clear().commit();
        }
    }
    

    要使用它,您可以使用其中的那些功能

    【讨论】:

      【解决方案2】:

      从服务器收到登录成功后,执行以下代码

      SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);    
      SharedPreferences.Editor editor = sharedpreferences.edit();
      editor.putString("hasLoggedIn", true);
      editor.commit();
      

      而无论你想在哪里检查用户是否登录,都可以使用以下代码进行检查。

      boolean hasLoggedIn = sharedpreferences.getBoolean("hasLoggedIn", false);
      

      如果 hasLogged 布尔值为 true,则表示用户已登录。

      【讨论】:

        【解决方案3】:

        您创建了共享首选方法并保存

        您可以使用此代码 ...对您有帮助

        savaLoginValue(mobileno, password, userTypeId, clientid);

        private void savaLoginValue(String mobileno, String password) 
        {
                SharedPreferences login = getSharedPreferences("Preferance", MODE_PRIVATE);
                SharedPreferences.Editor editor = login.edit();
                editor.putString("SPMobileno", mobileno);
                editor.putString("SPPass", password);
                editor.commit();
        }

        BackgoundTask.Class

        public class BackgroundTask extends AsyncTask<String,Void,String>
        {
        
        private Context context;
        private Activity activity;
        private String reg_url = "http://blaah.com/register.php";
        private String login_url = "http://blaah.com/login.php";
        private AlertDialog.Builder builder;
        private ProgressDialog progressDialog;
        
        
        public BackgroundTask(Context context)
        {
        
            this.context = context;
            activity = (Activity) context;
        }
        
        @Override
        protected void onPreExecute()
        {
            builder = new AlertDialog.Builder(activity);
            progressDialog = new ProgressDialog(context);
            progressDialog.setTitle("Please wait");
            progressDialog.setMessage("Connecting to Server...");
            progressDialog.setIndeterminate(true);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
        
        @Override
        protected String doInBackground(String... params)
        {
        
            String method = params[0];
        
            if (method.equals("register"))
            {
        
                try
                {
                    URL url = new URL(reg_url);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                    String name = params[1];
                    String email = params[2];
                    String username = params[3];
                    String password = params[4];
                    String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                            URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
                            URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
                    bufferedWriter.write(data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    outputStream.close();
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line = "";
                    while ((line = bufferedReader.readLine()) != null)
                    {
        
                        stringBuilder.append(line).append("\n");
        
                    }
        
        
                    httpURLConnection.disconnect();
                    Thread.sleep(8000);
                    return stringBuilder.toString().trim();
        
                } catch (MalformedURLException e)
                {
                    e.printStackTrace();
                } catch (IOException e)
                {
                    e.printStackTrace();
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
        
            }
            else if (method.equals("login"))
            {
                try
                {
                    URL url = new URL(login_url);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        
        
                    String username,password;
        
                    username = params[1];
                    password = params [2];
                    String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" +
                            URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
                    bufferedWriter.write(data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    outputStream.close();
        
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line = "";
                    while ((line = bufferedReader.readLine()) != null)
                    {
        
                        stringBuilder.append(line + "\n");
        
                    }
        
        
                    httpURLConnection.disconnect();
                    Thread.sleep(5000);
                    return stringBuilder.toString().trim();
        
        
                } catch (MalformedURLException e)
                {
                    e.printStackTrace();
                } catch (ProtocolException e)
                {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e)
                {
                    e.printStackTrace();
                } catch (IOException e)
                {
                    e.printStackTrace();
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        
            return null;
        }
        
        @Override
        protected void onProgressUpdate(Void... values)
        {
            super.onProgressUpdate(values);
        }
        
        @Override
        protected void onPostExecute(String json)
        {
           try
           {
        
               progressDialog.dismiss();
        
        
               Log.v("JSON", json);
               JSONObject jsonObject = new JSONObject(json);
               JSONArray jsonArray = jsonObject.getJSONArray("server_response");
               JSONObject jsonobject = jsonArray.getJSONObject(0);
               String code = jsonobject.getString("code");
               String message = jsonobject.getString("message");
        
        
        
               if(code.equals("reg_true"))
               {
                   showDialog("Sucessful registration.Thank you.Enjoy_AS!", message, code);
               }
        
               else if (code.equals("reg_false"))
               {
                   showDialog("User Already exists", message, code);
               }
        
               else if (code.equals("login_true"))
               {
                 
                 // Please You Can Take The Username & Password And Save It For Shared Preference Then Share Preference File Any where To Use It.. 
                   Toast.makeText(context, "You are logged in", Toast.LENGTH_LONG).show();
                   Intent intent = new Intent(activity, SplashScreen.class);
                   activity.startActivity(intent);
        
        
               } else if (code.equals("login_false"))
               {
                   showDialog("Login Error", message, code);
               }
        
        
           } catch (JSONException e){
               e.printStackTrace();
           }
        
        
        }
        
        public void  showDialog(String title,String message,String code)
        {
        
            builder.setTitle(title);
            if (code.equals("reg_true") || code.equals("reg_false"))
            {
                builder.setMessage(message);//message form server
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
        
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                        activity.finish();
        
                    }
                });
        
        
            }
        
            else if (code.equals("login_false"))
            {
        
        
                builder.setMessage(message);
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        EditText loginEmail, loginPassword;
                        loginEmail = (EditText) activity.findViewById(R.id.email);
                        loginPassword = (EditText) activity.findViewById(R.id.password);
                        loginEmail.setText("");
                        loginPassword.setText("");
                        dialog.dismiss();
        
                    }
        
        
                });
        
        
            }
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
        
        }

        【讨论】:

          【解决方案4】:

          只需创建一个名为 SessionManagement.java 的类并粘贴以下代码

          import android.content.Context;
          import android.content.Intent;
          import android.content.SharedPreferences;
          import java.util.HashMap;
          
          /**
          * Created by naveen.tp on 21/4/2016.
          */
          public class SessionManagement {
          
          SharedPreferences sharedPreferences;
          SharedPreferences.Editor editor;
          Context context;
          
          int PRIVATE_MODE = 0;
          
          private static final String PREF_NAME = "YourPreferences";
          
          private static final String IS_LOGIN = "isLogedIn";
          
          //Constructor
          public SessionManagement(Context context) {
          
              this.context = context;
              sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
              editor = sharedPreferences.edit();
          }
          
          
          //Create Login Session
          public void createLoginSession(boolean flag)
          {
              editor.putBoolean(IS_LOGIN, flag);
              editor.commit();
          }
          
          //check for isLogin returns True/false
          public boolean isLoggedIn()
          {
              return sharedPreferences.getBoolean(IS_LOGIN, false);
          }
          
          }
          

          在您的代码BackgroundTask.java onPostExcecute 方法中

          已编辑

          else if(code.equals("login_true"))
          {
           SessionManagement session = new SessionManagement(context);
           session.createLoginSession(true);
           Toast.makeText(context, "You are logged in", Toast.LENGTH_LONG).show();
           Intent intent = new Intent(activity, SplashScreen.class);
           activity.startActivity(intent);
          }
          

          您也可以在下次启动画面中检查登录状态,只需调用

          已编辑

          SessionManagement session = new SessionManagement(this); 
          boolean isLogin = session.isLoggedIn();
          if(isLogin)
          {
            //Already logged in
          }
          else
          {
            //Not logged in
          }
          

          希望对你有所帮助!

          【讨论】:

          • 试过这个但没用,在 boolean isLogin = session.isLoggedIn(); 上给我错误。毫无疑问我做错了什么。
          • 嘿,抱歉一直忙,运行应用程序时出现错误,java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.xxxxxxxx.project.userdata.SessionManagement.isLoggedIn()' on一个空对象引用。我必须在 session.isLoggedIn() 中为会话创建一个变量; .我已经把布尔isLogin放在splashscreen的onCreate方法中但是它只是抛出了错误。
          • 你只需要调用'Sessionmanagement session = SessionManagement(this);'在调用方法“session.isLoggedIn()”之前的 onCreate 中。效果很好。
          • 好的,仍然无法正常工作的应用程序崩溃。这是错误“尝试调用虚拟方法'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)'在空对象引用上”。唯一的区别是 android studio 让我在 Session 管理之前放新,SessionManagement session = new SessionManagement(context); .
          • 查看我编辑的答案。它已经过测试并在我的最后工作。
          猜你喜欢
          • 2011-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-14
          • 2011-03-03
          • 2014-03-15
          相关资源
          最近更新 更多