How do I retrieve a result from within the "onActivityResult" in my activity

0

I'm trying to use my cell phone camera as a bar code reader.

I can recover the bar code, and see the result within the "onActivityResult", however, I need to get the result I got, for my main function, and I'm not getting it.

Follow the code below.

Main function:

public void clickProducts(){


    listProdutos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            showCamera();

ShowCamera function:

private void showCamera() {
    try {
        //start the scanning activity from the com.google.zxing.client.android.SCAN intent
        Intent intent = new Intent(ACTION_SCAN);
        intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
        startActivityForResult(intent, 0);



    } catch (ActivityNotFoundException anfe) {
        //on catch, show the download dialog
        showDialog(ProductsListToThatSchoolAndUser.this, "Nenhuma câmera habilitada.", "Download a scanner code activity?", "Sim", "Não").show();
    }
}

onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            //get the extras that are returned from the intent
            String contents = intent.getStringExtra("SCAN_RESULT");

            Toast.makeText(ProductsListToThatSchoolAndUser.this, contents, Toast.LENGTH_LONG).show();


        }
    }
}

I'd like to use the "contents" result within my "clickProducts ()" function, but I'm not getting it.

    
asked by anonymous 23.03.2018 / 17:20

1 answer

1
  

I'd like to use the "contents" result within my "clickProducts ()" function, but I'm not getting it.

You will not be able to.

When the button is clicked, the clickProducts() method is finished. On the other hand, the result is obtained asynchronously. After showCamera() the onItemClick() method is called.

You have to put the code that will handle the result in the onActivityResult() method, or better yet, create your own method and call it in onActivityResult() .

private void handleScanResult(String contents){
    //Faça aqui o que quer com 'contents'
    Toast.makeText(ProductsListToThatSchoolAndUser.this, contents, Toast.LENGTH_LONG).show(); 
}

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            //get the extras that are returned from the intent
            String contents = intent.getStringExtra("SCAN_RESULT");
            handleScanResult(contents);   
        }
    }
}
    
23.03.2018 / 17:43