2017-12-26 7 views
0

안드로이드 응용 프로그램 업데이트하지만 내가 가진 기존 키를 업데이트 할 때마다 문제는 점점되지 않는다 새로운 가치, 애플 리케이션이 충돌합니다.값은 내가 안드로이드에서 초보자 및 데이터를 저장 된 SharedPreferences를 사용하려고 (String, int)를 사용합니다</p> <p>입니다

앱은 인물의 이름과 해당 금액 (정수)을 추가해야합니다. 이름이 sharedpreferences에 이미있는 경우 해당 값은 (이전 값 + 새 값)으로 업데이트해야합니다. 업데이트 된 값을 저장하려고합니다.

충돌의 원인을 파악할 수 없습니다. 친절하게 도와주세요. 미리 감사드립니다.

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> 
+1

로그 및 예외 스택 트레이스를 첨부하십시오. – Christopher

+0

질문을 편집하고 logcat에서 충돌의 스택 추적을 추가하십시오. –

+0

sharedpref에 set int를위한 별도의 키를 만든다. 이제는 int를 넣었으나 getString()에서 가져 오면 오류가 발생한다. –

답변

0

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

는이 오류를

java.lang.ClassCastException가 점점 될 수있다 java.lang.Integer의 안드로이드에 java.lang.String의 캐스트 할 수없는 .app.SharedPreferencesImpl.getString (SharedPreferencesImpl.java:205)

,

되는이 광고로

양 양 = +있는 Integer.parseInt 때문에 (sharedpreferences.getString (이름, ""));

그래서 하나 대신

량 = 양 이하 이것을 사용 + sharedpreferences.getInt (이름, 0);

당신은 putInt를 사용하고 있으므로 검색 할 때 getInt를 사용하십시오.

+0

하지만 내 키는 String이므로 getInt()를 사용해야하는 이유는 무엇입니까? –

+0

키가 문자열이며 저장하는 값이 아닙니다. int에있는 금액을 저장하려면'editor.putInt (name, amount); '를 사용하고 있습니다. –

0

변경 다음과 같이

관련 파일입니다.

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

그 줄은'if (sharedpreferences.contains (name)) '안에 있으므로 두번째 매개 변수를 바꾸어도 상관 없습니다. –

관련 문제