在Android应用程序中,共享首选项中的值未获得更新

时间:2017-12-26 08:31:05

标签: android android-sharedpreferences

我是android的新手并尝试使用sharedpreferences来存储数据(String,int)

但问题是每当我尝试使用新值更新现有密钥时,应用程序崩溃。

应用程序应该添加人员名称和相应的金额(整数)。如果共享首选项中已存在该名称,则应使用(旧值+新值)更新相应的值。我正在尝试存储更新后的值。

我无法弄清楚崩溃的原因。请帮助。提前谢谢。

相关文件如下:

MainActivity.java

 public class MainActivity extends AppCompatActivity {    
    SharedPreferences sharedpreferences;
    EditText etAmount;
    String name;
    int amount;                            
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);   
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        sharedpreferences = getSharedPreferences("sharedprefs", Context.MODE_PRIVATE);           
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add new person");
        View viewInflated = LayoutInflater.from(MainActivity.this).inflate(R.layout.add_new_member_alert, (ViewGroup) findViewById(android.R.id.content), false);
        // Set up the input
        final EditText etName = (EditText) viewInflated.findViewById(R.id.etName);
        etAmount = (EditText) viewInflated.findViewById(R.id.etAmount);       
        builder.setView(viewInflated);    
        // Set up the buttons
        builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                name = etName.getText().toString();
                amount = Integer.parseInt(etAmount.getText().toString());
                SharedPreferences.Editor editor = sharedpreferences.edit();    

                if (sharedpreferences.contains(name)) {
                    amount = amount + Integer.parseInt(sharedpreferences.getString(name, ""));
                    editor.putInt(name, amount);
                    editor.apply();
                }
                else{
                    editor.putInt(name, amount);
                    editor.commit();
                }

                Toast.makeText(MainActivity.this, name + " added!!" + "  Amount is " + amount, Toast.LENGTH_SHORT).show();    
                dialog.dismiss();                       //work is done so dismiss
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();                        //cancel the operation
            }
        });    
        builder.show();            
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
    }    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
}

add_new_member_alert.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="Name"/>           

    <EditText
        android:id="@+id/etName"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="20dp" />

    </LinearLayout>    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:text="Amount" />

        <EditText
            android:id="@+id/etAmount"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"/>                

    </LinearLayout>
</LinearLayout>

2 个答案:

答案 0 :(得分:0)

在代码中更改以下行。

amount = amount + Integer.parseInt(sharedpreferences.getString(name, ""));

amount = amount + Integer.parseInt(sharedpreferences.getString(name, "0"));

答案 1 :(得分:0)

您可能收到此错误

  

java.lang.ClassCastException:java.lang.Integer无法强制转换为java.lang.String                                                                                          在android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:205)

由于这一行

  

amount = amount + Integer.parseInt(sharedpreferences.getString(name,“”));

所以请在下面使用一个

  

amount = amount + sharedpreferences.getInt(name,0);

您正在使用putInt,因此请在检索时使用getInt。