java – add items to Arraylist by incrementing index value, but it fails when intent works-ThrowExceptions

Exception or error:

i have the activity with the barcodescanning and i store item through Gesture detect and the index of arraylist makes problem. index can’t be incremented now, because each time the index variable i gave is re-initialized when i used the Intent. but i can’t avoid Intent. plz help me out of it………….???
the iteration is created in onFling(). and which stores the item name. and when i use back button it sends to another activity. the code is working smoothly and always stores only one item in arralist=> pro


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GestureDetectorCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.zxing.Result;

import org.w3c.dom.Text;

import java.util.Locale;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

import static android.Manifest.permission.CAMERA;

public class SecondActivity<override> extends AppCompatActivity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener,ZXingScannerView.ResultHandler {
    private GestureDetectorCompat GestureDetect;
    private TextToSpeech tts;
    private static final int REQUEST_CAMERA =1;
    private ZXingScannerView scannerView;
    TextView result;
    TextToSpeech txt;
    Vibrator vibrator;
    ArrayList<String> pro = new ArrayList<String>();
    ArrayList<String> pri = new ArrayList<String>();
    String nameget;
    String priceget;
    int vb=0;


    //String[] windowarray;

    FirebaseAuth firebaseAuth;
    FirebaseUser firebaseUser;
    DatabaseReference databasefetch;
    Product user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        txt=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status!=TextToSpeech.ERROR)
                {
                    txt.setLanguage(Locale.UK);
                }
            }
        });
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        scannerView = new ZXingScannerView(this);
        setContentView(scannerView);

        //firebase saving user login activity
        firebaseAuth = FirebaseAuth.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();



        GestureDetect = new GestureDetectorCompat(this,this);
        GestureDetect.setOnDoubleTapListener(this);

        Toast.makeText(SecondActivity.this, "Firebase connection is successful", Toast.LENGTH_LONG).show();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if(checkPermission())
            {
                Toast.makeText(this, "permission is granted", Toast.LENGTH_SHORT).show();
            }
            else
            {
                requestPermission();
            }
        }
    }
    private boolean checkPermission()
    {
        return (ContextCompat.checkSelfPermission(SecondActivity.this, CAMERA) == PackageManager.PERMISSION_GRANTED);
    }
    private void requestPermission()
    {
        ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
    }
    public void onRequestPermissionsResult(int requestCode, String permission[], int grantResults[])
    {
        switch(requestCode) {
            case REQUEST_CAMERA:
                if (grantResults.length > 0)
                {
                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if(cameraAccepted)
                    {
                        Toast.makeText(SecondActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
                        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                        {
                            if(shouldShowRequestPermissionRationale(CAMERA))
                            {
                                displayAlertMessage("you need to allow access for both permission",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                requestPermissions(new String[]{CAMERA}, REQUEST_CAMERA);
                                            }
                                        });
                                return;
                            }
                        }
                    }
                }
                break;
        }
    }
    @Override
    public void onResume()
    {
        super.onResume();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if(checkPermission())
            {
                if(scannerView == null)
                {
                    scannerView = new ZXingScannerView(this);
                    setContentView(scannerView);
                }
                scannerView.setResultHandler(this);
                scannerView.startCamera();
            }
            else
            {
                requestPermission();
            }
        }
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        scannerView.stopCamera();
    }
    public void displayAlertMessage(String message, DialogInterface.OnClickListener listener)
    {
        new AlertDialog.Builder(SecondActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", listener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();

    }


    @Override
    public void handleResult(Result result) {
        //vibration
        if(Build.VERSION.SDK_INT>=26) {
            vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
        }else{
            vibrator.vibrate(500);
        }

        final String scanResult = result.getText().toString();
        setContentView(R.layout.activity_second);

        //typeCast
        long l = Long.parseLong(scanResult);

        //database query as "select * from save where id=l;
        databasefetch = FirebaseDatabase.getInstance().getReference().child("save");
        Query query = databasefetch.orderByChild("id").equalTo(l);
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    TextView text = (TextView) findViewById(R.id.textView3);
                    String name = snapshot.child("name").getValue().toString();
                    String details = snapshot.child("details").getValue().toString();
                    String price = snapshot.child("price").getValue().toString();

                    nameget = name;
                    priceget = price;

                    //to print
                    text.setText("\nProduct Name : "+name+"\nDetails : "+details+"\nPrice : "+price);

                    //text to speech
                    String  toSpeak=text.getText().toString();
                    //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
                    txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                throw databaseError.toException(); // never ignore errors
            }
        });
        scannerView.stopCamera();

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        GestureDetect.onTouchEvent(event);
        return super.onTouchEvent(event);
    }
    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        Toast.makeText(SecondActivity.this, "onSingletapConfirmed", Toast.LENGTH_LONG).show();
        //text to speech
        TextView ed1=(TextView) findViewById(R.id.textView3);
        String  toSpeak=ed1.getText().toString();
        //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
        txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        Intent intent=new Intent(SecondActivity.this,SecondActivity.class);
        startActivity(intent);
        return false;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {

        return false;
    }


    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }


    @Override
    public void onShowPress(MotionEvent e) {


    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {

        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {


    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        vb++;
        pro.add(vb,nameget);
        Intent ddf = new Intent(SecondActivity.this, SecondActivity.class)
        startActivity(ddf);

        Toast.makeText(SecondActivity.this, "Item saved for billing", 
        Toast.LENGTH_LONG).show();
        return false;
    }

    //back button of system handled
    @Override
    public void onBackPressed() {

        Intent bill = new Intent(SecondActivity.this,Billitemlist.class);
        bill.putExtra("pro", pro);
        startActivity(bill);

        return;
    }
}
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *