通过共享首选项

时间:2016-08-18 05:09:18

标签: java android android-studio android-intent

我正在制作一个包含一个主要活动和另外11个活动的应用程序,这11个活动中的每个活动必须返回一个值,主要活动应该将这些值一起添加并在文本视图中显示总数,开始它只是给了我最后一次活动的总数,所以我尝试通过共享首选项发送值并在主活动中将它们一起添加

这是我主要活动的代码:

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();
}
}

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

所以,这是Billiards Activity的代码:

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(和其他活动的其余部分)”,我不知道如何获得正确的值或总数到主要活动

提前致谢:)

3 个答案:

答案 0 :(得分:0)

1)您的 BToatal STotal 充当,因此无需在onActivityResult中为其指定值。

2)在totcalc(View v)方法中,您将尝试获取相对于的值。 值为字符串类型,因此如果直接对String执行add操作,它将连接字符串。而是将这些字符串转换为双,然后执行添加。 由于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));
}

答案 1 :(得分:0)

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

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();
}
}

答案 2 :(得分:0)

处理 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

<强> MainActivity 在这里,您将使用用于保存值的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保存在常量类或静态最终数组中将比硬编码更好。