Home > OS >  back button is not taking back to previous activity in android java
back button is not taking back to previous activity in android java

Time:10-29

I have 2 activities- main activity and OTP activity. In main activity,in edittext inside card view, I put the phone number. Then i press send otp button. It takes me to next activity, that is otp activity. But when I press the back button, the application exits. It does not go back to main activity.
CODE:
Main_activity.java:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{


    String[] countryNames={" 91"," 86"," 61"," 351"," 1"," 64"};
    int flags[] = {R.drawable.india, R.drawable.china, R.drawable.australia, R.drawable.portugal, R.drawable.america, R.drawable.new_zealand};
    Spinner spin;
    EditText edt;
    Button btn;
    String totalNumber;
    int phoneSuccessCode;
    String NUM = "EXTRA_PHONE_NUMBER";
    Data datum = null;
    String url = "https://swulj.000webhostapp.com/sms2.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        //Getting the instance of Spinner and applying OnItemSelectedListener on it
        spin = (Spinner) findViewById(R.id.simpleSpinner);
        edt = (EditText) findViewById(R.id.phNum);
        btn = (Button) findViewById(R.id.buttonOTP);

        spin.setOnItemSelectedListener(this);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String text = spin.getSelectedItem().toString();
        text  = edt.getText().toString();
        totalNumber = text;
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        try {
            Phonenumber.PhoneNumber swissNumberProto = phoneUtil.parse(totalNumber, "CH");
//  This will check if the phone number is real and it's length is valid.
            boolean isPossible = phoneUtil.isPossibleNumber(swissNumberProto);
            if(isPossible)
            {
                //edt.setText("OK");
                phoneSuccessCode = 1;
            }

            else {
                //edt.setText("Not OK");
                phoneSuccessCode = 0;
            }
        } catch (NumberParseException e) {
            System.err.println("NumberParseException was thrown: "   e.toString());
            //edt.setText("exception");
            phoneSuccessCode = -1;
        }
        switch(phoneSuccessCode){
            case 1:
                edt.setText("OK");
                break;
            case 0:
                edt.setText("Not OK");
                Toast.makeText(getApplicationContext(), "Enter valid number", Toast.LENGTH_LONG).show();
                break;
            case -1:
                edt.setText("exception");
                Toast.makeText(getApplicationContext(), "Enter valid number", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }

        /*datum = new Data(url, totalNumber);
        HTTPConnection1 conn = new HTTPConnection1();
        conn.execute(datum);*/

        Intent inte = new Intent(MainActivity.this,
                OTPActivity.class);
        inte.putExtra(NUM,totalNumber);
        startActivity(inte);
        //invoke the SecondActivity.
        finish();

    }
});
        CustomAdapter customAdapter=new CustomAdapter(getApplicationContext(),flags,countryNames);
        spin.setAdapter(customAdapter);
    }


    //Performing action onItemSelected and onNothing selected
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
        //Toast.makeText(getApplicationContext(), countryNames[position], Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }

    class HTTPConnection1 extends AsyncTask<Data, Void, String> {
        String phone;
        String url;
        String result;

        @Override
        protected String doInBackground(Data... params) {
            Data data = params[0];
            url = data.url;
            phone = data.phone;

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("phone", phone));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse httpResponse = httpclient.execute(httppost);
                InputStream inputStream = httpResponse.getEntity().getContent();
                //HTTPResult.setText("result3");
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                //HTTPResult.setText("result4");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                //HTTPResult.setText("result5");
                StringBuilder stringBuilder = new StringBuilder();
                //HTTPResult.setText("result6");
                String bufferedStrChunk = null;

                while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                    stringBuilder.append(bufferedStrChunk);
                }


                result = stringBuilder.toString();
                //result= "Sandeep";

            } catch (ClientProtocolException e) {
                result = "ClientProtocolException";
                // TODO Auto-generated catch block
            } catch (IOException e) {
                result = "IOException";
                // TODO Auto-generated catch block
            }
            return null;
        }

        @Override
        protected void onPostExecute(String bitmap) {
            super.onPostExecute(bitmap);
            //HTTPResult.setText(result);
            //parseAndNewIntent(result);
        }
    }
}

OTP_activity.java:

public class OTPActivity extends AppCompatActivity implements  AdapterView.OnItemSelectedListener{
    private EditText editText1, editText2, editText3, editText4, editText5, editText6;
    private EditText[] editTexts;
    CountDownTimer cTimer = null;
    TextView tv;
    TextView txt;
    TextView cnt, msg, test;
    Button resend;
    String mob;
    String NUM = "EXTRA_PHONE_NUMBER";
    int resendCount = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otpactivity2);

        Intent i = getIntent();
        mob =                                    i.getStringExtra(NUM);
        txt= (TextView) findViewById(R.id.text);
        txt.setText(txt.getText().toString()  mob);
        tv = (TextView) findViewById(R.id.timer);
        cnt = (TextView) findViewById(R.id.count);
        msg = (TextView) findViewById(R.id.msg);
        test = (TextView) findViewById(R.id.test);
        resend = (Button) findViewById(R.id.ResendOTP);
        editText1 = (EditText) findViewById(R.id.otpEdit1);
        editText2 = (EditText) findViewById(R.id.otpEdit2);
        editText3 = (EditText) findViewById(R.id.otpEdit3);
        editText4 = (EditText) findViewById(R.id.otpEdit4);
        editText5 = (EditText) findViewById(R.id.otpEdit5);
        editText6 = (EditText) findViewById(R.id.otpEdit6);
        editTexts = new EditText[]{editText1, editText2, editText3, editText4, editText5, editText6};

        editText1.addTextChangedListener(new PinTextWatcher(0));
        editText2.addTextChangedListener(new PinTextWatcher(1));
        editText3.addTextChangedListener(new PinTextWatcher(2));
        editText4.addTextChangedListener(new PinTextWatcher(3));
        editText5.addTextChangedListener(new PinTextWatcher(4));
        editText6.addTextChangedListener(new PinTextWatcher(5));

        editText1.setOnKeyListener(new PinOnKeyListener(0));
        editText2.setOnKeyListener(new PinOnKeyListener(1));
        editText3.setOnKeyListener(new PinOnKeyListener(2));
        editText4.setOnKeyListener(new PinOnKeyListener(3));
        editText5.setOnKeyListener(new PinOnKeyListener(4));
        editText6.setOnKeyListener(new PinOnKeyListener(5));

        startTimer();
        resend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resendCount  ;
                cnt.setText(String.valueOf(resendCount) " of 3");
                startTimer();
            }
        });
    }
    void startTimer() {
        resend.setEnabled(false);

        cTimer = new CountDownTimer(30000, 1000) {
            public void onTick(long millisUntilFinished) {
                tv.setText("seconds remaining: "  String.valueOf(millisUntilFinished/1000));

            }
            public void onFinish() {
                tv.setText("Re send OTP!");
                resend.setEnabled(true);
            }
        };
        cTimer.start();
    }


    //cancel timer
    void cancelTimer() {
        if(cTimer!=null)
            cTimer.cancel();
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

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

    }

    public class PinTextWatcher implements TextWatcher {

        private int currentIndex;
        private boolean isFirst = false, isLast = false;
        private String newTypedString = "";

        PinTextWatcher(int currentIndex) {
            this.currentIndex = currentIndex;

            if (currentIndex == 0)
                this.isFirst = true;
            else if (currentIndex == editTexts.length - 1)
                this.isLast = true;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            newTypedString = s.subSequence(start, start   count).toString().trim();
        }

        @Override
        public void afterTextChanged(Editable s) {

            String text = newTypedString;

            /* Detect paste event and set first char */
            if (text.length() > 1)
                text = String.valueOf(text.charAt(0)); // TODO: We can fill out other EditTexts

            editTexts[currentIndex].removeTextChangedListener(this);
            editTexts[currentIndex].setText(text);
            editTexts[currentIndex].setSelection(text.length());
            editTexts[currentIndex].addTextChangedListener(this);

            if (text.length() == 1)
                moveToNext();
            else if (text.length() == 0)
                moveToPrevious();
        }

        private void moveToNext() {
            if (!isLast)
                editTexts[currentIndex   1].requestFocus();

            if (isAllEditTextsFilled() && isLast) { // isLast is optional
                editTexts[currentIndex].clearFocus();
                hideKeyboard();
            }
        }

        private void moveToPrevious() {
            if (!isFirst)
                editTexts[currentIndex - 1].requestFocus();
        }

        private boolean isAllEditTextsFilled() {
            String str = "";
            for (EditText editText : editTexts) {
                str  = editText.getText().toString().trim();
                if (str.length() == 0)
                    return false;
            }
            test.setText(str);
            msg.setText("Incorrect OTP, Please try again!");
            return true;
        }

        private void hideKeyboard() {
            if (getCurrentFocus() != null) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            }
        }

    }

    public class PinOnKeyListener implements View.OnKeyListener {

        private int currentIndex;

        PinOnKeyListener(int currentIndex) {
            this.currentIndex = currentIndex;
        }

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (editTexts[currentIndex].getText().toString().isEmpty() && currentIndex != 0)
                    editTexts[currentIndex - 1].requestFocus();
            }
            return false;
        }

    }
}

otp_activity.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="match_parent"
    
        android:layout_height="match_parent"
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_height="match_parent">
            <TextView
                android:id="@ id/header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Enter the verification code"
                android:layout_marginLeft="10dp"
                android:textStyle="bold"
                android:textAppearance="?android:attr/textAppearanceLargePopupMenu"/>
            <TextView
                android:id="@ id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="We have sent the OTP to "
                android:layout_marginLeft="10dp"/>
            <androidx.cardview.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@ id/card_view"
                android:layout_width="180dp"
                card_view:cardElevation="4dp"
                android:gravity="center"
                android:layout_height="60dp"
                card_view:cardCornerRadius="4dp">
                <LinearLayout
    
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:layout_gravity="center">
                <EditText
                    android:id="@ id/otpEdit1"
                    android:digits="1234567890"
                    android:inputType="number"
                    android:maxLength="1"
                    android:gravity="center"
                    android:layout_weight="1"
                    android:layout_width="2dp"
                    android:layout_height="wrap_content"
                    />
                <EditText
                    android:id="@ id/otpEdit2"
                    android:digits="1234567890"
                    android:inputType="number"
                    android:maxLength="1"
                    android:gravity="center"
                    android:layout_weight="1"
                    android:layout_width="2dp"
                    android:layout_height="wrap_content"
                />
                <EditText
                    android:id="@ id/otpEdit3"
                    android:digits="1234567890"
                    android:inputType="number"
                    android:maxLength="1"
                    android:gravity="center"
                    android:layout_weight="1"
                    android:layout_width="2dp"
                    android:layout_height="wrap_content"
                />
                <EditText
                    android:id="@ id/otpEdit4"
                    android:digits="1234567890"
                    android:inputType="number"
                    android:maxLength="1"
                    android:gravity="center"
                    android:layout_weight="1"
                    android:layout_width="2dp"
                    android:layout_height="wrap_content"
                />
                    <EditText
                        android:id="@ id/otpEdit5"
                        android:digits="1234567890"
                        android:inputType="number"
                        android:maxLength="1"
                        android:gravity="center"
                        android:layout_weight="1"
                        android:layout_width="2dp"
                        android:layout_height="wrap_content"
                        />
                    <EditText
                        android:id="@ id/otpEdit6"
                        android:digits="1234567890"
                        android:inputType="number"
                        android:maxLength="1"
                        android:gravity="center"
                        android:layout_weight="1"
                        android:layout_width="2dp"
                        android:layout_height="wrap_content"
                        />
                </LinearLayout>
            </androidx.cardview.widget.CardView>
            <TextView
                android:id="@ id/msg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Waiting for OTP..."
                android:layout_marginLeft="10dp"/>
            <TextView
                android:id="@ id/timer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Timer"
                android:layout_marginLeft="10dp"/>
            <Button
                android:id="@ id/ResendOTP"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="ResendOTP" />
            <TextView
                android:id="@ id/count"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:layout_marginLeft="10dp"/>
            <TextView
                android:id="@ id/test"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:layout_marginLeft="10dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="500dp">
        </LinearLayout>
    </LinearLayout>

main_activity.xml:


 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:background="@drawable/image">
    
        <androidx.cardview.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@ id/card_view"
            android:layout_width="330dp"
            card_view:cardElevation="4dp"
            android:layout_height="60dp"
            card_view:cardCornerRadius="4dp">
    
            <LinearLayout
    
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_gravity="center">
            <Spinner
                android:id="@ id/simpleSpinner"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                />
    
    
            <EditText
                android:id="@ id/phNum"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:inputType="number"
                android:maxLength="10"
                android:hint="Enter phone number"
                  />
            </LinearLayout>
        </androidx.cardview.widget.CardView>
        <Button
            android:id="@ id/buttonOTP"
    
            android:layout_marginTop="20dp"
            android:layout_width="330dp"
            android:layout_height="wrap_content"
            android:text="Send OTP" />
        </LinearLayout>

CodePudding user response:

I have read your code and answer below, however it is not the right solution for this problem. I think you should write code like this:

Intent intent = new Intent(MainActivity.this, OTPActivity.class);
intent .putExtra(NUM,totalNumber);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(inte);

And in OTP Activity when you press back button just call:

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

CodePudding user response:

Solved using this code in OTPActivity.java:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //finish();
                onBackPressed();
                break;
        }
        return true;
    }


    @Override
    public void onBackPressed() {
        //Execute your code here
        Intent inte = new Intent(OTPActivity.this,
                MainActivity.class);
        //inte.putExtra(NUM,totalNumber);
        startActivity(inte);
        finish();

    }
  • Related