如何将数据从Main活动传递到另一个活动

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将数据从Main活动传递到另一个活动相关的知识,希望对你有一定的参考价值。

我想将用户输入的名称和号码传递给我的android应用程序中的FakeRinger类。我在putExtra()的意图中使用了fab.setOnClickListener方法。这是我在MainActivity中使用的代码

public class MainActivity extends AppCompatActivity {

    public static final String LOG_TAG = "MainActivity";

    ImageView imageView;
    EditText number, name;
    Button setTimeButton;
    FloatingActionButton fab;
    Calendar calendar;
    long selectedTimeInMillis;
    TimePickerDialog timePicker;
    String enteredName, enteredNumber;
    Intent intent;

    private static final int SELECT_IMAGE = 100;

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

        PreferenceManager.setDefaultValues(this, R.xml.settings, false);

        imageView = findViewById(R.id.image_view);
        setTimeButton = findViewById(R.id.set_time);
        fab = findViewById(R.id.floatingActionButton);

        number = findViewById(R.id.number);
        name = findViewById(R.id.name);

        enteredName = name.getText().toString().trim();
        enteredNumber = number.getText().toString().trim();

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, SELECT_IMAGE);
            }
        });

        setTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar = Calendar.getInstance();
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                timePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        calendar.set(Calendar.MINUTE, minute);
                        calendar.set(Calendar.SECOND, 0);
                        calendar.set(Calendar.MILLISECOND, 0);
                        selectedTimeInMillis = calendar.getTimeInMillis();

                        if (hourOfDay > 12) {
                            hourOfDay = hourOfDay - 12;
                        }

                        if (minute < 10) {
                            String minuteStr = "0" + String.valueOf(minute);
                            minute = Integer.parseInt(minuteStr);
                            Log.v(LOG_TAG, "minute is :" + minute);
                        }

                        Toast.makeText(MainActivity.this, hourOfDay + ":" + minute, Toast.LENGTH_SHORT).show();

                        Log.v(LOG_TAG, "Selected time in millis:" + selectedTimeInMillis);
                    }
                }, hour, minute, false);
                timePicker.show();
            }
        });

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(MainActivity.this, AlarmReciever.class);
                intent.putExtra("FAKE_NAME", enteredName);
                intent.putExtra("FAKE_NUMBER", enteredNumber);
                PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                if (alarmManager != null) {
                    alarmManager.set(AlarmManager.RTC_WAKEUP, selectedTimeInMillis, pi);
                    Toast.makeText(MainActivity.this, "Your call has been placed", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Error: something wrong", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.settings:
                Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(intent);
                return true;

            case R.id.quick_call:
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            try {
                Uri imageUri = data.getData();
                InputStream imageStream = null;
                if (imageUri != null) {
                    imageStream = getContentResolver().openInputStream(imageUri);
                }
                Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                imageView.setImageBitmap(selectedImage);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
            }

        } else {
            Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_SHORT).show();
        }
    }
}

这是我的BroadcastReceiver课程

public class AlarmReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String getFakeName = intent.getStringExtra("FAKE_NAME");
        String getFakeNumber = intent.getStringExtra("FAKE_NUMBER");

        Intent fakeRinger = new Intent();
        fakeRinger.setClassName("com.example.mani.fakecall", "com.example.mani.fakecall.FakeRinger");
        fakeRinger.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        fakeRinger.putExtra("USER_FAKE_NAME", getFakeName);
        fakeRinger.putExtra("USER_FAKE_NUMBER", getFakeNumber);
        context.startActivity(fakeRinger);

        Log.v("Yes, we are in", "Alarm reciever");
        Log.v("fake name is: ", getFakeName);
        Log.v("fake number is: ", getFakeNumber);
    }
}

这是我的FakeRinger活动

public class FakeRinger extends AppCompatActivity {

    TextView displayName;
    TextView displayNumber;
    Button alarmOffButton;

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

        displayName = findViewById(R.id.display_name);
        displayNumber = findViewById(R.id.display_number);

        String callName = getFakeName();
        String callNumber = getFakeNumber();

        displayName.setText(callName);
        displayNumber.setText(callNumber);

        alarmOffButton = findViewById(R.id.alarm_off);
        alarmOffButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private String getFakeName(){
        String contactName = null;
        Intent i = getIntent();
        Bundle bundle = i.getExtras();
        if (bundle != null) {
            contactName = bundle.getString("USER_FAKE_NAME");
        }
        return contactName;
    }

    private String getFakeNumber(){
        String contactNumber = null;
        Intent i = getIntent();
        Bundle bundle = i.getExtras();
        if (bundle != null) {
            contactNumber = bundle.getString("USER_FAKE_NUMBER");
        }
        return contactNumber;
    }
}

我仍然无法在FakeRinger活动中显示用户输入的名称和号码。谁能告诉我我做错了什么?

答案

您需要将这两行移动到FAB单击侦听器中

enteredName = name.getText().toString().trim();
enteredNumber = number.getText().toString().trim();

你当前拥有它们的地方,布局是空的,你永远不会将这些字符串分配给其他任何东西。

如果你没有看到来自AlarmReciever的日志,那么无论如何都没有传递给下一个活动

以上是关于如何将数据从Main活动传递到另一个活动的主要内容,如果未能解决你的问题,请参考以下文章

如何将数据从一个活动传递到android中的另一个活动片段? [复制]

如何从片段获取数据到另一个活动? (不是容器活动)[重复]

如何将数据从一个片段传输到另一个片段android

完全下载文件时,将下载的文件从一个片段传递到另一个片段

将数据从一个片段发送到另一个片段时出错。 (两个片段都由一个活动托管)

我如何将数据从一个活动传递到另一个活动