【问题标题】:Adding two values from two different activities through Shared Preferences通过共享首选项添加来自两个不同活动的两个值
【发布时间】:2016-08-18 05:09:18
【问题描述】:

我正在制作一个具有一个 Main Activity 和 11 个其他 Activity 的应用程序,这 11 个 Activity 中的每个 Activity 都必须返回一个值,并且 Main Activity 应该将这些值加在一起并在 Text View 上显示总数一开始它只是给了我最后一次活动的总数,所以我尝试通过共享首选项发送值并将它们添加到主活动中

这是我主要活动的代码:

package cafe.al_sheikhabuhamzehcafe;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ItemMenu extends AppCompatActivity {

Button cDrinks;
Button hDrinks;
Button sandwiches;
Button snacks;
Button meat;
Button chickenarrayes;
Button water;
Button snooker;
Button billiards;
Button qallayat;
Button hookah;
TextView total;

public static  String BToatal = "BilliardsTotal";
public static  String STotal = "SnookerTotal";
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;





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

    cDrinks             =       (  Button  )   findViewById        (  R.id.              cDrinks  )         ;
    hDrinks             =       (  Button  )   findViewById        (  R.id.              hDrinks  )         ;
    sandwiches          =       (  Button  )   findViewById        (  R.id.           sandwiches  )         ;
    snacks              =       (  Button  )   findViewById        (  R.id.               snacks  )         ;
    meat                =       (  Button  )   findViewById        (  R.id.                 meat  )         ;
    chickenarrayes      =       (  Button  )   findViewById        (  R.id.       chickenarrayes  )         ;
    water               =       (  Button  )   findViewById        (  R.id.                water  )         ;
    snooker             =       (  Button  )   findViewById        (  R.id.              snooker  )         ;
    billiards           =       (  Button  )   findViewById        (  R.id.            billiards  )         ;
    qallayat            =       (  Button  )   findViewById        (  R.id.             qallayat  )         ;
    hookah              =       (  Button  )   findViewById        (  R.id.               hookah  )         ;
    total               =       ( TextView )   findViewById        (  R.id.                total  )         ;

    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_WORLD_READABLE);


}



public void cDrinks (View v)
{
    Intent cd= new Intent(getApplicationContext(),ColdDrinks.class);

    startActivity(cd);
}

public void hDrinks (View v)
{

    Intent hd = new Intent(getApplicationContext(),HotDrinks.class);

    startActivity(hd);

}

public void qallayat (View v)
{

    Intent q = new Intent(getApplicationContext(),Qallayat.class);

    startActivity(q);

}

public void sandwiches (View v)
{

    Intent sand = new Intent(getApplicationContext(),Sandwiches.class);

    startActivity(sand);

}

public void snacks (View v)
{

    Intent snack = new Intent(getApplicationContext(),Snacks.class);

    startActivity(snack);

}

public void meat (View v)
{

    Intent sawanee = new Intent(getApplicationContext(),SawaneeMeat.class);

    startActivity(sawanee);

}

public void chickenarr (View v)
{

    Intent chicken = new Intent(getApplicationContext(),Chicken.class);

    startActivity(chicken);

}

public void water (View v)
{

    Intent water = new Intent(getApplicationContext(),ColdWater.class);

    startActivity(water);

}

public void hookah (View v)
{

    Intent hookah = new Intent(getApplicationContext(),Hookahs.class);

    startActivity(hookah);

}

public void billiards (View v)
{

    Intent billiards = new Intent(this,Billiards.class);

    startActivityForResult(billiards,9710);

}



public void snooker (View v)
{

    Intent snooker = new Intent(this,Snooker.class);

    startActivityForResult(snooker,9711);



}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==9710) {
        if (resultCode == RESULT_OK) {
            String billiardstot = data.getStringExtra("btot");

            BToatal = String.valueOf(billiardstot);

            String bt = String.valueOf(billiardstot);

            SharedPreferences.Editor editor = sharedpreferences.edit();

            editor.putString(billiardstot, bt);

            editor.commit();


        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Wrong Request Code", Toast.LENGTH_LONG).show();
        }
    }

    if (requestCode==9711) {
        if (resultCode == RESULT_OK) {

            String snookertot = data.getStringExtra("stot");

            STotal = String.valueOf(snookertot);

            String st = String.valueOf(snookertot);

            SharedPreferences.Editor editor = sharedpreferences.edit();

            editor.putString(snookertot, st);

            editor.commit();


        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Wrong Result Code", Toast.LENGTH_LONG).show();
        }

    }

}


public void totcalc (View v)
{


    sharedpreferences.getString(BToatal,null);
    sharedpreferences.getString(STotal,null);


    Intent gettot = getIntent();

    Double imfromcd = gettot.getDoubleExtra("cdtot",0 )  ;
    Double imfromhd = gettot.getDoubleExtra("hdtot",0 )  ;
    Double imfromq  = gettot.getDoubleExtra("qtot", 0 )  ;
    Double imfromsand = gettot.getDoubleExtra("sandtot",0);
    Double imfromsnack = gettot.getDoubleExtra("snacktot",0);
    Double imfromsawanee = gettot.getDoubleExtra("sawaneetot",0);
    Double imfromchicken = gettot.getDoubleExtra("chtot",0);
    Double imfromcw = gettot.getDoubleExtra("cwtot",0);
    Double imfromh = gettot.getDoubleExtra("htot",0);



    String gtotal = String.valueOf(STotal) + String.valueOf(BToatal) + imfromcd + imfromhd + imfromq + imfromsand + imfromsnack + imfromsawanee + imfromchicken + imfromcw + imfromh;

    total.setText(String.valueOf(gtotal));

}



@Override
public void onBackPressed() {
    finish();
    super.onBackPressed();
}
}

到目前为止,我只做过台球和斯诺克活动..

所以,这是台球活动的代码:

package cafe.al_sheikhabuhamzehcafe;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.Preference;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.prefs.Preferences;

public class Billiards extends AppCompatActivity {

EditText ebgames;
Button   bsave;

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

    ebgames = (EditText)findViewById(R.id.ebgames);
    bsave   = ( Button )findViewById(R.id.  bsave);


}

public void bsave (View v)
{

    Double dbgames = Double.parseDouble(ebgames.getText().toString());
    Double calcbgames = (dbgames)*0.50;

    Double btotal = (calcbgames);


    Intent billiards=new Intent();
    billiards.putExtra("btot",String.valueOf(btotal));
    setResult(9710,billiards);
    finish();


}


@Override
public void onBackPressed() {

    Double dbgames = Double.parseDouble(ebgames.getText().toString());
    Double calcbgames = (dbgames)*0.50;

    Double btotal = (calcbgames);


    Intent billiards=new Intent();
    billiards.putExtra("btot",String.valueOf(btotal));
    setResult(9710,billiards);
    finish();


    super.onBackPressed();
}
}

这是斯诺克活动的代码:

package cafe.al_sheikhabuhamzehcafe;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Snooker extends AppCompatActivity {

EditText esgames;
Button   ssave;


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

    esgames = (EditText)findViewById(R.id.esgames);
    ssave   = ( Button )findViewById(R.id.  ssave);



}

public void ssave (View v)
{

    Double dsgames = Double.parseDouble(esgames.getText().toString());
    Double calcsgames = (dsgames)*1.00;

    Double stotal = (calcsgames);


    Intent snooker=new Intent();
    snooker.putExtra("stot",String.valueOf(stotal));
    setResult(9711,snooker);
    finish();


}

@Override
public void onBackPressed() {

    Double dsgames = Double.parseDouble(esgames.getText().toString());
    Double calcsgames = (dsgames)*1.00;

    Double stotal = (calcsgames);


    Intent snooker=new Intent();
    snooker.putExtra("stot",String.valueOf(stotal));
    setResult(9711,snooker);
    finish();


    super.onBackPressed();

}
}

问题是当我按下应该计算每个活动的总数的按钮时,它显示“BilliardsTotalSnookerTotal(以及其他活动的其余总数)”,我不知道如何获得正确的值或总数到主要活动

提前致谢:)

【问题讨论】:

  • 创建一个公共类文件使用两种方法获取和设置sharepreference数据。将您的值发送到 setsharepreference 方法,获取以前的 sharedprefece 值,首先将其添加到新值并更新 sharedPreference

标签: java android android-studio android-intent


【解决方案1】:

1) 您的 BTotalSTotal 充当 ,因此无需在 onActivityResult 中为其分配值。

2) 在 totcalc (View v) 方法中,您将尝试根据这些 keys 获取值。 值是String类型,所以如果直接对String进行add操作,就会拼接String。而是将这些字符串转换为双精度,然后执行加法。 由于TextView的setText(CharSequence text)方法采用String,最后将totalValue转为字符串。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==9710) {
        if (resultCode == RESULT_OK) {
            String billiardstot = data.getStringExtra("btot");
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString(BToatal, billiardstot);
            editor.commit();

        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Wrong Request Code", Toast.LENGTH_LONG).show();
        }
    }
    if (requestCode==9711) {
        if (resultCode == RESULT_OK) {
            String snookertot = data.getStringExtra("stot");
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString(STotal, snookertot);
            editor.commit();

        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Wrong Result Code", Toast.LENGTH_LONG).show();
        }

    }

}


public void totcalc (View v)
{
    String billiardstotTotal = sharedpreferences.getString(BToatal,null);
    String snookerTotal = sharedpreferences.getString(STotal,null);

    Intent gettot = getIntent();

    Double imfromcd = gettot.getDoubleExtra("cdtot",0 )  ;
    Double imfromhd = gettot.getDoubleExtra("hdtot",0 )  ;
    Double imfromq  = gettot.getDoubleExtra("qtot", 0 )  ;
    Double imfromsand = gettot.getDoubleExtra("sandtot",0);
    Double imfromsnack = gettot.getDoubleExtra("snacktot",0);
    Double imfromsawanee = gettot.getDoubleExtra("sawaneetot",0);
    Double imfromchicken = gettot.getDoubleExtra("chtot",0);
    Double imfromcw = gettot.getDoubleExtra("cwtot",0);
    Double imfromh = gettot.getDoubleExtra("htot",0);

    Double totalValue = imfromcd + imfromhd + imfromq + imfromsand + imfromsnack + imfromsawanee + imfromchicken + imfromcw + imfromh
    totalValue += Double.valueOf(billiardstotTotal) + Double.valueOf(snookerTotal);
    total.setText(String.valueOf(totalValue));
}

【讨论】:

  • 它有点工作,现在它将(台球,斯诺克)以外的活动总数添加到它们的总数中,但是这两个活动的总数永远不会改变为“7.5”以外的任何东西当我从任何不同的屏幕添加其他内容时会发生变化,我应该在其余的活动中这样做吗? ,请帮帮我,我今天必须完成它
  • 首先通过在 OnActivityResult 方法中输入日志来检查这些变量(台球、台球)的值。你得到正确的值了吗?
【解决方案2】:

在你的主要活动中做这样的事情

public void billiards (View v)
{
    Intent billiards = new Intent(this,Billiards.class);
    startActivity(billiards);
}

public void snooker (View v)
{
    Intent snooker = new Intent(this,Snooker.class);
    startActivity(snooker);
}

public void totcalc (View v)
{
    double billiardsTotal = sharedpreferences.getFloat(BToatal,0);
    double snookerTotal = sharedpreferences.getFloat(STotal,0);

    double totalFromActivities = billiardsTotal + snookerTotal;

    total.setText(String.valueOf(totalFromActivities));

}

然后在你的其他活动中这样做

public class Billiards extends AppCompatActivity {

EditText ebgames;
Button   bsave;
public static  String BToatal = "BilliardsTotal";
Double dbgames = 0;
Double calcbgames = 0;
SharedPreferences sharedPreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_billiards);
    ebgames = (EditText)findViewById(R.id.ebgames);
    bsave   = ( Button )findViewById(R.id.  bsave);
    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_WORLD_READABLE);
}

public void bsave (View v)
{
    dbgames = Double.parseDouble(ebgames.getText().toString());
    calcbgames = (dbgames)*0.50;

    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putFloat(BToatal,calcbgames);
    editor.apply();

    finish();
}


@Override
public void onBackPressed() {

    dbgames = Double.parseDouble(ebgames.getText().toString());
    calcbgames = (dbgames)*0.50;
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putFloat(BToatal,calcbgames);
    editor.apply();

    finish();

    super.onBackPressed();
}
}

【讨论】:

    【解决方案3】:

    处理 SharedPreferences 非常简单!

    活动一、二、三:

    您可以在此处创建数据并保存在共享首选项中。 保存时,您可以使用该屏幕的预定义 ID/名称 来识别值的来源。 在每个活动中重复代码并在存储值时使用适当的 ID。

    SharedPreferences sp = getSharedPreferences("YourSharedPreference", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    int VALUE_TO_PASS = <your value here>;
    editor.putInt("ACTIVITY_ONE", VALUE_TO_PASS); //ACTIVITY_TWO,ACTIVITY_THREE...
    editor.commit();
    // Now screen shift
    

    主活动 在这里,您将使用用于保存值的 SAME id 逐一检索值

    SharedPreferences sp = getSharedPreferences("YourSharedPreference", Activity.MODE_PRIVATE);
    int DEFAULT_FALLBACK_VALUE = 0;  //When value is not received, show this
    int VALUE_PASSED_ACTIVITY_1 = sp.getInt("ACTIVITY_ONE", DEFAULT_FALLBACK_VALUE);
    int VALUE_PASSED_ACTIVITY_2 = sp.getInt("ACTIVITY_TWO", DEFAULT_FALLBACK_VALUE);
    int VALUE_PASSED_ACTIVITY_3 = sp.getInt("ACTIVITY_THREE", DEFAULT_FALLBACK_VALUE);
    
    int Total = VALUE_PASSED_ACTIVITY_1 + VALUE_PASSED_ACTIVITY_2 + ...;
    

    将这些 ID 保存在 常量类或静态最终数组中会比硬编码更好。

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 2012-09-08
      • 2018-03-17
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多