-3

I've created some activities for my project, but I have some problems when go from one activity to another

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transaksibaru);
        getSupportActionBar().show();
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        radioGroup = (RadioGroup) findViewById(R.id.editJenis);
        KeteranganTrx = (EditText)findViewById(R.id.editKeterangan);
        JumlahTrx = (EditText)findViewById(R.id.editJumlah);
        JumlahTrx.addTextChangedListener(onTextChangedListener());

        SubmitTransaksi = (TextView) findViewById(R.id.buttonSubmit);

        SubmitTransaksi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Checking whether EditText is Empty or Not
                CheckEditTextIsEmptyOrNot();
                if(CheckEditText){
                    // If EditText is not empty and CheckEditText = True then this block will execute.
                    ProsesTransaksi(JenisTrxHolder,KeteranganTrxHolder, JumlahTrxHolder);
                }
                else {
                    // If EditText is empty then this block will execute .
                    Toast.makeText(TransaksiBaru.this,"Pastikan Semua Kolom Terisi", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private TextWatcher onTextChangedListener() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                JumlahTrx.removeTextChangedListener(this);

                try {
                    String originalString = s.toString();
                    Long longval;
                    if (originalString.contains(",")) {
                        originalString = originalString.replaceAll(",", "");
                    }
                    longval = Long.parseLong(originalString);
                    DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
                    formatter.applyPattern("#,###,###,###");
                    String formattedString = formatter.format(longval);
                    //setting text after format to EditText
                    JumlahTrx.setText(formattedString);
                    JumlahTrx.setSelection(JumlahTrx.getText().length());
                } catch (NumberFormatException nfe) {
                    nfe.printStackTrace();
                }
                JumlahTrx.addTextChangedListener(this);
            }
        };
    }

    public void ProsesTransaksi(final String S_Jenis, final String S_Keterangan, final String S_Jumlah){
        class ProsesTransaksiClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog = ProgressDialog.show(TransaksiBaru.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {
                super.onPostExecute(httpResponseMsg);
                progressDialog.dismiss();
                if(httpResponseMsg.equalsIgnoreCase("Transaksi berhasil di simpan")){
                    Toast.makeText(TransaksiBaru.this,httpResponseMsg.toString(), Toast.LENGTH_SHORT).show();
                    finish();
                    Intent IntentDashboard = new Intent(getApplicationContext(),UserDashboard.class);
                    startActivity(IntentDashboard);
                }
                else{
                    Toast.makeText(TransaksiBaru.this,httpResponseMsg.toString(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected String doInBackground(String... params) {
                hashMap.put("JenisTrx",params[0]);
                hashMap.put("KeteranganTrx",params[1]);
                String a = params[2];
                a=a.replaceAll(",","");
                hashMap.put("JumlahTrx",a);
                finalResult = httpParse.postRequest(hashMap, HttpURL);
                return finalResult;
            }
        }

        ProsesTransaksiClass prosesTransaksiClass = new ProsesTransaksiClass();
        prosesTransaksiClass.execute(S_Jenis,S_Keterangan,S_Jumlah);
    }

    public void CheckEditTextIsEmptyOrNot(){
        int selectedId = radioGroup.getCheckedRadioButtonId();
        JenisTrx = (RadioButton) findViewById(selectedId);
        JenisTrxHolder = JenisTrx.getText().toString();
        KeteranganTrxHolder = KeteranganTrx.getText().toString();
        JumlahTrxHolder = JumlahTrx.getText().toString();

        if(TextUtils.isEmpty(JenisTrxHolder) || TextUtils.isEmpty(KeteranganTrxHolder) || TextUtils.isEmpty(JumlahTrxHolder))
        {
            CheckEditText = false;
        }
        else {
            CheckEditText = true ;
        }

    }

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

When I press the back key on my device, it directly closes the app. What I want is when I press the key back in my device it will back to the previous activity. How to detect if there is previous activity then true back to previous activity.

Any help with this?

Poeja Network
  • 184
  • 2
  • 17

7 Answers7

3

In the previous activities, you might have called finish() before/after startActivity(intent), I suggest you to remove finish() method call there.

For eg:

To go from Activity A -> Activity B

You call

Intent intent = new Intent(A.this, B.class);
startActivity(intent);
finish();

Now in Activity B, you press BackButton, It will close the App, because there is no activity present in background stack to regain focus/ resume

To fix this, just remove finish() method in Activity A where you make intent call like:

Intent intent = new Intent(A.this, B.class);
startActivity(intent);
// finish();    // Note: finish() is commented

Now, when in Activity B you press BackButton, it will resume Activity A

Note: make sure you are calling finish() in onBackPressed() in Activity B; which indicates that you no longer need this Activity(Activity B) and can resume last activity which was paused/stopped and is in background stack

Firoz Memon
  • 4,282
  • 3
  • 22
  • 32
2

You can try this

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

instead of this

@Override
public void onBackPressed()
{
    this.finish();
}
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
1

If you use a Intent it might works e.g:

public void onBackPressed() {
        Intent gotoBack = new Intent(YourActualActivity.this, YourDestiny.class);
        //gotoBack.putExtra(USER_GLOBAL_SENDER, username_global); <-- Use this if you want to carry some data to the other activity.
        startActivity(gotoBack);
}

Hope it helps.

marcode_ely
  • 434
  • 1
  • 5
  • 18
1
@Override
 protected void onPostExecute(String httpResponseMsg) {
 super.onPostExecute(httpResponseMsg);

 progressDialog.dismiss();
 if(httpResponseMsg.equalsIgnoreCase("Transaksi berhasil di simpan")){

   Toast.makeText(TransaksiBaru.this,httpResponseMsg.toString(), 
   Toast.LENGTH_SHORT).show();
   finish();// Remove this line from your asynctask.
   Intent IntentDashboard = new Intent(getApplicationContext(),UserDashboard.class);
               startActivity(IntentDashboard);
            } else {
             Toast.makeText(TransaksiBaru.this,httpResponseMsg.toString(), 
Toast.LENGTH_SHORT).show();
            }
        }
Jackey kabra
  • 199
  • 1
  • 9
  • nice, but I got an error when trying to click back button in action bar in activity, can you help? – Poeja Network Nov 28 '17 at 05:19
  • You should get on click listener of back button of action bar in your activity. – Jackey kabra Nov 28 '17 at 05:23
  • 1
    @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // todo: goto back activity from here Intent intent = new Intent(CurrentActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); return true; default: return super.onOptionsItemSelected(item); } } – Jackey kabra Nov 28 '17 at 05:25
  • nice, fix it, just case android.R.id.home: finish(); thanks – Poeja Network Nov 28 '17 at 05:37
0

You can use finish() or finishAffinity() to end that activity

@Override
public void onBackPressed() {
   finishAffinity();
}
Android Geek
  • 8,956
  • 2
  • 21
  • 35
0

Remove

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

It should work fine.

josh_gom3z
  • 294
  • 1
  • 13
0

I think your'e before activity is u called intent time is finish as called so this activity finish then not go to previous.

@Override
public void onBackPressed()
{ 
    startActivity(new Intent(TransaksiBaru.this,backActivity.class));
    this.finish();
}
Firoz Memon
  • 4,282
  • 3
  • 22
  • 32