I want to select 4 images from phone gallery and display them in 4 imageviews, so far below code is working fine by selecting 4 buttons individually.
Now i want to implement to select 4 images with 1 button and get them displayed in 4 imageview simulatenously, i am stuck here and have done many google search and found a solution by using getClipData below but after many trial and error still not working, can someone enlighthen me and appreicate your help.
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(int i = 0; i < count; i++) {
// Uri filepath = data.getClipData().getItemAt(i).getUri();
}
//do something with the image (save it to some directory or whatever you need to do with it here)
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//do something with the image (save it to some directory or whatever you need to do with it here)
MainActivity.java code:
public class MainActivity extends AppCompatActivity
{
EditText t1,t2;
// TextView tv_upload1;
Button browse,browse_two,browse_three,browse_four,upload;
ImageView img, img_two,img_three,img_four;
Bitmap bitmap,bitmap_two,bitmap_three,bitmap_four;
String encodeImageString,encodeImageString_two,encodeImageString_three,encodeImageString_four;
private static final String url="http://example.com/fileupload.php";
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button openActivityBtn = findViewById(R.id.openActivityBtn);
img = (ImageView) findViewById(R.id.img);
img_two = (ImageView) findViewById(R.id.img_two);
img_three = (ImageView) findViewById(R.id.img_three);
img_four = (ImageView) findViewById(R.id.img_four);
upload = (Button) findViewById(R.id.upload);
browse = (Button) findViewById(R.id.browse);
browse_two = (Button) findViewById(R.id.browse_two);
browse_three = (Button) findViewById(R.id.browse_three);
browse_four = (Button) findViewById(R.id.browse_four);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Browse Image"), 1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
//-----brose2
browse_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Browse Image"), 2);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
//-----browse3
browse_three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Browse Image"), 3);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
//-----browse4
browse_four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Browse Image"), 4);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText firstName = (EditText) findViewById(R.id.t1);
// if (firstName.getText().toString().length() != 0);
// firstName.setError("Dealer name is required!");
EditText fivecode = (EditText) findViewById(R.id.t2);
// if (fivecode.getText().toString().length() != 12)
// fivecode.setError("12 digit 5+5 dealer code is required!");
//--------progressbar start
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// mProgressDialog.setMessage(getString(R.string.progress_detail));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgress(0);
mProgressDialog.setTitle("UPLOAD STATUS");
mProgressDialog.setMessage("Your photos are being uploaded...");
mProgressDialog.setProgressNumberFormat(null);
mProgressDialog.setProgressPercentFormat(null);
mProgressDialog.show();
//---------progressbar end
uploaddatatodb();
return;
}
});
//-----------------view button
openActivityBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,ItemsActivity.class);
startActivity(intent);
// mProgressDialog.show();
}
});
//-----------------view button
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(int i = 0; i < count; i++) {
// Uri filepath = data.getClipData().getItemAt(i).getUri();
}
//do something with the image (save it to some directory or whatever you need to do with it here)
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//do something with the image (save it to some directory or whatever you need to do with it here)
// Uri filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(imagePath);
bitmap = BitmapFactory.decodeStream(inputStream);
img.setImageBitmap(bitmap);
encodeBitmapImage(bitmap);
} catch (Exception ex) {
}
}
//start
if (requestCode == 2 && resultCode == RESULT_OK) {
Uri filepath = data.getData();
try {
InputStream inputStream_two = getContentResolver().openInputStream(filepath);//two
bitmap_two = BitmapFactory.decodeStream(inputStream_two); //two
img_two.setImageBitmap(bitmap_two);
encodeBitmapImage_two(bitmap_two);
} catch (Exception ex) {
}
}//end
//start 3
if (requestCode == 3 && resultCode == RESULT_OK) {
Uri filepath = data.getData();
try {
InputStream inputStream_three = getContentResolver().openInputStream(filepath);//two
bitmap_three = BitmapFactory.decodeStream(inputStream_three); //two
img_three.setImageBitmap(bitmap_three);
encodeBitmapImage_three(bitmap_three);
} catch (Exception ex) {
}
}//end 3
//start 4
if (requestCode == 4 && resultCode == RESULT_OK) {
Uri filepath = data.getData();
try {
InputStream inputStream_four = getContentResolver().openInputStream(filepath);//two
bitmap_four = BitmapFactory.decodeStream(inputStream_four); //two
img_four.setImageBitmap(bitmap_four);
encodeBitmapImage_four(bitmap_four);
} catch (Exception ex) {
}
}//end 4
super.onActivityResult(requestCode, resultCode, data);
}
private void encodeBitmapImage(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
encodeImageString=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
// encodeImageString_two=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
}
private void encodeBitmapImage_two(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
// encodeImageString=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
encodeImageString_two=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
}
private void encodeBitmapImage_three(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
// encodeImageString=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
encodeImageString_three=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
}
private void encodeBitmapImage_four(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30,byteArrayOutputStream);
byte[] bytesofimage=byteArrayOutputStream.toByteArray();
// encodeImageString=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
encodeImageString_four=android.util.Base64.encodeToString(bytesofimage, Base64.DEFAULT);
}
//-------------------refresh page after uploaded--------------
public void checkStartOtherActivity(){
// Intent i=new Intent(this, MainActivity.class);
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
private void uploaddatatodb() {
t1 = (EditText) findViewById(R.id.t1);
t2 = (EditText) findViewById(R.id.t2);
final String name = t1.getText().toString().trim();
final String dsg = t2.getText().toString().trim();
// tv_upload1 = (TextView) findViewById(R.id.tv_upload1);
//-----------------------------check imageview got inserted photos?----------
if (img.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.uploadimg).getConstantState()
| img_two.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.uploadimg_two).getConstantState()
| img_three.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.uploadimg_three).getConstantState()
| img_four.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.uploadimg_four).getConstantState()
)
{
Toast.makeText(MainActivity.this,"There are no photos inserted",
Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mProgressDialog.show();
// t1.setText("");
// t2.setText("");
// img.setImageResource(R.drawable.uploadimg);
// img_two.setImageResource(R.drawable.uploadimg_two);
// img_three.setImageResource(R.drawable.uploadimg_three);
// img_four.setImageResource(R.drawable.uploadimg_four);
startActivity(new Intent(getApplicationContext(),MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK));
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this,"Photos uploaded successfully",
Toast.LENGTH_SHORT).show();
// img.setImageResource(R.drawable.uploadimg);
// img_two.setImageResource(R.drawable.uploadimg_two);
// img_three.setImageResource(R.drawable.uploadimg_three);
// img_four.setImageResource(R.drawable.uploadimg_four);
//---------------------without refresh page-------------------
finish();
overridePendingTransition( 0, 0);
startActivity(getIntent());
overridePendingTransition( 0, 0);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this,"Please insert all photos",
Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("t1", name);
map.put("t2", dsg);
map.put("upload", encodeImageString);
map.put("upload_two", encodeImageString_two);
map.put("upload_three", encodeImageString_three);
map.put("upload_four", encodeImageString_four);
return map;
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
}
}
You can do it in the following way . I have used viewBinding in this project and have used the new activity contracts for getting images since startActivity is deprecated .The code is as follows .
public class MainActivity extends AppCompatActivity {
//Getting the binding
ActivityMainBinding binding;
//Defining a contract and assiging it to imageView
ActivityResultLauncher<String> mGetMultipleContent = registerForActivityResult(new ActivityResultContracts.GetMultipleContents(),
new ActivityResultCallback<List<Uri>>() {
#Override
public void onActivityResult(List<Uri> result) {
for (int i = 0; i < result.size(); i++) {
binding.imgone.setImageURI(result.get(0));
binding.imgtwo.setImageURI(result.get(1));
binding.imgthree.setImageURI(result.get(2));
binding.imgfour.setImageURI(result.get(3));
}
}
});
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//Launching contract for getting images
binding.addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mGetMultipleContent.launch("image/*");
}
});
}
}
Use this xml layout for the above code :
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imgone"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imgtwo"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/imgone" />
<ImageView
android:id="#+id/imgthree"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/imgtwo" />
<ImageView
android:id="#+id/imgfour"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/imgthree" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/addButton"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Related
I want to send image as well as data using volley help me i need simplest way to send it please help me i have tried in postman where i selected the file rather than text and send all went well i need like that.
Map<String, String> params = new HashMap<String, String>();
params.put("number", strUserName.trim());
params.put("image", image);
JSONObject json = new JSONObject(params);
String url = "";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url
, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject object = new JSONObject(String.valueOf(response));
String status = object.getString("Status");
if (status.equals("200")) {
Intent intent = new Intent(MainActivity.this, OtpVerification.class);
intent.putExtra("mobile1",strUserName);
startActivity(intent);
finish();
} else if(status.equals("404")) {
Toast.makeText(MainActivity.this, "Please Enter Valid No.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("Ashish", " " + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(jsonObjectRequest);
}
I have tried this now but its shopwing me the error my value on addstring are not passing they are sending empty as i am directly putting the value too.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
btnChoose = findViewById(R.id.button_choose);
btnUpload = findViewById(R.id.button_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_REQUEST) {
Uri picUri = data.getData();
filePath = getPath(picUri);
Log.d("picUri", picUri.toString());
Log.d("filePath", filePath);
imageView.setImageURI(picUri);
}
}
}
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr1= new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("status");
if (message.equals("201")) {
Toast.makeText(getApplicationContext(), message + "Done", Toast.LENGTH_LONG).show();
} else if (message.equals("200")) {
Toast.makeText(getApplicationContext(), message + "Done", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr1.addStringParam("a_k_s_no", "1112");
smr1.addStringParam("year", "2020");
smr1.addStringParam("month", "01");
smr1.addStringParam("token", "5c041062bf7ab2a409f910ab34fe6e1e");
smr1.addFile("fileToUpload", imagePath);
MyApplication.getInstance().addToRequestQueue(smr1);
}
private String getPath(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Sample Code :
Volley Image Upload Layout
For creating the above layout you can use the following xml code
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Upload Image using Volley"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/button_choose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="Browse Image"
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_margin="20dp"
android:padding="10dp"/>
<ImageView
android:id="#+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#drawable/border"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:layout_margin="20dp"/>
<Button
android:id="#+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="upload"
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_margin="20dp"/>
</LinearLayout>
Now lets come to MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btnChoose, btnUpload;
public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
static final int PICK_IMAGE_REQUEST = 1;
String filePath;
Now implement OnClickListener interface to our buttons.
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
Now we will create a method to choose image from gallery. Create the following method.
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
To complete the image choosing process we need to override the following method.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
filePath = getPath(picUri);
imageView.setImageURI(picUri);
}
}
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
More information about Android Images, read chapter Amazing Facts of Android ImageView.
Now run your application and if you can choose image from gallery then you can move ahead. In below snapshot you can see mine app is working.Image Upload Using Volley
Now we need to create one more method that will upload the image to our server. Create the following method in MainActivity class.
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
So the final complete code for our MainActivity.java file would be like
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btnChoose, btnUpload;
public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
static final int PICK_IMAGE_REQUEST = 1;
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
btnChoose = (Button) findViewById(R.id.button_choose);
btnUpload = (Button) findViewById(R.id.button_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
Log.d("picUri", picUri.toString());
Log.d("filePath", filePath);
imageView.setImageURI(picUri);
}
}
}
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
}
Now at last add below permission to your application.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MyApplication.java
public class MyApplication extends Application {
public static final String TAG = MyApplication.class.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Hope this will work!
I am building an app to upload images to my company server
I am using koush-ion for the upload,
now my problem is I have to dynamically change the URL for upload depending on information entered in another activity(LoginActivity) via edittext boxes
and I don't understand how to do that
so what I want to happen is the client enters thier Email, password and clientID(4 digits)(in LoginActivity) and the app uses that to build a url for the upload
like this one(in CameraActivity)
https://www.blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes&ClientID=1234&Username=man#blahpractice.co.za&Pwd=BlahBlah123#
I got this From the koush github, and i am unsure if this is what i am looking for and also how to implement data from another activity in koush-ion
Post application/x-www-form-urlencoded and read a String
Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.setBodyParameter("goop", "noop")
.setBodyParameter("foo", "bar")
.asString()
.setCallback(...)
Camera Activity
public class CameraActivity extends AppCompatActivity implements
View.OnClickListener{
private final int PICK_IMAGE = 12345;
private final int REQUEST_CAMERA = 6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION =5674;
private Bitmap bitmap;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView =findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
fromCamera.setVisibility(View.GONE);
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fromCamera:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_ACCESS_PERMISSION);
}else {
getImageFromCamera();
}
break;
case R.id.fromGallery:
getImageFromGallery();
break;
case R.id.upload:
if (bitmap != null)
uploadImageToServer();
break;
}
}
private void uploadImageToServer() {
I want to call the url here
File imageFile = persistImage(bitmap, "SP_Upload");
Ion.with(this)
.load("https://www.Blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes")
.setMultipartFile("SP-LOG", "image/jpeg", imageFile)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
}
});
}
private File persistImage(Bitmap bitmap, String name) {
File filesDir = getApplicationContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
return imageFile;
}
private void getImageFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void getImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImageFromCamera();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private EditText email, password, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
Button loginBtn=findViewById(R.id.button);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emailAddress=email.getText().toString().trim();
String userPassword=password.getText().toString().trim();
String clientId=id.getText().toString().trim();
Intent intent=new Intent(LoginActivity.this, CameraActivity.class);
intent.putExtra("clientId", clientId);
intent.putExtra("email", emailAddress);
intent.putExtra("password", userPassword);
startActivity(intent);
}
});
}
}
You could store the url on the shared preferences and retrieve it every time you execute your upload task and set it on the .load() method.
Also, what you need to send an image to your server is a multipart post. I haven't used Ion but I have used multipart in other libraries like OkHttp, I´ve copied the method that appears on the Ion documentation:
String dynamicUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(CURRENT_SELECTED_URL, null);
File myImage = new File(myImagePath);
if(dynamicUrl != null) {
Ion.with(getContext())
.load(dynamicUrl)
.uploadProgressBar(uploadProgressBar)
.setMultipartParameter("goop", "noop")
.setMultipartFile("myImageName", "image/*", myImage)
.asJsonObject()
.setCallback(...)
}
I keep getting the same error and the app stops working when I try and select an image to upload for user using google firease firebaseAuth on android. Here is the error I keep getting: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzbq"
My code is as follows:
public class StudentAccount extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
public static final int CAMERA_REQUEST_CODE = 10;
public static final int PROFILE_PIC_REQUEST_CODE = 20;
private Button button, signout;
private FirebaseAuth mAuth;
TextView username;
ImageView imageView;
EditText editText;
Uri uriProfileImage;
ProgressBar progressBar;
String profileImageUrl;
ListView listView;
private List<String> userList = new ArrayList<>();
private final int BARCODE_RECO_REQ_CODE = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_account);
mAuth = FirebaseAuth.getInstance();
signout = (Button) findViewById(R.id.SIGNOUT3);
username = (TextView) findViewById(R.id.welcomeText2);
//Check if user i already logged in or not
if (mAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
}
//Fetching display name of current user and setting to activity
FirebaseUser user = mAuth.getCurrentUser();
if (user != null){
username.setText("Welcome " +user.getEmail());
}
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
imageView = findViewById(R.id.imageView);
progressBar = findViewById(R.id.progressbar);
mAuth = FirebaseAuth.getInstance();
button = findViewById(R.id.VIEW_ATTENDANCE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openViewMyAttendance();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
findViewById(R.id.buttonSave).setOnClickListener( new View.OnClickListener(){
#Override
public void onClick(View view) {
saveUserInformation();
}
private void saveUserInformation() {
String displayName = editText.getText().toString();
if (displayName.isEmpty()){
editText.setError("Username required");
editText.requestFocus();
return;
}
FirebaseUser user = mAuth.getCurrentUser();
if (user != null && profileImageUrl != null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
.setDisplayName(displayName).setPhotoUri(Uri.parse(profileImageUrl)).build();
user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(StudentAccount.this, "Profile Updated", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() !=null){
uriProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
imageView.setImageBitmap(bitmap);
uploadImageToFirebaseStorage();
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == BARCODE_RECO_REQ_CODE){
if (resultCode == RESULT_OK){
Bitmap photo = (Bitmap)data.getExtras().get("data");
barcodeRecognition(photo);
}
}
}
private void barcodeRecognition(Bitmap photo) {
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(photo);
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
.getVisionBarcodeDetector();
Task<List<FirebaseVisionBarcode>> result = detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> barcodes) {
for (FirebaseVisionBarcode barcode: barcodes) {
Rect bounds = barcode.getBoundingBox();
Point[] corners = barcode.getCornerPoints();
String rawValue = barcode.getRawValue();
int valueType = barcode.getValueType();
Toast.makeText(StudentAccount.this, rawValue, Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StudentAccount.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private void uploadImageToFirebaseStorage() {
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference
("profilepics/"+System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null){
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(StudentAccount.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void loadUserInformation() {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
updateProfilePermissions();
} else {
String[] permissionRequested = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissionRequested, PROFILE_PIC_REQUEST_CODE);
}
}
private void updateProfilePermissions() {
FirebaseUser user = mAuth.getCurrentUser();
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl().toString()).into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
}
private void showImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Profile Image"),CHOOSE_IMAGE);
}
#Override
protected void onPause(){
super.onPause();
}
public void barcodeReco(View v) {
if(checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
callsCamera();
} else {
String[] permissionRequested = {Manifest.permission.CAMERA};
requestPermissions(permissionRequested, CAMERA_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_REQUEST_CODE){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
callsCamera();
} else {
Toast.makeText(this, getString(R.string.unable_to_invoke_camera), Toast.LENGTH_LONG).show();
}
} else if (requestCode == PROFILE_PIC_REQUEST_CODE){
if (grantResults [0] == PackageManager.PERMISSION_GRANTED){
loadUserInformation();
} else {
Toast.makeText( this, getString(R.string.Unable_to_update_profile), Toast.LENGTH_LONG).show();
}
}
}
private void callsCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,BARCODE_RECO_REQ_CODE);
}
public void openViewMyAttendance () {
Intent intent = new Intent(this, ViewMyAttendance.class);
startActivity(intent);
}
}
My Activity class:
public class CommonChattingAttachmentActivity
extends AppCompatActivity {
Realm realm;
RealmChangeListener realmChangeListener;
CommonChattingAttachmentCustomAdapter adapter;
ListView lv;
EditText descEditTxt;
boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
String userChoosenTask;
TextView descTxt;
ImageView imgallery, imgcam, img;
private static final int REQUEST_CAMERA = 1888;
private static final int SELECT_FILE = 1889;
ImageView imgattach;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_common_chatting_attachment);
lv = (ListView) findViewById(R.id.Listview_common);
//img=(ImageView)findViewById(R.id.img);
//descTxt= (TextView) findViewById(R.id.textdesc);
//INITIALIZE REALM
realm = Realm.getDefaultInstance();
setAdapter();
displayInputDialog();
imgcam = (ImageView) findViewById(R.id.imgcam);
imgallery = (ImageView) findViewById(R.id.imggallery);
imgattach = (ImageView) findViewById(R.id.imgattach);
imgallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
galleryIntent();
}
});
imgcam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cameraIntent();
}
});
imgattach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
public void setAdapter() {
//lv= (ListView) findViewById(R.id.Listview_common);
final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
helper.retrieveFromDB();
adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange() {
adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
realm.addChangeListener(realmChangeListener);
}
private void setAdapters() {
lv = (ListView) findViewById(R.id.Listview_common);
//INITIALIZE REALM
realm = Realm.getDefaultInstance();
final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
helper.retrieveFromDB();
adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange() {
adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
realm.addChangeListener(realmChangeListener);
}
//DISPLAY INPUT DIALOG
public void displayInputDialog() {
//EDITTEXTS
descEditTxt = (EditText) findViewById(R.id.editwrite);
ImageView fab = (ImageView) findViewById(R.id.send);
//SAVE
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// descTxt.setVisibility(View.VISIBLE);
//img.setVisibility(View.GONE);
String desc = descEditTxt.getText().toString();
CommonChat s = new CommonChat();
s.setDescription(desc);
CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
if(helper.save(s)) {
descEditTxt.setText("");
} else {
Toast.makeText(CommonChattingAttachmentActivity.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
}
});
}
public void cameraIntent() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Intent intent = new Intent(MediaStore.EXTRA_OUTPUT);
startActivityForResult(intent, REQUEST_CAMERA);
}
public void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
public void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CommonChattingAttachmentActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
if(items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if(result) {
cameraIntent();
}
} else if(items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if(result) {
galleryIntent();
}
} else if(items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch(requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo")) {
cameraIntent();
} else if(userChoosenTask.equals("Choose from Library")) {
galleryIntent();
}
} else {
//code for deny
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK) {
if(requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
} else if(requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
}
}
#SuppressWarnings("deprecation")
public void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if(data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch(IOException e) {
e.printStackTrace();
}
}
SaveImageVideoData(String.valueOf(bm));
setAdapters();
}
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
SaveImageVideoData(String.valueOf(destination));
setAdapters();
}
public void SaveImageVideoData(String data) {
try {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CommonChat s = realm.createObject(CommonChat.class);
// obj.setExtensionTypeValue(stringMediaExtType);
s.setImageUrl(data);
realm.commitTransaction();
realm.close();
setAdapters();
Log.d("path", data);
Log.d("working realm", "yes....");
} catch(Exception ex) {
}
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
My Adapter Class
public class CommonChattingAttachmentCustomAdapter
extends BaseAdapter {
Context c;
ArrayList<CommonChat> CommonChats;
public CommonChattingAttachmentCustomAdapter(Context c, ArrayList<CommonChat> CommonChats) {
this.c = c;
this.CommonChats = CommonChats;
}
#Override
public int getCount() {
return CommonChats.size();
}
#Override
public Object getItem(int position) {
return CommonChats.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = LayoutInflater.from(c).inflate(R.layout.item_commonchat, parent, false);
}
TextView descTxt = (TextView) convertView.findViewById(R.id.textdesc);
ImageView img = (ImageView) convertView.findViewById(R.id.img);
final CommonChat s = (CommonChat) this.getItem(position);
if(descTxt != null) {
descTxt.setVisibility(View.VISIBLE);
img.setVisibility(View.GONE);
descTxt.setText(s.getDescription());
}
String imageUrl = s.getImageUrl();
if(imageUrl != null && imageUrl.length() > 0) {
img.setVisibility(View.VISIBLE);
descTxt.setVisibility(View.GONE);
Picasso.with(c).load(imageUrl).placeholder(R.mipmap.ic_launcher).into(img);
} else {
Picasso.with(c).load(R.mipmap.ic_launcher).into(img);
}
return convertView;
}
}
My RealmHelper Class:
public class CommonChatRealmHelper {
Realm realm;
RealmResults<CommonChat> CommonChats;
Boolean saved = null;
public CommonChatRealmHelper(Realm realm) {
this.realm = realm;
}
//WRITE
public Boolean save(final CommonChat CommonChat) {
if(CommonChat == null) {
saved = false;
} else {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
CommonChat s = realm.copyToRealm(CommonChat);
saved = true;
} catch(RealmException e) {
e.printStackTrace();
saved = false;
}
}
});
}
return saved;
}
//READ
public void retrieveFromDB() {
CommonChats = realm.where(CommonChat.class).findAll();
}
// REFRESH
public ArrayList<CommonChat> justRefresh() {
ArrayList<CommonChat> latest = new ArrayList<>();
for(CommonChat s : CommonChats) {
latest.add(s);
Log.d("Testing", String.valueOf(s));
}
return latest;
}
}
Blockquote 10-06 10:46:40.735 24930-24930/com.xitiz.xitizmobile D/Testing: CommonChat = [{description:null},{imageUrl:/storage/emulated/0/1507267000613.jpg}]
10-06 10:46:40.745 24930-24930/com.xitiz.xitizmobile D/path: /storage/emulated/0/1507267000613.jpg
**My Edited Code Snippet of URI**
public class CommonChattingAttachmentActivity
extends AppCompatActivity {
Realm realm;
RealmChangeListener realmChangeListener;
CommonChattingAttachmentCustomAdapter adapter;
ListView lv;
EditText descEditTxt;
boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
String userChoosenTask;
TextView descTxt;
ImageView imgallery, imgcam, img;
private static final int REQUEST_CAMERA = 1888;
private static final int SELECT_FILE = 1889;
ImageView imgattach;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_common_chatting_attachment);
lv = (ListView) findViewById(R.id.Listview_common);
//img=(ImageView)findViewById(R.id.img);
//descTxt= (TextView) findViewById(R.id.textdesc);
//INITIALIZE REALM
realm = Realm.getDefaultInstance();
setAdapter();
displayInputDialog();
imgcam = (ImageView) findViewById(R.id.imgcam);
imgallery = (ImageView) findViewById(R.id.imggallery);
imgattach = (ImageView) findViewById(R.id.imgattach);
imgallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
galleryIntent();
}
});
imgcam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cameraIntent();
}
});
imgattach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
public void setAdapter() {
//lv= (ListView) findViewById(R.id.Listview_common);
final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
helper.retrieveFromDB();
adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange() {
adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
realm.addChangeListener(realmChangeListener);
}
private void setAdapters() {
lv = (ListView) findViewById(R.id.Listview_common);
//INITIALIZE REALM
realm = Realm.getDefaultInstance();
final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
helper.retrieveFromDB();
adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange() {
adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
realm.addChangeListener(realmChangeListener);
}
//DISPLAY INPUT DIALOG
public void displayInputDialog() {
//EDITTEXTS
descEditTxt = (EditText) findViewById(R.id.editwrite);
ImageView fab = (ImageView) findViewById(R.id.send);
//SAVE
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// descTxt.setVisibility(View.VISIBLE);
//img.setVisibility(View.GONE);
String desc = descEditTxt.getText().toString();
CommonChat s = new CommonChat();
s.setDescription(desc);
CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
if(helper.save(s)) {
descEditTxt.setText("");
} else {
Toast.makeText(CommonChattingAttachmentActivity.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
}
});
}
public void cameraIntent() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Intent intent = new Intent(MediaStore.EXTRA_OUTPUT);
startActivityForResult(intent, REQUEST_CAMERA);
}
public void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
public void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CommonChattingAttachmentActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
if(items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if(result) {
cameraIntent();
}
} else if(items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if(result) {
galleryIntent();
}
} else if(items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch(requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo")) {
cameraIntent();
} else if(userChoosenTask.equals("Choose from Library")) {
galleryIntent();
}
} else {
//code for deny
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK) {
if(requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
} else if(requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
}
}
#SuppressWarnings("deprecation")
public void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if(data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch(IOException e) {
e.printStackTrace();
}
}
Uri myUri = Uri.parse(String.valueOf(bm));
SaveImageVideoData(String.valueOf(myUri));
// setAdapters();
}
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
// SaveImageVideoData(String.valueOf(destination));
// setAdapters();
Uri myUri = Uri.parse(String.valueOf(destination));
SaveImageVideoData(String.valueOf(myUri));
}
public void SaveImageVideoData(String data) {
try {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CommonChat s = realm.createObject(CommonChat.class);
// obj.setExtensionTypeValue(stringMediaExtType);
s.setImageUrl(data);
realm.commitTransaction();
realm.close();
setAdapters();
Log.d("path", data);
Log.d("working realm", "yes....");
} catch(Exception ex) {
}
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
You need to first convert your image url to a Uri, and then load it using Picasso the same way you did.
As I am seeing in the log you are using just the same url string in the load method parameter. So kindly convert image url (String) to Uri and then try it.
Hope this will work. Please do update.
Instead of this code
public class CommonChattingAttachmentActivity
extends AppCompatActivity {
Realm realm;
//RealmChangeListener realmChangeListener;
CommonChattingAttachmentCustomAdapter adapter;
ListView lv;
EditText descEditTxt;
boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
String userChoosenTask;
TextView descTxt;
ImageView imgallery, imgcam, img;
private static final int REQUEST_CAMERA = 1888;
private static final int SELECT_FILE = 1889;
ImageView imgattach;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_common_chatting_attachment);
lv = (ListView) findViewById(R.id.Listview_common);
//img=(ImageView)findViewById(R.id.img);
//descTxt= (TextView) findViewById(R.id.textdesc);
//INITIALIZE REALM
realm = Realm.getDefaultInstance();
setAdapter();
displayInputDialog();
imgcam = (ImageView) findViewById(R.id.imgcam);
imgallery = (ImageView) findViewById(R.id.imggallery);
imgattach = (ImageView) findViewById(R.id.imgattach);
imgallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
galleryIntent();
}
});
imgcam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cameraIntent();
}
});
imgattach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
public void setAdapter() {
//lv= (ListView) findViewById(R.id.Listview_common);
//final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
//helper.retrieveFromDB();
//adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
lv.setAdapter(adapter);
//adapter.notifyDataSetChanged();
//realmChangeListener = new RealmChangeListener() {
// #Override
// public void onChange() {
// adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
// lv.setAdapter(adapter);
// adapter.notifyDataSetChanged();
// }
// };
// realm.addChangeListener(realmChangeListener);
}
private void setAdapters() {
lv = (ListView) findViewById(R.id.Listview_common);
//INITIALIZE REALM
// realm = Realm.getDefaultInstance();
//final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
// helper.retrieveFromDB();
// adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
lv.setAdapter(adapter);
// adapter.notifyDataSetChanged();
// realmChangeListener = new RealmChangeListener() {
// #Override
// public void onChange() {
// adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
// lv.setAdapter(adapter);
// adapter.notifyDataSetChanged();
// }
//};
//realm.addChangeListener(realmChangeListener);
}
//DISPLAY INPUT DIALOG
public void displayInputDialog() {
//EDITTEXTS
descEditTxt = (EditText) findViewById(R.id.editwrite);
ImageView fab = (ImageView) findViewById(R.id.send);
//SAVE
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// descTxt.setVisibility(View.VISIBLE);
//img.setVisibility(View.GONE);
String desc = descEditTxt.getText().toString();
CommonChat s = new CommonChat();
s.setDescription(desc);
CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
if(helper.save(s)) {
descEditTxt.setText("");
} else {
Toast.makeText(CommonChattingAttachmentActivity.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
}
});
}
public void cameraIntent() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Intent intent = new Intent(MediaStore.EXTRA_OUTPUT);
startActivityForResult(intent, REQUEST_CAMERA);
}
public void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
public void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CommonChattingAttachmentActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
if(items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if(result) {
cameraIntent();
}
} else if(items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if(result) {
galleryIntent();
}
} else if(items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch(requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo")) {
cameraIntent();
} else if(userChoosenTask.equals("Choose from Library")) {
galleryIntent();
}
} else {
//code for deny
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK) {
if(requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
} else if(requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
}
}
#SuppressWarnings("deprecation")
public void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if(data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch(IOException e) {
e.printStackTrace();
}
}
SaveImageVideoData(String.valueOf(bm));
setAdapters();
}
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
SaveImageVideoData(String.valueOf(destination));
setAdapters();
}
public void SaveImageVideoData(String data) {
try {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CommonChat s = realm.createObject(CommonChat.class);
// obj.setExtensionTypeValue(stringMediaExtType);
s.setImageUrl(data);
realm.commitTransaction();
realm.close();
setAdapters();
Log.d("path", data);
Log.d("working realm", "yes....");
} catch(Exception ex) {
}
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
and
public class CommonChattingAttachmentCustomAdapter
extends BaseAdapter {
Context c;
// ArrayList<CommonChat> CommonChats;
// #Override
// public int getCount() {
// return CommonChats.size();
// }
// #Override
// public Object getItem(int position) {
// return CommonChats.get(position);
// }
// #Override
// public long getItemId(int position) {
// return position;
// }
and
public class CommonChatRealmHelper {
Realm realm;
// RealmResults<CommonChat> CommonChats;
// Boolean saved = null;
public CommonChatRealmHelper(Realm realm) {
this.realm = realm;
}
// WRITE
public Boolean save(final CommonChat CommonChat) {
if(CommonChat == null) {
saved = false;
} else {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
CommonChat s = realm.copyToRealm(CommonChat);
saved = true;
} catch(RealmException e) {
e.printStackTrace();
saved = false;
}
}
});
}
return saved;
}
// //READ
// public void retrieveFromDB() {
// CommonChats = realm.where(CommonChat.class).findAll();
// }
// // REFRESH
// public ArrayList<CommonChat> justRefresh() {
// ArrayList<CommonChat> latest = new ArrayList<>();
// for(CommonChat s : CommonChats) {
// latest.add(s);
// Log.d("Testing", String.valueOf(s));
// }
// return latest;
// }
}
You should do:
public class CommonChattingAttachmentCustomAdapter
extends RealmBaseAdapter { // from https://github.com/realm/realm-android-adapters
public CommonChattingAttachmentCustomAdapter(OrderedRealmCollection<ChatCommon> results) {
super(results);
}
and
public void setAdapter() {
//lv= (ListView) findViewById(R.id.Listview_common);
//final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
//helper.retrieveFromDB();
adapter = new CommonChattingAttachmentCustomAdapter(realm.where(CommonChat.class).findAll());
//adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
lv.setAdapter(adapter);
See which code was commented out, that should generally be deleted entirely
I am trying to build an app that enables you to change your profile picture. When the app opens for the first time, it contains a Networkimageview for the current profile pic and a button to change the picture. When the button is pressed a new Activity is started that enables one to choose an image from the gallery and upload to a server.
When the upload is done, the new Activity is closed and the app returns to the MainActivity. How can I make the MainActivity to reload the image just uploaded to the server when the image uploads successfully from the new activity and closes? This is my code
Here's the MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private Button buttonChoose;
static final int PROFILE_PICTURE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
loadImage();
}
private String url = "http://10.0.2.2/images/0.jpg";
private void loadImage() {
mImageLoader = CustomVolleyRequest.getInstance(this).getImageLoader();
mNetworkImageView.setImageUrl(url, mImageLoader);
}
public void newActivity(View view) {
Intent profileIntent = new Intent(this, Activity2.class);
startActivityForResult(profileIntent, PROFILE_PICTURE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PROFILE_PICTURE_REQUEST) {
if (resultCode == RESULT_OK) {
loadImage();
}
}
}
}
The second activity Activity2.java
public class Activity2 extends AppCompatActivity implements View.OnClickListener {
private Bitmap bitmap;
private ImageView imageView;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="http://10.0.2.2/uploadd.php";
private String KEY_IMAGE = "image";
private Button buttonUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonUpload.setOnClickListener(this);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage() {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(Activity2.this, s, Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(RESULT_OK,returnIntent);
finish();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(Activity2.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
#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) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if(v == buttonUpload){
uploadImage();
}
}
}
When you're finishing the Activity2 on a successful image upload, you need to put some extras in the intent which is passed to the launcher activity which is MainActivity.
So the onResponse segment of your uploadImage() function should look like the following. Declare the filePath variable as public so that you can use it here too.
// Declare filePath as public
Uri filePath;
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(Activity2.this, s, Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("UPDATED_PIC", filePath.toString());
setResult(RESULT_OK,returnIntent);
finish();
}
Now from your MainActivity handle the retuneIntent to get the filePath and load the image from there. So the onActivityResult may look like -
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PROFILE_PICTURE_REQUEST) {
if (resultCode == RESULT_OK) {
if(data != null) {
Uri filePath = Uri.parse(extras.getString("UPDATED_PIC"));
try {
//Getting the Bitmap from Gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// Setting the Bitmap to ImageView
mNetworkImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}