Arif Nur Rohman
Arif Nur Rohman

Reputation: 195

android finish() not finishing my activity

I have 2 activity (Nota and Pembayaran) activity.

in Nota activity, I show some data on textview. when layout_link_pembayaran clicked, it will Intent to Pembayaran activity.

In Pembayaran activity, I show a form, when form submitted, it will intent to Nota activity.

My problem is in Nota activity still showing the old data, not the newest data based on new data that I submit in Pembayaran activity.

here the Nota activity package com.example.arif.celmira;

    import android.app.Activity;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;

    public class Nota extends Dashboard {
String id_pembelian;
String total_bayar;
TextView txt_tanggal_pembelian,txt_status_pembelian,txt_alamat,txt_ekspedisi;
ArrayList<String>nama_produk,gambar_produk;
ArrayList<Integer>jumlah_produk,harga_produk,subharga_produk;
ListView list_produk,list_status;
TextView txt_total_belanja,txt_total_ongkir,txt_kode_unik,txt_total_tagihan,txt_status_pembayaran;
public ArrayList<String>status,tanggal,waktu,keterangan;

String status_pembayaran;
Intent pindah;
LinearLayout layout_link_pembayaran;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nota);

    getSupportActionBar().setTitle("Nota");

    txt_tanggal_pembelian = (TextView)findViewById(R.id.txt_tanggal_pembelian);
    txt_status_pembelian= (TextView)findViewById(R.id.txt_status_pembelian);
    txt_alamat= (TextView)findViewById(R.id.txt_alamat);
    txt_ekspedisi= (TextView)findViewById(R.id.txt_ekspedisi);
    list_produk = (ListView)findViewById(R.id.list_produk);
    list_status = (ListView)findViewById(R.id.list_status_pembelian);

    layout_link_pembayaran = (LinearLayout)findViewById(R.id.layout_link_pembayaran);

    nama_produk = new ArrayList<String>();
    gambar_produk = new ArrayList<String>();
    jumlah_produk = new ArrayList<Integer>();
    harga_produk = new ArrayList<Integer>();
    subharga_produk = new ArrayList<Integer>();
    status = new ArrayList<String>();
    tanggal = new ArrayList<String>();
    waktu = new ArrayList<String>();
    keterangan = new ArrayList<String>();

    txt_total_belanja = (TextView)findViewById(R.id.txt_total_belanja);
    txt_total_ongkir = (TextView)findViewById(R.id.txt_total_ongkir);
    txt_kode_unik = (TextView)findViewById(R.id.txt_kode_unik);
    txt_total_tagihan = (TextView)findViewById(R.id.txt_total_tagihan);
    txt_status_pembayaran = (TextView)findViewById(R.id.txt_status_pembayaran);

    Intent i = getIntent();
    id_pembelian = i.getStringExtra("id_pembelian");

    Log.d("id_pembelian",id_pembelian);


    layout_link_pembayaran.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (status_pembayaran.equals("sudah")){
                pindah = new Intent(Nota.this,Lihatpembayaran.class);
                pindah.putExtra("id_pembelian",id_pembelian);
            }else{
                pindah = new Intent(Nota.this,Pembayaran.class);
                pindah.putExtra("id_pembelian",id_pembelian);
                pindah.putExtra("total_bayar",total_bayar);
            }
            startActivity(pindah);
            finish();


        }
    });

    RequestQueue permintaanhati = Volley.newRequestQueue(getApplicationContext());

    StringRequest sr = new StringRequest(Request.Method.POST, Konfigurasi.url_nota, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jo = new JSONObject(response);

                JSONObject pm = jo.getJSONObject("pembelian");
                JSONObject pengiriman = jo.getJSONObject("pengiriman");
                JSONArray produk = jo.getJSONArray("produk");
                for (int i = 0; i <  produk.length(); i++){
                    JSONObject pp = produk.getJSONObject(i);
                    nama_produk.add(pp.getString("nama_produk"));
                    gambar_produk.add(pp.getString("gambar_produk"));
                    harga_produk.add(pp.getInt("harga_produk"));
                    jumlah_produk.add(pp.getInt("jumlah_produk"));
                    subharga_produk.add(pp.getInt("subharga_produk"));
                }
                Notaadapter na = new Notaadapter(getApplicationContext(),nama_produk,harga_produk,jumlah_produk,subharga_produk,gambar_produk);
                list_produk.setAdapter(na);

                String tgl = pm.getString("tanggal_pembelian");
                String sts = pm.getString("status_pembelian");
                total_bayar = pm.getString("total_bayar");


                Log.d("alamat",pengiriman.toString());

                String alamat = pengiriman.getString("alamat_penerima")+" "+pengiriman.getString("nama_kecamatan")+" "+pengiriman.getString("tipe_distrik")+" "+pengiriman.getString("nama_distrik")+" "+pengiriman.getString("kode_pos")+" "+pengiriman.getString("nama_provinsi");
                String ekspedisi = pengiriman.getString("nama_ekspedisi")+" "+pengiriman.getString("nama_paket")+" "+pengiriman.getString("lama_paket")+" hari";


                txt_tanggal_pembelian.setText(tgl);
                txt_status_pembelian.setText(sts);
                txt_alamat.setText(alamat);
                txt_ekspedisi.setText(ekspedisi);
                txt_total_belanja.setText("Rp "+String.format("%,d",Integer.parseInt(pm.getString("total_belanja"))));
                txt_total_ongkir.setText("Rp "+String.format("%,d",Integer.parseInt(pm.getString("total_ongkir"))));
                txt_kode_unik.setText(pm.getString("kode_unik"));
                txt_total_tagihan.setText("Rp "+String.format("%,d",Integer.parseInt(pm.getString("total_bayar"))));

                JSONArray js  = jo.getJSONArray("status");
                for (int i = 0; i < js.length(); i++){
                    JSONObject perstatus = js.getJSONObject(i);
                    status.add(perstatus.getString("status"));
                    tanggal.add(perstatus.getString("tanggal_status"));
                    waktu.add(perstatus.getString("waktu_status"));
                    keterangan.add(perstatus.getString("keterangan_status"));
                }
                Notastatusadapter nsa = new Notastatusadapter(getApplicationContext(),status,tanggal,waktu,keterangan);
                list_status.setAdapter(nsa);

                status_pembayaran = jo.getString("pembayaran");
                if (status_pembayaran.equals("sudah")){
                    txt_status_pembayaran.setText("Sudah kirim bukti pembayaran");
                }
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> param = new HashMap<String, String>();
            param.put("id_pembelian",id_pembelian);
            return param;
        }
    };
    permintaanhati.add(sr);
}

   }

and here my Pembayaran activity

    package com.example.arif.celmira;
    import android.Manifest;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.provider.MediaStore;
    import android.support.annotation.NonNull;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;

    import net.gotev.uploadservice.MultipartUploadRequest;
    import net.gotev.uploadservice.UploadNotificationConfig;

    import java.io.IOException;
    import java.util.UUID;

    public class Pembayaran extends AppCompatActivity implements View.OnClickListener {

//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText pemilik,bank,jumlah,tanggal,catatan;

String id_pembelian,total_bayar;



//Image request code
private int PICK_IMAGE_REQUEST = 1;

//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;

//Bitmap to get image from gallery
private Bitmap bitmap;

//Uri to store the image uri
private Uri filePath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pembayaran);

    getSupportActionBar().setTitle("Konfirmasi Pembayaran");

    Intent pindahan = getIntent();
    id_pembelian = pindahan.getStringExtra("id_pembelian");
    total_bayar = pindahan.getStringExtra("total_bayar");

    Log.d("pindahan",id_pembelian);

    //Requesting storage permission
    requestStoragePermission();

    //Initializing views
    buttonChoose = (Button) findViewById(R.id.buttonChoose);
    buttonUpload = (Button) findViewById(R.id.buttonUpload);
    imageView = (ImageView) findViewById(R.id.imageView);
    pemilik = (EditText) findViewById(R.id.edt_rekening);
    bank = (EditText) findViewById(R.id.edt_bank);
    jumlah = (EditText) findViewById(R.id.edt_jumlah);
    tanggal = (EditText) findViewById(R.id.edt_tanggal);
    catatan = (EditText) findViewById(R.id.edt_catatan);

    jumlah.setText(total_bayar);

    //Setting clicklistener
    buttonChoose.setOnClickListener(this);
    buttonUpload.setOnClickListener(this);
}
/*
 * This is the method responsible for image upload
 * We need the full image path and the name for the image in this method
 * */
public void uploadMultipart() {
    //getting name for the image
    String pm = pemilik.getText().toString();
    String bk = bank.getText().toString();
    String jml = jumlah.getText().toString();
    String tgl = tanggal.getText().toString();
    String ct = catatan.getText().toString();

    //getting the actual path of the image
    String path = getPath(filePath);

    //Uploading code
    try {
        String uploadId = UUID.randomUUID().toString();

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, Konfigurasi.url_upload_pembayaran)
                .addFileToUpload(path, "bukti") //Adding file
                .addParameter("id_pembelian", id_pembelian) //Adding text parameter to the request
                .addParameter("pemilik_rekening", pm) //Adding text parameter to the request
                .addParameter("nama_bank", bk) //Adding text parameter to the request
                .addParameter("jumlah_pembayaran", jml) //Adding text parameter to the request
                .addParameter("tanggal_pembayaran", tgl) //Adding text parameter to the request
                .addParameter("catatan_pembayaran", ct) //Adding text parameter to the request
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload
        Toast.makeText(this,"Konfirmasi pembayaran sukses",Toast.LENGTH_LONG).show();
        Intent maupindah = new Intent(Pembayaran.this,Nota.class);
        maupindah.putExtra("id_pembelian",id_pembelian);
        maupindah.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        maupindah.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        maupindah.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(maupindah);
        finish();

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
//method to show file chooser
private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Pilih Gambar"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//method to get the file path from uri
public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}
//Requesting permission
private void requestStoragePermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        return;

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }
    //And finally ask for the permission
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if (requestCode == STORAGE_PERMISSION_CODE) {

        //If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Displaying a toast
            Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
        } else {
            //Displaying another toast if permission is not granted
            Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
        }
    }
}
@Override
public void onClick(View v) {
    if (v == buttonChoose) {
        showFileChooser();
    }
    if (v == buttonUpload) {
        uploadMultipart();
    }
}

   }

I tried using finish() and pindah.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); pindah.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); pindah.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); but no one worked.

how can Nota activity start/restart after submit form in Pembayaran activity?

update I remove everything about uploading image, so in the Pembayaran activity just post Edittext, not including upload image anymore, and then it works, intent can finish() and when Intent going to Nota activity, the onCreate on Nota activity works (can load the new data using Volley StringRequest).

from this, I think the problem is intent choose image on Pembayaran activity

Upvotes: 0

Views: 396

Answers (3)

Yec8789
Yec8789

Reputation: 51

In your Nota activity, you should use startActivityForResult() instead of startActivity() and then override the method onActivityResult() in the same class. From your Pembayaran activity, send your new intent using setResult() method so it the result would come to the callback onActivityResult() in Nota activity. Try this.

Upvotes: 1

Jose Riballo
Jose Riballo

Reputation: 318

You probably need startActivityForResult() instead of startActivity(). Then, on your Pembayaran activity set the extras result and listen for onActivityResult() on Nota activity where you can set the new values.

Best regards.

Upvotes: 1

Maxouille
Maxouille

Reputation: 2911

onCreate() is not call again once you go back to Nota Activity.

May be you should try to move your StringRequest into onResume()/onStart() which are called every time the activity is displayed.

Best

Upvotes: 0

Related Questions