意向从一个活动转移到另一个活动,然后在另一个活动中进行创建

时间:2019-03-07 12:41:50

标签: android android-intent android-volley android-lifecycle

我有2个活动,Tambah和Tampil活动。

我使用Tambah活动添加新数据(表单和按钮提交),提交后,它将移至Tampil活动。在Tampil活动中,将显示数据的列表视图(我正在使用Volley)。所有脚本均有效,没有错误。但是在Tampil活动中,仅显示旧数据(如添加之前),而不显示最新数据。

这里是我的Tambah活动

package com.example.arif.upload;

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.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 Tambah extends AppCompatActivity implements View.OnClickListener{

//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;

//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.tambah);

    //Requesting storage permission
    requestStoragePermission();

    //Initializing views
    buttonChoose = (Button) findViewById(R.id.buttonChoose);
    buttonUpload = (Button) findViewById(R.id.buttonUpload);
    imageView = (ImageView) findViewById(R.id.imageView);
    editText = (EditText) findViewById(R.id.editTextName);

    //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 name = editText.getText().toString().trim();

    //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_tambah_tentor)
                .addFileToUpload(path, "foto") //Adding file
                .addParameter("nama", name) //Adding text parameter to the request
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

        Intent move = new Intent(getApplicationContext(),Tampil.class);
        startActivity(move);

    } 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, "Select Picture"), 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();
    }
}
}

这里还有Tampil活动

package com.example.arif.upload;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

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.List;

public class Tampil extends AppCompatActivity {

ListView list_tentor;
ArrayList<String>nama;

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

    list_tentor = (ListView)findViewById(R.id.list_tentor);
    nama = new ArrayList<String>();

    list_tentor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent pindah = new Intent(Tampil.this,Tambah.class);
            pindah.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(pindah);
            finish();
        }
    });

    RequestQueue req = Volley.newRequestQueue(getApplicationContext());
    StringRequest sr = new StringRequest(Request.Method.GET, Konfigurasi.url_tampil_tentor, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONObject jo = new JSONObject(response);
                JSONArray tentor = jo.getJSONArray("tentor");
                for (int i = 0; i < tentor.length(); i++){
                    JSONObject pertentor = tentor.getJSONObject(i);
                    nama.add(pertentor.getString("nama"));
                }
                Tampiladapter ta = new Tampiladapter(getApplicationContext(),nama);
                list_tentor.setAdapter(ta);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    req.add(sr);
}
}

当将Intent从Tambah活动转换为Tampil活动时,Tampil活动重新加载所有数据(包括最新数据)怎么能?

1 个答案:

答案 0 :(得分:2)

似乎您没有等到数据上传并重定向到下一个屏幕。 试试这个答案 Implementing ProgressDialog in Multipart Upload Request

  

onCompleted重定向到下一个屏幕