Leon Brenn
Leon Brenn

Reputation: 33

How can I "save" a value from a variable after the Activity is destroyed?

I am quite new in Java programming and need your help.

I am a Trainee in a Company and I need to make a stocktaking application on Android Studio. I implemented a scanner (ZXing) and it works, but I need to save the result. I have different Buttons and for these buttons I need to save the scanner result. For Example: I click on Button A and the result need to be saved in a Variable A. When I click on Button B it's needs to be saved in the Variable B. After that, I want to send this Variables via email.

I stuck at the saving point.

I have 3(4) Activities. One of them is duplicated or splitted into put and fetched.

The fetched code:

package app.local.leipziger_messe.lbrenn.cable;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;


public class AbgeholtActivity extends AppCompatActivity {
    //setzt die für die Buttonzuordnung nötigen Strings
    ZwischenSpeicher zs = new ZwischenSpeicher();

    //Setzt die IDs für die einzelnen Checkboxen
    CheckBox b1_ab;
    CheckBox b2_ab;
    CheckBox b3_ab;
    CheckBox b4_ab;
    CheckBox b5_ab;
    CheckBox b6_ab;

    public String test = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //Superklasse wird festgelegt
        super.onCreate(savedInstanceState);
        //Es wird als Inhalt der Activity das angegebene Layout festgelegt
        setContentView(R.layout.activity_abgeholt);


        //Checkboxen werden definiert
        b1_ab = (CheckBox)findViewById(R.id.b1_ab);
        b2_ab = (CheckBox)findViewById(R.id.b2_ab);
        b3_ab = (CheckBox)findViewById(R.id.b3_ab);
        b4_ab = (CheckBox)findViewById(R.id.b4_ab);
        b5_ab = (CheckBox)findViewById(R.id.b5_ab);
        b6_ab = (CheckBox)findViewById(R.id.b6_ab);

        //TEST NUR EIN TEST



        //Buttons werden erstellt und einer ID zugewiesen
        final SimpleScannerActivity test_scanner = new SimpleScannerActivity();

        final Button button_abgeholt_pc = findViewById(R.id.abgeholt_pc);
        button_abgeholt_pc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Buttonid wird festgelegt und der Intent wird festgelegt
                zs.button_ergebnis[0] = test;
                Toast.makeText(getApplicationContext(),zs.button_ergebnis[0],Toast.LENGTH_LONG).show();
                //ntent abgeholtpcIntent = new Intent(getApplicationContext(),SimpleScannerActivity.class);
                //startActivity(abgeholtpcIntent);
            }
        });
        final Button button_abgeholt_mo = findViewById(R.id.abgeholt_mo);
        button_abgeholt_mo.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Buttonid wird festgelegt und der Intent wird festgelegt
                zs.buttonid = "2";
                Intent abgeholtpcIntent = new Intent(getApplicationContext(),SimpleScannerActivity.class);
                startActivity(abgeholtpcIntent);
                String ergebnis = test_scanner.ergebnis_test();
            }
        });
        final Button button_abgeholt_dr = findViewById(R.id.abgeholt_dr);
        button_abgeholt_dr.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Buttonid wird festgelegt und der Intent wird festgelegt
                zs.buttonid = "3";
                Intent abgeholtpcIntent = new Intent(getApplicationContext(),SimpleScannerActivity.class);
                startActivity(abgeholtpcIntent);
            }
        });
        final Button button_abgeholt_tel = findViewById(R.id.abgeholt_tel);
        button_abgeholt_tel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Buttonid wird festgelegt und der Intent wird festgelegt
                zs.buttonid = "4";
                Intent abgeholtpcIntent = new Intent(getApplicationContext(),SimpleScannerActivity.class);
                startActivity(abgeholtpcIntent);
            }
        });
    }

    public void checkbox_clicked(View v)
    {
        //Checkt ob die Checkbox angeklickt ist oder nicht (Text ist noch Platzhalter mäßig vorhanden)
        if(b1_ab.isChecked())
        {
            Toast.makeText(getApplicationContext(), "Es wurde keine ID gefunden! Wechsel zur Main Activity1", Toast.LENGTH_LONG).show();
        }
        else if (b2_ab.isChecked())
        {
            Toast.makeText(getApplicationContext(), "Es wurde keine ID gefunden! Wechsel zur Main Activity2", Toast.LENGTH_LONG).show();
        }else if (b3_ab.isChecked())
        {
            Toast.makeText(getApplicationContext(), "Es wurde keine ID gefunden! Wechsel zur Main Activity3", Toast.LENGTH_LONG).show();
        }else if (b4_ab.isChecked())
        {
            Toast.makeText(getApplicationContext(), "Es wurde keine ID gefunden! Wechsel zur Main 4", Toast.LENGTH_LONG).show();
        }else if (b5_ab.isChecked())
        {
            Toast.makeText(getApplicationContext(), "Es wurde keine ID gefunden! Wechsel zur Main Activity5", Toast.LENGTH_LONG).show();
        }else if (b6_ab.isChecked()) {
            Toast.makeText(getApplicationContext(), "Es wurde keine ID gefunden! Wechsel zur Main Activity6", Toast.LENGTH_LONG).show();
        }

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Setzt das Menu oben Rechts
        getMenuInflater().inflate(R.menu.menu_hilfe, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_help) {
            //Führt noch nichts aus -> wird dann das von der Main Activity ausführen!

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

This is the MainActivity:

package app.local.leipziger_messe.lbrenn.cable;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;

public class MainActivity extends AppCompatActivity {


    //Berechtigungscode für die Permissionsabfrage
    private int CAMERA_PERMISSION_CODE = 1;

    //Erstellung der Activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //Superklasse wird vergeben
        super.onCreate(savedInstanceState);
        //Es wird der Inhalt der Activity gesetzt
        setContentView(R.layout.activity_main);
        //Die Permissions werden abgefragt
        pCheck();

        //Buttons werden initialisiert und erstellt
        final Button button_abgeholt = findViewById(R.id.button_abgeholt);
        button_abgeholt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Beim klicken wird ein neuer Intent erstellt und man wird auf die AbgeholtActivity weitergeleitet
                Intent abgeholttIntent = new Intent(getApplicationContext(),AbgeholtActivity.class);
                startActivity(abgeholttIntent);
            }
        });

        final Button button_hingestellt = findViewById(R.id.button_hingestellt);
        button_hingestellt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Beim klicken wird ein neuer Intent erstellt und man wird auf die HingestelltActivity weitergeleitet

                Intent hingestelltIntent = new Intent(getApplicationContext(),HingestelltActivity.class);
                startActivity(hingestelltIntent);
            }
        });

        final Button button_weiter = findViewById(R.id.button_weiter);
        button_weiter.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Beim klicken wird ein neuer Intent erstellt und man wird auf die WeiterActivity weitergeleitet

                Intent testIntent = new Intent(getApplicationContext(),SimpleScannerActivity.class);
                startActivity(testIntent);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //Checkt ob die ID von dem Menu das Hilfe Menu ist
        if (id == R.id.action_help) {
            //Führt den Debug aus
            String debug_test[] = new String[8];

            //Erstellt eine neue Instanz von der SimpleScannerActivity
            ZwischenSpeicher debug_abfrage = new ZwischenSpeicher();
            //Fragt die einzelnen IDs ab, die in der SimpleScannerActivity gesetzt wurden
            debug_test[0] = debug_abfrage.button_ergebnis[0];

            //Gibt die einzelnen Ergebnisse aus
            Toast.makeText(this, debug_test[0], Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    //Checkt ob die Permissions in der Manifest Datei gesetzt wurden
    private void requestCameraPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
        }
    }


    //Gibt das Ergebnis aus und zeigt ob die Berechtigung vom Nutzer erteilt wurde oder nicht
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == CAMERA_PERMISSION_CODE)  {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Berechtigung erteilt", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Berechtigung verweigert", Toast.LENGTH_SHORT).show();
            }
        }
    }
    //Führt den ganzen Check aus
    public void pCheck() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Berechtigungen vollständig vergeben",Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "Berechtigungen müssen noch vergeben werden!",Toast.LENGTH_LONG).show();
            requestCameraPermission();
        }
    }
}

And this the Scanner (I tested something in the code):

package app.local.leipziger_messe.lbrenn.cable;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.io.*;
import app.local.leipziger_messe.lbrenn.cable.MainActivity;

import com.google.zxing.Result;

import java.io.FileWriter;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class SimpleScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
    //Die nötigen Buttonids werden definiert
    public final static String STATE_DATA = "ButtonIDs";
    static final String LOG_TAG = "Test_test";

    //Strings zur Nutzung der Buttonids werden festgelegt sowie die nötigen Scanner Elemente
    public String abgeholt_pc_id;
    public String abgeholt_mo_id;
    public String abgeholt_dr_id;
    public String abgeholt_tel_id;
    public String hingestellt_pc_id;
    public String hingestellt_mo_id;
    public String hingestellt_dr_id;
    public String hingestellt_tel_id;
    private static final String TAG = "Code Results:";
    private Result scanResult;
    public ZXingScannerView mScannerView;


    @Override
    public void onCreate(Bundle state) {
        //Superklasse wird festgelegt
        super.onCreate(state);
        //Scanner Ansicht wird initzialisiert
        mScannerView = new ZXingScannerView(this);   // Programmatically initialize the scanner view
        //Der Scanner wird als Inhalt gesetzt
        setContentView(mScannerView);                // Set the scanner view as the content view
    }

    @Override
    public void onResume() {
        //legt die Superklasse fest
        super.onResume();
        ZwischenSpeicher zs = new ZwischenSpeicher();
        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
        mScannerView.startCamera();          // Start camera on resume
        Toast.makeText(this, zs.button_ergebnis[0],Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPause() {
        //Legt die Superklasse fest
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause
    }

    @Override
    public void handleResult(Result rawResult) {
        //führt die Kamerview weiter aus
        mScannerView.resumeCameraPreview(this);
        //Setzt das das scanResult das rawResult ist
        scanResult=rawResult;
        //führt die untere Funktion aus
        //getrawresult_test();
        Log.d("handler","");
        AbgeholtActivity AA = new AbgeholtActivity();
        ZwischenSpeicher zs = new ZwischenSpeicher();
        Toast.makeText(this, zs.button_ergebnis[0],Toast.LENGTH_LONG).show();
    }

    public Result getrawresult_test() {
        Log.d("getrawresult","Result");
        AbgeholtActivity AA = new AbgeholtActivity();
        ZwischenSpeicher zs = new ZwischenSpeicher();

        //liest das Ergebnis aus dem handleResult aus
        String result = scanResult.getText();
//
//
//
//
//        //Checkt welcher Button gedrückt wurde und speichert das Ergebnis in die entsprechende Variable ein
//
//        if (zs.buttonid == "1") {
//            Log.d("buttonid1","Result");
//            abgeholt_pc_id = result;
//            zs.buttonID_array[0] = abgeholt_pc_id;
//            Toast.makeText(getApplicationContext(), zs.buttonID_array[0]+" wurde gespeichert!", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        } else if(zs.buttonid == "2") {
//            Log.d("buttonid2","Result");
//            abgeholt_mo_id = result;
//            zs.buttonID_array[1] = abgeholt_mo_id;
//            Toast.makeText(getApplicationContext(), zs.buttonID_array[1]+" wurde gespeichert!", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        } else if(zs.buttonid == "3") {
//            Log.d("buttonid3","Result");
//            abgeholt_dr_id = result;
//            zs.buttonID_array[2] = abgeholt_dr_id;
//            Toast.makeText(getApplicationContext(), zs.buttonID_array[2]+" wurde gespeichert!", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        } else if(zs.buttonid == "4") {
//            Log.d("buttonid4","Result");
//            abgeholt_tel_id = result;
//            zs.buttonID_array[3] = abgeholt_tel_id;
//            Toast.makeText(getApplicationContext(), zs.buttonID_array[3]+" wurde gespeichert!", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        } else if(zs.buttonid == "5") {
//            Log.d("buttonid5","Result");
//            hingestellt_pc_id = result;
//            zs.buttonID_array[4] = hingestellt_pc_id;
//            Toast.makeText(getApplicationContext(), zs.buttonID_array[4]+" wurde gespeichert!", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        } else if(zs.buttonid == "6") {
//            Log.d("buttonid6","Result");
//            zs.buttonID_array[5] = hingestellt_mo_id;
//            Toast.makeText(getApplicationContext(), zs.buttonID_array[5]+" wurde gespeichert!", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        } else if(zs.buttonid == "7") {
//            Log.d("buttonid7","Result");
//            hingestellt_dr_id = result;
//            zs.buttonID_array[6] = hingestellt_dr_id;
//            Toast.makeText(getApplicationContext(), zs.buttonID_array[6]+" wurde gespeichert!", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        } else if(zs.buttonid == "8") {
//            Log.d("buttonid8","Result");
//            hingestellt_tel_id = result;
//            zs.buttonID_array[7] = hingestellt_tel_id;
//            Toast.makeText(getApplicationContext(), zs.buttonID_array[7]+" wurde gespeichert!", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        } else {
//            Toast.makeText(getApplicationContext(), "Es wurde keine ID gefunden! Wechsel zur Main Activity", Toast.LENGTH_LONG).show();
//            wechselzumainActivity();
//        }
        return scanResult;
    }

    public String ergebnis_test() {
        String ergebnis = scanResult.getText();
        return ergebnis;
    }

    //Es wird eine Intent erstellt, die zur MainActivity wechselt
    public void wechselzumainActivity() {
        Intent mainactivityIntent = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(mainactivityIntent);
    }
}

Upvotes: 0

Views: 885

Answers (1)

Karthic Srinivasan
Karthic Srinivasan

Reputation: 525

Let me explain how I implemented barcode scanner in my app recently. My requirement is, my users who want to sell their book through my app will scan the barcode at the back cover of their book (if it is available). Once the scanner complete the scan, it will return the ISBN number stored in the barcode. Now I have to post that ISBN number to a webservice which will return the complete data about that book as JSON. Now I will parse the JSON and populate my views with the data returned by the webservice.

Now in your case, you want to scan the barcode which will return a number (may be asset ID) and you want to post this number to a database or something (this is my understanding. If something i missed, please comment). Now just follow these steps to get this done:

Adding dependencies:

First add the barcode dependencies in your app level build.gradle file. Like this:

implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
implementation 'com.google.zxing:core:3.2.1'

I hope you have already done this.

Declare Shared preference file:

Now declare Shared preference and a Shared preference file with any name of your choice. Like this:

SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";

This should be done in your main class before onCreate() method.

Add a button to launch barcode scanner:

Now add a button at the desired activity from where you want to launch the barcode scanner. Remember your result from barcode will be returned to this activity. Like this:

Button barcodeBtn = findViewById(R.id.barcodeBtn);
barcodeBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
        integrator.setPrompt("Scan the barcode on the asset");
        integrator.setCameraId(0);  // Use a specific camera of the device
        integrator.setOrientationLocked(true);
        integrator.setBeepEnabled(true);
        integrator.setCaptureActivity(CaptureActivityPortrait.class);
        integrator.initiateScan();
    }
}

Retrieving scanned Asset ID and storing in Shared Preference:

Once you tap the scanner button, you can see the barcode scanner opened and you can scan the barcode. Once scan is over, scanner will return the scanned asset ID to the host activity. Now you have to capture the asset ID and store it in a shared preference file. Like this:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    final IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if(result != null) {
        if(result.getContents() == null) {
            Log.d("MainActivity", "Cancelled scan");
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            Log.d("MainActivity", "Scanned");
            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            // This is where you are saving the scanned asset ID in the shared preference file.
            sharedpreferences = getActivity().getSharedPreferences("mypref", 0); // 0 - for private mode
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString("assetID", result.getContents());
            editor.apply();
        }
    } else {
        // This is important, otherwise the result will not be passed to the fragment
        super.onActivityResult(requestCode, resultCode, data);
    }

}

Using the value stored in Shared preference :

Now you have received asset ID from barcode scanner and stored it in a shared preference file with the variable name assetID. Remember this value is available across all the activities in your app. You can retrieve the value stored in assetID from anywhere like this:

 sharedpreferences = getActivity().getSharedPreferences("mypref", 0); // 0 - for private mode
 String assetID= sharedpreferences.getString(assetID, "0");

Next time you open the barcode scanner and scan another barcode, the value stored in assetID will be overridden with the new asset ID.

Hope this helps :)

Upvotes: 1

Related Questions