2014-12-08 2 views
-3

Я пытаюсь сохранить и сохранить данные в приложении Android с помощью java. На данный момент данные не будут сохранены, и это приведет к сбою моего приложения. Может ли кто-нибудь сделать какие-либо предложения по моему коду? Часть моей страницы включает общий бюджет, и я затрудняюсь хранить и экономить общий бюджет.Сложность сохранения и хранения

  public class Summary extends Activity implements TextWatcher, View.OnClickListener 
      { 
     DecimalFormat df = new DecimalFormat("£0.00"); 
     int noOfGifts, giftsPurchased; 
     double cost; 
     EditText budgetEntered; 
     double savedBudget = 0; 
     String budgetString; 

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

    budgetEntered = (EditText) findViewById(R.id.s2TotalBudget); 
    budgetEntered.addTextChangedListener(this); 

     Button saveBudget = (Button) findViewById(R.id.s2ViewList); 
    saveBudget.setOnClickListener(saveButtonListener); 
    if(savedBudget != 0) 
     { 
    saveBudget.setText(budgetString); 
     } 

    Bundle passedInfo = getIntent().getExtras(); 
    if (passedInfo != null) 
    { 
    cost = passedInfo.getDouble("cost"); 
    noOfGifts = passedInfo.getInt("noOfGifts"); 
    giftsPurchased = passedInfo.getInt("giftsPurchased"); 
    } 

    Button logoutButton = (Button) findViewById(R.id.s2LogoutButton); 
    logoutButton.setOnClickListener(new View.OnClickListener() 
    { 
    public void onClick(View view) 
    { 
     Intent myIntent = new Intent(Summary.this, MainActivity.class); 
     startActivity(myIntent); 
    } 
    }); 

    Button viewList = (Button) findViewById(R.id.s2ViewList); 
    viewList.setOnClickListener(new View.OnClickListener() 
    { 
    public void onClick(View view) 
    { 
     Intent myIntent = new Intent(Summary.this, GiftList.class); 
     startActivity(myIntent); 
    } 
    }); 

    String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")}, 
      {"Number of Presents bought:", (giftsPurchased + "")}, 
      {"Cost:      £", (cost + "")}, 
      {"Budget:     £", "50"}}; 



    String passedBudget=null; 

    //convert totalPresents to double from String 
    String tempPresents = summary[0][1]; 
    int presents = Integer.parseInt(tempPresents); 

    //convert presentsBought to double from String 
    String tempBought = summary[1][1]; 
    int presentsToBuy = Integer.parseInt(tempBought); 



    //Number of presents 
    TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult); 
    s2PresentResult.setText(summary[0][1]); 

    //Number of presents to buy 
    TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult); 
    s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + ""); 


    Bundle passedId = getIntent().getExtras(); 
    if (passedId != null) 
    { 
    passedBudget = passedId.getString("Enter Budget"); 
    } 


    //EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget); 
    //s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this); 
    //s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE); 


    //Number of people 
    //TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget); 
    //s2TotalBudget.setText("Enter budget"); 




    //Number of people 
    TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost); 
    s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1]))); 

    //Output if over or under budget 
    TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget); 

    //convert totalCost to double from String 
    String temp = summary[2][1]; 
    double totalCost = Double.parseDouble(temp); 

    //convert totalBudget to double from String 
     String tempTwo = "14"; 
    double totalBudget = Double.parseDouble(tempTwo); 


     if((totalCost>totalBudget)&&(totalBudget!=0)) 
     { 
     s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0)); 
     s2CalculateOverBudget.setText("You are over budget"); 
     } 
     else if(totalBudget==0){ 
     s2CalculateOverBudget.setText(""); 
     } 
     else { 
     s2CalculateOverBudget.setText("You are within budget"); 
     } 


     } 

     public View.OnClickListener saveButtonListener = new View.OnClickListener() 
     { 
     @Override 
     public void onClick(View v) 
     { 
     if(budgetEntered.getText().length()>0) 
    { 
      budgetString = budgetEntered.getText().toString(); 


    } 
     } 
    }; 



     public void onClick(View v) 
    { 

    } 

    @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) 
     { 

      } 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) 
    { 

    } 

    @Override 
    public void afterTextChanged(Editable s) 
    { 
+3

«_it вызывает мое приложение к crash_» Опубликовать Ваш выход LogCat и указать, какую строку вызывает сбой (который вы можете получить от выхода LogCat). И ** пожалуйста ** правильно отступы свой код. Это значительно облегчает отладку soooo. – csmckelvey

+1

Что говорит ловушка? – ohaleck

+0

Все ошибки и журналы, которые генерирует ваше приложение, если вы используете eclipse, вы можете просмотреть его, перейдя в Window-> Show View-> Other-> Logcat –

ответ

0

этого лучший способ для хранения и значения нагрузки в Android:

  • сохранения значений: (поместить это, где вы хотите сохранить значения, например, в методе OnStop или OnPause. Или, в вашем случае, метод OnClick)

    SharedPreferences settings = getSharedPreferences("MyPref", 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt("testValue", value); editor.commit();

  • значения нагрузки:

    SharedPreferences settings = getSharedPreferences("MyPref", 0); value = settings.getInt("testValue", defValue);

+0

, где разместить значения нагрузки? –

+0

@HawkeDamian вы можете разместить его везде, где хотите загрузить переменную. Например, в методе onCreate –

Смежные вопросы