简体   繁体   English

不同类别/方法之间的意图

[英]Intent Between different classes/methods

I want to send 2 different values to the InformationActivity. 我想向InformationActivity发送2个不同的值。
Firstly: I want to send the barcode number, and a list (which works correctly). 首先:我要发送条形码编号和一个列表(可以正常工作)。 But for some reason the list that i send (wheat or crus or eggs depending on what i press) doesnt appear in the InformationActivity. 但是由于某种原因,我发送的列表(小麦,面包屑或鸡蛋取决于我按的内容)没有出现在InformationActivity中。
I think that the problem is because it is in 2 different classes. 我认为问题是因为它在2个不同的类中。

How I could change the code so that it sends both the barcode string and one of the lists into the next activity? 如何更改代码,以便将条形码字符串和列表之一发送到下一个活动中?

PS. PS。 I tried declaring intent as a global variable and that crashes the app PSS. 我尝试将意图声明为全局变量,这使应用PSS崩溃。 at the moment I am just testing it by printing i item in that array. 目前,我只是通过在该阵列中打印i项目来对其进行测试。

Main: 主要:

public class HomeActivity extends AppCompatActivity{

private FirebaseAuth firebaseAuth;
private Button buttonLogout;
private ZXingScannerView scannerView;
private final int permission_code = 1;

Spinner spinner;
ArrayAdapter<CharSequence> adapter;

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

    firebaseAuth = FirebaseAuth.getInstance();
    if(firebaseAuth.getCurrentUser() == null){
        finish();
        startActivity(new Intent(this, MainActivity.class));
    }
    FirebaseUser user = firebaseAuth.getCurrentUser();

    //android spinner to select profile
    spinner = (Spinner)findViewById(R.id.spinnerProfiles);
    adapter = ArrayAdapter.createFromResource(this, R.array.restrictions, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String item = parent.getItemAtPosition(position).toString();
            Toast.makeText(getBaseContext(), item + " Selected", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getApplicationContext(), InformationActivity.class);
            switch (position){
                case 0:
                    String[] wheat = getResources().getStringArray(R.array.Wheat);
                    intent.putExtra("Profile", wheat);
                    break;
                case 1:
                    String[] crus = getResources().getStringArray(R.array.Crustaceans);
                    intent.putExtra("Profile", crus);
                    break;
                case 2:
                    String[] eggs = getResources().getStringArray(R.array.Eggs);
                    intent.putExtra("Profile", eggs);
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            return;
        }
    });

}


//opens camera when button is pressed
public void scanBarcode(View view) {
    //check if user given app camera permissions
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, permission_code);

    }
    //opens camera
    scannerView = new ZXingScannerView(this);
    scannerView.setResultHandler(new ZXingScannerResultHandler());
    //stops camera and scannerview
    setContentView(scannerView);
    scannerView.startCamera();

}

//stops camera and outputs barcode result to a Toast
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler {
    @Override
    public void handleResult(Result result) {
        String resultBarcode = result.getText();
        Intent intent = new Intent(getApplicationContext(), InformationActivity.class);
        intent.putExtra("barcode", resultBarcode.toString());
        startActivity(intent);
        scannerView.stopCamera();
    }
}

InformationActivity: 信息活动:

public class InformationActivity extends AppCompatActivity {

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

    TextView barcodeView = (TextView) findViewById(R.id.tvBarcode);
    barcodeView.setText(getIntent().getExtras().getString("barcode"));

    TextView profileView = (TextView) findViewById(R.id.tvProfile);
    String[] Profile = getIntent().getStringArrayExtra("Profile");
    profileView.setText(Profile[1]);


}


@Override
public void onBackPressed() {
    Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
    startActivity(intent);
}
}

Your onItemSelected() method is adding a String[] to an Intent object, but then just throwing that Intent away. 您的onItemSelected()方法是添加一个String[]Intent对象,但随后只投掷该Intent程。

 @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { ... Intent intent = new Intent(getApplicationContext(), InformationActivity.class); switch (position){ case 0: String[] wheat = getResources().getStringArray(R.array.Wheat); intent.putExtra("Profile", wheat); break; case 1: String[] crus = getResources().getStringArray(R.array.Crustaceans); intent.putExtra("Profile", crus); break; case 2: String[] eggs = getResources().getStringArray(R.array.Eggs); intent.putExtra("Profile", eggs); break; } } 

Later on, you start the activity with a different Intent : 稍后,您以不同的 Intent开始活动:

 @Override public void handleResult(Result result) { String resultBarcode = result.getText(); Intent intent = new Intent(getApplicationContext(), InformationActivity.class); intent.putExtra("barcode", resultBarcode.toString()); startActivity(intent); scannerView.stopCamera(); } 

It's important to understand that these two intents are not shared somehow; 重要的是要了解这两个意图没有以某种方式共享。 the first one is completely separate from the second, and as soon as onItemSelected() finishes executing, the intent is thrown away. 第一个与第二个完全分开,一旦onItemSelected()完成执行,该意图便被丢弃。

What you should do is change your onItemSelected() method so that it stores information about the selection somehow (maybe update a variable in your activity), and then change your handleResult() method to read that saved information and add the array to the intent. 您应该做的是更改onItemSelected()方法,以便它以某种方式存储有关选择的信息(可能会更新您的活动中的变量),然后更改您的handleResult()方法以读取保存的信息并将数组添加到意图中。 。 Maybe something like this: 也许是这样的:

String[] selectedArray;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    ...
    switch (position){
        case 0:
            selectedArray = getResources().getStringArray(R.array.Wheat);
            break;
        case 1:
            selectedArray = getResources().getStringArray(R.array.Crustaceans);
            break;
        case 2:
            selectedArray = getResources().getStringArray(R.array.Eggs);
            break;
    }
}
@Override
public void handleResult(Result result) {
    String resultBarcode = result.getText();
    Intent intent = new Intent(getApplicationContext(), InformationActivity.class);
    intent.putExtra("barcode", resultBarcode.toString());
    intent.putExtra("Profile", selectedArray);
    startActivity(intent);
    scannerView.stopCamera();
}

我认为您应该使用startActivityForResult()更好地管理活动之间的信息交换,并构建一个更可靠的应用程序。

You need to call scanBarcode() function to fire the intent and launch InformationActivity using the perfect solution provided by Ben: 您需要调用scanBarcode()函数来激发意图并使用Ben提供的完美解决方案启动InformationActivity:

String[] selectedArray;
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    ...
    switch (position){
        case 0:
            selectedArray = getResources().getStringArray(R.array.name);
            break;
        case 1:
            selectedArray = getResources().getStringArray(R.array.name);
            break;
    }
}

Also simply call finish(); 也可以简单地调用finish();。 function in onBackPressed() of InformationActivity to navigate to Mainactivity : 在InformationActivity的onBackPressed()函数中导航到Mainactivity:

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

Happy Coding :) 快乐编码:)

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

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