【问题标题】:SharedPreferences not reading DataSharedPreferences 不读取数据
【发布时间】:2012-05-05 11:00:39
【问题描述】:

我保存了两部分数据,用户密码和用户名以供以后使用的数据和字母的随机组合,然后检查应用程序何时再次执行以避免再次出现登录屏幕。

我昨天有这个工作,但由于某种原因,我预计我在添加功能时放错了代码,现在无法让它再次工作,我已经尝试了一整天来修复它,但我不能。

EDIT1:出于某种原因,它转到“CheckPrefs”方法的 else 语句,我无法理解。

EDIT2:它可以很好地保存首选项并达到意图,但是它无法读取它。

代码:

public static final String PREFS_NAME = "MyPregs";
    public static final String PREFS_CHECK = "CheckSignedIn";
    public static final String UID ="";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        CheckPrefs();

        // Login button clicked
        ok = (Button) findViewById(R.id.btn_login);
        ok.setOnClickListener(this);

        result = (TextView) findViewById(R.id.lbl_result);

    } 
    private void CheckPrefs() {
        // TODO Auto-generated method stub
        //checks to see if the user has signed in before if they have it gets there data from SharedPreferences and checks against our database via HttpPost.
        SharedPreferences settings = getSharedPreferences(PREFS_CHECK, 0);
        String SCheck1 = settings.getString("key4", null);
        if (SCheck1 != null  && equals(UID)) {
            Intent c = new Intent(this, CheckUserInfo.class);
            startActivity(c);   

        } else {

        }



    }
    //create bracket.

    public void postLoginData() {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();

        /* login.php returns true if username and password is equal to saranga */
        HttpPost httppost = new HttpPost("http://gta5news.com/login.php");

        try {
            // Add user name and password
            uname = (EditText) findViewById(R.id.txt_username);
            String username = uname.getText().toString();

            pword = (EditText) findViewById(R.id.txt_password);
            String password = pword.getText().toString();

            SharedPreferences signedin = getSharedPreferences(PREFS_CHECK, 0);
            SharedPreferences.Editor editor1 = signedin.edit();
            editor1.putString("key4", UID);
            editor1.commit();


            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("key1", username);
            editor.putString("key2", password);
            editor.commit();

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            Log.w("HttpPost", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);

            String str = inputStreamToString(response.getEntity().getContent())
                    .toString();
            Log.w("HttpPost", str);

            if (str.toString().equalsIgnoreCase("true")) {
                Log.w("HttpPost", "TRUE");
                result.setText("Login successful");
                try {Thread.sleep(250);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Intent login = new Intent(LogIn.this, ChatService.class);
                startActivity(login);

            } else {
                Log.w("HttpPost", "FALSE");
                result.setText(str);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Return full string
        return total;
    }

    public void onClick(View view) {
        if (view == ok) {

            postLoginData();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
        }
        // Click end
    }
    // if statement
}

// class ends here

【问题讨论】:

  • if (SCheck1 != null && equals(UID))?总是假的
  • 怎么样?对我来说,这似乎是一个正确的说法。
  • 试图得到澄清。如果我错了,请纠正我:你想从共享首选项中提取 key4 值,如果 key4 的值与常量 UID 匹配,你想进入你的 IF 语句吗?对吗?

标签: java android sharedpreferences preferences


【解决方案1】:

需要查看您将首选项保存在哪里,以便我们将其与您如何称呼您的首选项相匹配...但是,这是一个错字吗?

public static final String PREFS_NAME = "MyPregs"; 

应该是“MyPrefs”而不是“MyPregs”吗?

【讨论】:

  • 是的,是的,一旦我解决了这个问题,我就会改变它。
【解决方案2】:

你有

if (SCheck1 != null  && equals(UID))

但你是不是想说

if (SCheck1 != null  && !SCheck.equals(UID))

?

【讨论】:

  • 没有?我想检查 UID 是否在共享首选项中,而不是检查它是否不等于 UID。
【解决方案3】:

您也可以使用“反向比较”模式:

if (UID.equals(SCheck1)) {

} else {

}

这样,您不必费心检查 SCheck1 == null。 UID.equals(null) 将返回 false 而不是 null.equals(UID) 抛出 NullPointerException。

【讨论】:

  • 不,做同样的事情。
  • 在进行比较之前,您是否检查过 SCheck1 的值是多少?是你所期望的吗?
  • 是的,三重检查。我不知道我做了什么,我想我放错了一些代码,现在我在任何地方都找不到我做了什么。
  • 那是什么价值?和 UID 一样是空的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 2013-01-07
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
相关资源
最近更新 更多