使用if和else if检查sharedpreference中是否存在一个值。

huangapple go评论92阅读模式
英文:

Checking with if and else if there is a value in sharedpreference

问题

我试图检查共享首选项中是否存在一个值,如果不存在,将显示带有 EditText 的警告对话框以添加该值。

目前为止,一切都很好,显示了对话框,并且插入并保存了该值。

然而,当应用程序被关闭并重新打开时,它会再次显示对话框,要求再次输入不再分配给共享首选项的值。

这是我的代码:

public void checkValue() {
    SharedPreferences sp = getSharedPreferences("USERCODE", 0);
    if (sp.getString("tag", "").equals("")) {
        openAlert();
    } else {
        Toast.makeText(getBaseContext(), "Existing value.", Toast.LENGTH_SHORT).show();
    }
}

private void openAlert() {
    mValue = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("mValue", true);

    if (mValue) {
        AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(this);

        final View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog, null);
        final EditText userInput = customLayout.findViewById(R.id.alertdialogEditTextCode);
        mAlertDialog.setView(customLayout);
        mAlertDialog.setCancelable(false);

        mAlertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = userInput.getText().toString();

                SharedPreferences sp = getSharedPreferences("USERCODE", 0);
                SharedPreferences.Editor preferencesEditor = sp.edit();
                preferencesEditor.putString("tag", value);
                preferencesEditor.apply();
                updatdCode();
                Toast.makeText(getBaseContext(), "Código salvo com sucesso!", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        mAlertDialog.show();

        getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("mValue", false).apply();
    }
}

private void updatdCode() {
    SharedPreferences sp = getSharedPreferences("USERCODE", 0);
    String data = sp.getString("tag", "");
    mTextView = findViewById(R.id.game_title);
    mTextView.setText(data);
}

这个问题已经解决了,使用一个 String,并在开头调用 updatdCode();。

package com.vanderclin.app;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.vanderclin.app.*;

public class MainActivity extends Activity {

    private boolean mValue;
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SharedPreferences sp = this.getSharedPreferences("USERCODE", 0);
        String usercode = sp.getString("CODE", "");
        updatdCode();
        if (usercode.equals("")) {
            Toast.makeText(getBaseContext(), "User not registered.", Toast.LENGTH_LONG).show();
            mValue = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("mValue", true);

            if (mValue) {
                AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(this);

                final View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog, null);
                final EditText userInput = customLayout.findViewById(R.id.alertdialogEditTextCode);
                mAlertDialog.setView(customLayout);
                mAlertDialog.setCancelable(false);

                mAlertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String value = userInput.getText().toString();

                        SharedPreferences sp = getSharedPreferences("USERCODE", 0);
                        SharedPreferences.Editor preferencesEditor = sp.edit();
                        preferencesEditor.putString("CODE", value);
                        preferencesEditor.apply();
                        updatdCode();
                        Toast.makeText(getBaseContext(), "Code saved successfully!", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
                mAlertDialog.show();

                getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("mValue", false).apply();
            }
        } else {
            Toast.makeText(getBaseContext(), "Registered user.", Toast.LENGTH_LONG).show();
        }
    }

    private void updatdCode() {
        SharedPreferences sp = getSharedPreferences("USERCODE", 0);
        String data = sp.getString("CODE", "");
        mTextView = findViewById(R.id.mainTextView);
        mTextView.setText(data);
    }
}
英文:

I'm trying to check if there is a value in the shared preference, if not, an Alert Dialog with an EditText will be displayed to add the value.

More so far so good, and displayed and the value is inserted and saved.

More when the application is closed and opened again, it displays the dialog asking again for the value that is no longer assigned to Shared Preference

This is my code:

public void checkValue() {
SharedPreferences sp = getSharedPreferences("USERCODE", 0);
if (sp.getString("tag", "") != null)
{
openAlert();
}
else
{
Toast.makeText(getBaseContext(), "Existing value.", Toast.LENGTH_SHORT).show();
}
}
private void openAlert()
{
mValue = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("mValue", true);
if (mValue)
{
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(this);
final View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog, null);
final EditText userInput = customLayout.findViewById(R.id.alertdialogEditTextCode);
mAlertDialog.setView(customLayout);
mAlertDialog.setCancelable(false);
mAlertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
String value = userInput.getText().toString();
SharedPreferences sp = getSharedPreferences("USERCODE", 0);
SharedPreferences.Editor preferencesEditor = sp.edit();
preferencesEditor.putString("tag", value);
preferencesEditor.commit();
updatdCode();
Toast.makeText(getBaseContext(), "Código salvo com sucesso!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
mAlertDialog.show();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("mValue", true).commit();
}
}
private void updatdCode()
{
SharedPreferences sp = getSharedPreferences("USERCODE", 0);
String data = sp.getString("tag", "");
mTextView = (TextView) findViewById(R.id.game_title);
mTextView.setText(data);
}
}

How can this be resolved?

The problem was solved, using a String and calling updatdCode (); at the beginning.

package com.vanderclin.app;
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.vanderclin.app.*;
public class MainActivity extends Activity 
{
private boolean mValue;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences sp = this.getSharedPreferences("USERCODE", 0);
String usercode = sp.getString("CODE", "");
updatdCode();
if (usercode == "")
{
Toast.makeText(getBaseContext(), "User not registered.", Toast.LENGTH_LONG).show();
mValue = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("mValue", true);
if (mValue)
{
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(this);
final View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog, null);
final EditText userInput = customLayout.findViewById(R.id.alertdialogEditTextCode);
mAlertDialog.setView(customLayout);
mAlertDialog.setCancelable(false);
mAlertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
String value = userInput.getText().toString();
SharedPreferences sp = getSharedPreferences("USERCODE", 0);
SharedPreferences.Editor preferencesEditor = sp.edit();
preferencesEditor.putString("CODE", value);
preferencesEditor.commit();
updatdCode();
Toast.makeText(getBaseContext(), "Code saved successfully!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
mAlertDialog.show();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("mValue", true).commit();
}
}
else
{
Toast.makeText(getBaseContext(), "Registered user.", Toast.LENGTH_LONG).show();
}
}
private void updatdCode()
{
SharedPreferences sp = getSharedPreferences("USERCODE", 0);
String data = sp.getString("CODE", "");
mTextView = findViewById(R.id.mainTextView);
mTextView.setText(data);
}
}```
</details>
# 答案1
**得分**: 1
```plaintext
sp.getString("tag", "")
这个结果永远不可能为null,因为如果在SharePreference中找不到,它会返回默认值,而默认值是您在第二个参数中声明的空字符串`""`。
所以您必须更改为
if (!sp.getString("tag", "").equals(""))
英文:

> sp.getString("tag", "")

The result of this can never be null, cause if can't find in SharePreference it will return the default value which is &quot;&quot; that you just declare as the second argument.

So you must change to

if (!sp.getString(&quot;tag&quot;, &quot;&quot;).equals(&quot;&quot;))

答案2

得分: 1

从Brian H.的回答中,我稍微修改了一下:

if (sp.getString("tag", "").equals("")) {
    openAlert();
}

默认值是 "",因此您必须与空字符串进行比较。如果相等,那么意味着在共享首选项中没有值。

抱歉,我还不能发表评论。

英文:

From the answer of Brian H., I change it a little bit

if (sp.getString(&quot;tag&quot;, &quot;&quot;).equals(&quot;&quot;))
{
openAlert();
}

The default value is &quot;&quot;, so you must compare with empty string. If it equals, then that means there is no value in shared preference.

Sorry I can't comment yet.

huangapple
  • 本文由 发表于 2020年8月18日 12:28:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63461891.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定