简体   繁体   English

如何在Android中的Activity之间传递数据

[英]How to pass data between Activities in Android

How do I pass data between Activities in Android?如何在 Android 中的活动之间传递数据?

Example: I made a group CardView is in the second activitys, and I collected this card (It shows the user how much card there is in this activity)示例:我在第二个活动中创建了一个 CardView 组,我收集了这张卡片(它向用户显示了该活动中有多少卡片)

I would like to pass the card number to the first activity我想把卡号传给第一个活动

Second activity第二个活动

public class Skin extends AppCompatActivity   {
    private Toolbar toolbar;
    public TextView tx;
    private  static  int mysize;
    public List<SettersAndGetters> lstPress;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainm);
        TextView tt = (TextView) findViewById(R.id.titel_card);
        Button add = (Button) findViewById(R.id.add);

        toolbar = (Toolbar) findViewById(R.id.toolbar20);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                v.setFocusableInTouchMode(true);
                v.requestFocus();
                onBackPressed();
            }
        });


        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Skin.this, ADD.class);
                startActivity(intent);
            }
        });

//The contents of the card that you collected
        tt.setText(R.string.cn1);

        lstPress = new ArrayList<>();
        lstPress.add(new SettersAndGetters(R.string.cr5, R.string.c2, R.string.com1, R.string.des5, R.drawable.p5, 120, 55, 10000005));
        lstPress.add(new SettersAndGetters(R.string.cr1, R.string.c2, R.string.com1, R.string.des1, R.drawable.p2, 12, 12, 1800000));
        lstPress.add(new SettersAndGetters(R.string.cr1, R.string.c2, R.string.com1, R.string.des1, R.drawable.p2, 12, 12, 1800000));
        lstPress.add(new SettersAndGetters(R.string.cr1, R.string.c2, R.string.com1, R.string.des1, R.drawable.p2, 12, 12, 1800000));
        lstPress.add(new SettersAndGetters(R.string.cr1, R.string.c2, R.string.com1, R.string.des1, R.drawable.p2, 12, 12, 1800000));
        lstPress.add(new SettersAndGetters(R.string.cr1, R.string.c2, R.string.com1, R.string.des1, R.drawable.p2, 12, 12, 1800000));

        tx = (TextView) findViewById(R.id.c);
        int size = lstPress.size();     //here This line works great for me, but I want it in the first class (pass it to a class before it)
        tx.setText("" + size);
        mysize=size;



        Toast.makeText(getApplicationContext(),"Size="+size,Toast.LENGTH_LONG).show();




        RecyclerView myr = (RecyclerView) findViewById(R.id.recycler_view);
        RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this, lstPress);
        myr.setLayoutManager(new GridLayoutManager(this, 2));
        myr.setAdapter(myAdapter);



    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        return true;

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_add, menu);
        // Inflate switch
        ImageButton re = (ImageButton) menu.findItem(R.id.item_switch2)
                .getActionView().findViewById(R.id.back2);






        re.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                Toast.makeText(Skin.this, "hhi", Toast.LENGTH_SHORT).show();
            }
        });



        ImageButton btnubload = (ImageButton) menu.findItem(R.id.item_switch2)
                .getActionView().findViewById(R.id.btnaddUPLOAD);






        btnubload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Skin.this, ADD.class);
                startActivity(intent);



            }
        });





        return true;




    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase));
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }




public static int getMysize(){


        return mysize;

}


}

MainActivity is first activity MainActivity 是第一个活动

    public class MainActivity extends AppCompatActivity implements BootShett.BottomSheetListener {


protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainm);
        TextView tt = (TextView) findViewById(R.id.Number_of_badges)


 int c=Skin.getMysize();
        tt.setText(""+c);


}

To pass data between activities use Intents .要在活动之间传递数据,请使用Intents

For example set some data before opening the an Activity:例如在打开一个 Activity 之前设置一些数据:

Intent intent = new Intent(Skin.this, ADD.class);
intent.putExtra("key_a", "hello world");
intent.putExtra("key_b", 123);
intent.putExtra("key_c", true);
startActivity(intent);

And to retrieve it in the other activity:并在其他活动中检索它:

protected void onCreate(Bundle savedInstanceState) {
    ....
    final String valueA = this.getIntent().getStringExtra("key_a");
    final int valueB = this.getIntent().getIntExtra("key_b", 0);
    final boolean valueC = this.getIntent().getBooleanExtra("key_c", false);
    ....
}

If instead , you need to return a value from the second activity, so in reverse mode, then start the second activity with startActivityForResult (and not startActivity), and then override in the first activity the onActivityResult method to handle the result.如果相反,您需要从第二个活动返回一个值,因此在反向模式下,然后使用startActivityForResult (而不是 startActivity)启动第二个活动,然后在第一个活动中覆盖onActivityResult方法来处理结果。 See this link for more documentation about returning values from activities.有关从活动返回值的更多文档,请参阅此链接

Example:例子:

  1. In the first activity you must start the second activity with startActivityForResult :在第一个活动中,您必须使用startActivityForResult启动第二个活动:

     Intent intent = new Intent(this, SecondActivity.class); this.startActivityForResult(intent, YUR_REQUEST_CODE);
  2. In the second activity before closing it by calling finish , set the return value using setResult :在通过调用完成关闭它之前的第二个活动中,使用setResult设置返回值:

     public void onClick(View view) { final Intent intent = new Intent(); intent.putExtra("key_a", 1234567890); setResult(YUR_REQUEST_CODE, intent); finish(); }
  3. When back into the first activity you will automatically get the result in the method onActivityResult当回到第一个活动时,您将自动在方法onActivityResult 中获得结果

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == YOUR_REQUEST_CODE) { final int value = data.getIntExtra("key_a", 0); .... }

    } }

You can also use Shared Preferences:您还可以使用共享首选项:

Add this code in first activity在第一个活动中添加此代码

SharedPreferences sp;
sp = getSharedPreferences("card",MODE_PRIVATE);
int cardNumber = Skin.getMysize();
sp.edit().putInt("card_number", cardNumber).apply();

Add this code in second activity在第二个活动中添加此代码

SharedPreferences sp;
sp = getSharedPreferences("card",MODE_PRIVATE);
int cardNumber = sp.getInt("card_number", "");

In that case just do this in the second activity just put:在这种情况下,只需在第二个活动中执行此操作即可:

Intent intent = new Intent();
intent.putExtra(key, value);
setResult(result key, intent); 
finish();

And in your 1st activity get the result through onActivityResult在你的第一个活动中通过 onActivityResult 获得结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM