Related
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>
I want to show my image in imageview after click but i don't know why this error occur and i searched a lot on this but i could no find solution of this problem and i tried to implement code after see solution but it doesn't work,so i m confused what's going wrong.This is my code:
package kmsg.com.onetouch.activity;
public class UploadDocumentActivity extends AppCompatActivity {
JSONParser parser;
Bitmap photo;
ImageView mImgDocument;
Button mBtnBill,mBtnPres,mBtnGetFile,mBtnUpload;
EditText mEtBillDate,mEtbillValue,mEtStoreRefID,mEtDoctorID;
LinearLayout mBillLinear,mPresLinear;
String mBillDate,mBillValue,mStoreRefID,mDoctorID;
boolean flag= true;
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_document);
parser = new JSONParser(this);
init();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
private void init() {
mImgDocument=(ImageView)findViewById(R.id.imgDocument);
mBtnBill=(Button)findViewById(R.id.btnBill);
mBtnPres=(Button)findViewById(R.id.btnPres);
mBtnGetFile=(Button)findViewById(R.id.btnGetFile);
mBtnUpload=(Button)findViewById(R.id.btnUpload);
mEtBillDate=(EditText)findViewById(R.id.et_billDate);
mEtbillValue=(EditText)findViewById(R.id.et_billValue);
mEtStoreRefID=(EditText)findViewById(R.id.et_refID);
mEtDoctorID=(EditText)findViewById(R.id.et_doctorID);
mBillLinear=(LinearLayout)findViewById(R.id.bill_linear);
mPresLinear=(LinearLayout)findViewById(R.id.prescription_linear);
}
public void getBill(View view) {
flag= true;
mPresLinear.setVisibility(View.GONE);
mBillLinear.setVisibility(View.VISIBLE);
}
public void getPrescription(View view) {
flag=false;
mBillLinear.setVisibility(View.GONE);
mPresLinear.setVisibility(View.VISIBLE);
}
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureNm = getPictureName();
imageFile = new File(pictureDirectory , pictureNm);
Uri pictureUri = Uri.fromFile(imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
/* public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CAMERA_REQUEST);
}
}
*/
private String getPictureName(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "paymentProof" + timestamp + ".jpg";
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_CANCELED){
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImgDocument.setImageBitmap(photo);
}
}
}
private boolean validateFormForBill() {
mBillDate = mEtBillDate.getText().toString().trim();
mBillValue = mEtbillValue.getText().toString().trim();
mStoreRefID = mEtStoreRefID.getText().toString().trim();
mEtBillDate.setError(null);
mEtbillValue.setError(null);
mEtStoreRefID.setError(null);
if (TextUtils.isEmpty(mBillDate.trim())) {
mEtBillDate.setError("Bill Date cannot be blank");
return false;
}
if (TextUtils.isEmpty(mBillValue.trim())) {
mEtbillValue.setError("Bill Value cannot be blank");
return false;
}
if (TextUtils.isEmpty(mStoreRefID.trim())) {
mEtStoreRefID.setError("Ref ID cannot be blank");
return false;
}
return true;
}
private boolean validateFormForPres() {
mDoctorID = mEtDoctorID.getText().toString().trim();
mEtDoctorID.setError(null);
if (TextUtils.isEmpty(mDoctorID.trim())) {
mEtDoctorID.setError("Doctor ID cannot be blank");
return false;
}
return true;
}
public void uploadDocument(View view) {
if (UtilityServices.checkInternetConnection(UploadDocumentActivity.this)) {
if (flag) {
if (UploadDocumentActivity.this.validateFormForBill()) {
new UploadBill().execute();
}
} else {
if (UploadDocumentActivity.this.validateFormForPres()) {
// new UploadPres().execute();
}
}
}else {
Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
}
}
private class UploadBill extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("billAmt", mBillValue));
partList.add(new StringPart("billDate", mBillDate));
partList.add(new StringPart("storeId", mStoreRefID));
System.out.println("Data"+mBillDate+mBillValue+mStoreRefID);
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")));
/* try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}*/
String url = Constants.UPLOAD_BILL;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
private class UploadPres extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("storeId", mDoctorID));
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")+""));
try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String url = Constants.UPLOAD_PRESCRIPTION;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
}
This is my class and i am trying to capture an image on click a button and then save into directory after that show into imageview and then want to send to server,i hope you will help me as a best programmer.
this question may be a duplicate of this.
Basically, when you pass an OutPut file to the intent, you cannot read data from extra, you have to make sure that CameraApplication has access to your files. You are getting this exception, because CameraApplication cannot save the file on your directory, you need to add a file provider...
Please make your code is same as the base android documentation.
Try This
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
I've written an application which should take picture and record video and then show it on the screen. When trying it on phone the camera won't work but works in emulator.
When executing the app this is what exactly happens:
Every time I clicked on the button to open the camera, the app stopped and the error it display is Appname has stopped, Open app again
When I clicked on Open app again it return to normal state
I have granted the camera permission in my program
below is my code:
public class EventActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
public static final String KEY_MENU_TYPE = "menutype";
//public static final String KEY_PREF_USER_DETAILS = "prefUserDetails";
private static final String TAG = EventActivity.class.getSimpleName();
private static final String SERVER_IMAGE_PATH = "http://edo.com/imageupload/";
private static final String SERVER_PATH = "http://edo.com/";
String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private EditText event, eventDescription, name;
private TextView attachmentStatus;
private static final int TAKE_PICTURE = 1;
private static final int PERMISSION_ALL = 3;
private Uri capturedImageUri;
private Uri videoUri;
private String mediaFile;
private String videoFile;
private static final int MY_SOCKET_TIMEOUT_MS = 5000;
private String[] serverData;
private static final int REQUEST_VIDEO_CAPTURE = 300;
private boolean isImage;
private String locationResult;
String menutype = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
Intent intent = getIntent();
/* ActionBar mBar = getSupportActionBar();
if(mBar != null){
mBar.setDisplayHomeAsUpEnabled(true);
}*/
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = createLocationRequest();
Button photoVideoButton = (Button)findViewById(R.id.take_image_video);
photoVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showOptionDialog();
}
});
attachmentStatus = (TextView)findViewById(R.id.file_status);
event = (EditText)findViewById(R.id.enter_event);
eventDescription =(EditText)findViewById(R.id.enter_event_description);
name = (EditText)findViewById(R.id.name);
Button cancelUploadButton = (Button) findViewById(R.id.cancel_upload);
assert cancelUploadButton != null;
cancelUploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resetViewControls();
}
});
Button sendToServerButton = (Button) findViewById(R.id.send_to_server);
assert sendToServerButton != null;
sendToServerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String eventValue = event.getText().toString().trim();
String eventDescriptionValue = eventDescription.getText().toString();
String nameValue = name.getText().toString();
String locationValue = "";
if(TextUtils.isEmpty(eventValue) || TextUtils.isEmpty(eventDescriptionValue) || TextUtils.isEmpty(nameValue)){
Toast.makeText(EventActivity.this, getString(R.string.send_to_server_error), Toast.LENGTH_LONG).show();
return;
}
if(locationResult == null || locationResult.equals("")){
locationValue = "";
}else{
locationValue = locationResult;
}
if(TextUtils.isEmpty(mediaFile) && TextUtils.isEmpty(videoFile)){
Toast.makeText(EventActivity.this, "Please attach a photo or video", Toast.LENGTH_LONG).show();
return;
}
if(!TextUtils.isEmpty(mediaFile) && isImage){
// send the information to remote server
Bitmap storeBitmap = BitmapFactory.decodeFile(mediaFile);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(storeBitmap, 640, 420, true);
String imageBasedString = convertBitmapToBaseImageString(resizedBitmap);
serverData = new String[]{eventValue, eventDescriptionValue, nameValue, imageBasedString, locationValue};
sendCapturedImageToServer(serverData);
//move stored video to a new folder
String photoPath = getMovedFilePath(mediaFile, eventValue);
moveFileToNewDestination(mediaFile, photoPath);
}else if(!TextUtils.isEmpty(mediaFile) && !isImage){
//Store the video to your server
uploadVideoToServer(videoFile, eventValue, eventDescriptionValue, nameValue, locationValue);
//move stored video to a new folder
String photoPath = getMovedFilePath(videoFile, eventValue);
moveFileToNewDestination(videoFile, photoPath);
}else{
// Image or video is missing. Show message to user
Toast.makeText(EventActivity.this, getString(R.string.upload_image_or_video), Toast.LENGTH_LONG).show();
}
}
});
this.menutype = intent.getStringExtra(KEY_MENU_TYPE);
if (this.menutype == null) {
this.menutype = "";
}
}
public void goBack(View view) {
Intent intent;
if (this.menutype.equals("PRE")) {
intent = new Intent(this, PreElectionMenuActivity.class);
} else if (this.menutype.equals("ACC")) {
intent = new Intent(this, AccreditationMenuActivity.class);
} else if (this.menutype.equals("ELE")) {
intent = new Intent(this, VotingMenuActivity.class);
} else if (this.menutype.equals("INC")) {
intent = new Intent(this, IncidentMenuActivity.class);
} else {
intent = new Intent(this, HomeActivity.class);
}
startActivity(intent);
}
private String getMovedFilePath(String filePath, String eventName){
int indexPosition = filePath.lastIndexOf(".");
String fileExtension = filePath.substring(indexPosition, filePath.length());
String newFilename = eventName + fileExtension;
return getFileDestinationPath(newFilename);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == TAKE_PICTURE) {
capturedImageUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = "";
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
Log.d(TAG, "Capture image path" + mediaFile);
attachmentStatus.setText("Image file has been attached");
isImage = true;
}
}
if (requestCode == REQUEST_VIDEO_CAPTURE) {
videoUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else{
videoFile = getRealPathFromURIPath(videoUri, EventActivity.this);
Log.d(TAG, "Captured video path " + videoUri);
Log.d(TAG, "New path " + videoFile);
attachmentStatus.setText("Video file has been attached");
isImage = false;
}
}
}
}
private void resetViewControls(){
event.setText("");
eventDescription.setText("");
name.setText("");
attachmentStatus.setText(R.string.attached_file);
}
#Override
protected void onResume() {
super.onResume();
if(capturedImageUri != null){
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
}
}
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
private String convertBitmapToBaseImageString(Bitmap bitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
return Base64.encodeToString(byte_arr, 0);
}
private void sendCapturedImageToServer(String[] photoDetails){
Map<String, String> params = new HashMap<String,String>();
params.put("EVENT", photoDetails[0]);
params.put("EVENT_DESCRIPTION", photoDetails[1]);
params.put("NAME", photoDetails[2]);
params.put("CAPTURE_IMAGE", photoDetails[3]);
params.put("EVENT_LOCATION", photoDetails[4]);
GsonRequest<ServerObject> serverRequest = new GsonRequest<ServerObject>(
Request.Method.POST,
SERVER_IMAGE_PATH,
ServerObject.class,
params,
createRequestSuccessListener(),
createRequestErrorListener());
serverRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(EventActivity.this).addToRequestQueue(serverRequest);
}
private Response.Listener<ServerObject> createRequestSuccessListener() {
return new Response.Listener<ServerObject>() {
#Override
public void onResponse(ServerObject response) {
try {
Log.d(TAG, "Json Response " + response.getSuccess());
if(!TextUtils.isEmpty(response.getSuccess()) && response.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
};
};
}
private Response.ErrorListener createRequestErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
}
public static void getAddressFromLocation(final double lat, final double lon, final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(lat, lon, 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality() + ", " + address.getCountryName() ;
Log.d(TAG, "The converted Address " + result);
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to GeoCoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
#SuppressLint("HandlerLeak")
private class GeoCoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationResult = bundle.getString("address");
Log.d(TAG, "Location Result " + locationResult);
break;
default:
locationResult = null;
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.d(TAG, "Connection method has been called");
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
else{
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
getAddressFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), EventActivity.this, new GeoCoderHandler());
}
}
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_ALL: {
// If request is cancelled, the result arrays are empty.
if(grantResults[0] == PackageManager.PERMISSION_DENIED){
Toast.makeText(EventActivity.this, "Sorry!!!, you can't use this app without granting this permission", Toast.LENGTH_LONG).show();
finish();
}
if (grantResults[1] == PackageManager.PERMISSION_DENIED || grantResults[2] == PackageManager.PERMISSION_DENIED) {
// permission was denied, show alert to explain permission
showPermissionAlert();
}else{
//permission is granted. Get current location values
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
}
}
}
}
private void showPermissionAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permission_request_title);
builder.setMessage(R.string.app_permission_notice);
builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(EventActivity.this, R.string.permission_refused, Toast.LENGTH_LONG).show();
}
});
builder.show();
}
protected LocationRequest createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private boolean isLocationEnabled(){
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
return false;
}
return true;
}
private void showLocationAlert(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_enable));
dialog.setPositiveButton(getResources().getString(R.string.network_location), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
EventActivity.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private void moveFileToNewDestination(String fromPath, String toPath){
File fromFile = new File(fromPath);
File toFile = new File(toPath);
if(!toFile.exists()){
try {
toFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fromStream = null;
FileOutputStream toStream = null;
try {
fromStream = new FileInputStream(fromFile);
toStream = new FileOutputStream(toFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] sourceByte = new byte[1024];
int index;
try {
while((index = fromStream.read(sourceByte)) > 0){
if (toStream != null) {
toStream.write(sourceByte, 0, index);
}
}
Log.d(TAG, "Video successfully moved to a new location");
} catch (IOException e) {
e.printStackTrace();
}
}
private String getFileDestinationPath(String filename){
String filePathEnvironment = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
File directoryFolder = new File(filePathEnvironment + "/events/");
if(!directoryFolder.exists()){
directoryFolder.mkdir();
}
Log.d(TAG, "Full path " + filePathEnvironment + "/events/" + filename);
return filePathEnvironment + "/events/" + filename;
}
private void uploadVideoToServer(String pathToVideoFile, String eventName, String eventDescription, String eventCoverage, String eventLocation){
File videoFile = new File(pathToVideoFile);
RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
RequestBody event = RequestBody.create(MediaType.parse("text/plain"), eventName);
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), eventDescription);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), eventCoverage);
RequestBody location = RequestBody.create(MediaType.parse("text/plain"), eventLocation);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_PATH)
.addConverterFactory(GsonConverterFactory.create())
.build();
VideoInterface vInterface = retrofit.create(VideoInterface.class);
Call<ResultObject> serverCom = vInterface.uploadVideoToServer(vFile, event, description, name, location);
serverCom.enqueue(new Callback<ResultObject>() {
#Override
public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
ResultObject result = response.body();
if(!TextUtils.isEmpty(result.getSuccess()) && result.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResultObject> call, Throwable t) {
Log.d(TAG, "Error message " + t.getMessage());
}
});
}
private void showOptionDialog(){
final Dialog dialog = new Dialog(EventActivity.this);
dialog.setTitle("SELECT ACTION TO COMPLETE");
dialog.setContentView(R.layout.image_video_layout);
final TextView takePhoto = (TextView)dialog.findViewById(R.id.take_photo);
final TextView recordVideo = (TextView)dialog.findViewById(R.id.record_video);
dialog.show();
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Take a picture");
if(isLocationEnabled()){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
}else{
showLocationAlert();
}
dialog.dismiss();
}
});
recordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Record a video");
Intent videoCaptureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if(videoCaptureIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(videoCaptureIntent, REQUEST_VIDEO_CAPTURE);
}
dialog.dismiss();
}
});
}
private boolean gps_enabled;
private boolean network_enabled;
Android app crashes when linking to another page
Every time I clicked on the button I created to go to the next Activity, the app crashes.
Here is the code I used:
public void openPictureCaptures(View view) {
Intent intent = new Intent(this, EventActivity.class);
this.startActivity ( intent );
}
The Activity I am linking to(EventActivity.class):
public class EventActivity extends Activity {
//public static final String KEY_MENU_TYPE = "menutype";
Button CaptureImageFromCamera,UploadImageToServer;
ImageView ImageViewHolder;
EditText imageName;
EditText detailText;
ProgressDialog progressDialog ;
Intent intent ;
public static final int RequestPermissionCode = 1 ;
Bitmap bitmap;
boolean check = true;
String GetImageNameFromEditText;
String GetImageDescFromEditText;
String ImageNameFieldOnServer = "event" ;
String ImageDescOnServer = "description";
String ImagePathFieldOnServer = "image" ;
//String menutype = "";
String ImageUploadPathOnSever ="http://getme.com/osunelection/capture_img_upload_to_server.php" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
CaptureImageFromCamera = (Button)findViewById(R.id.button);
ImageViewHolder = (ImageView)findViewById(R.id.imageView);
UploadImageToServer = (Button) findViewById(R.id.button2);
imageName = (EditText)findViewById(R.id.editText);
detailText = (EditText) findViewById(R.id.detailText);
EnableRuntimePermissionToAccessCamera();
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
UploadImageToServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetImageNameFromEditText = imageName.getText().toString();
GetImageDescFromEditText = detailText.getText().toString();
ImageUploadToServerFunction();
}
});
/* this.menutype = intent.getStringExtra(KEY_MENU_TYPE);
if (this.menutype == null) {
this.menutype = "";
}*/
}
// Star activity for result method to Set captured image on image view after click.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 7 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
// Adding captured image in bitmap.
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// adding captured image in imageview.
ImageViewHolder.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Requesting runtime permission to access camera.
public void EnableRuntimePermissionToAccessCamera(){
if (ActivityCompat.shouldShowRequestPermissionRationale(EventActivity.this,
Manifest.permission.CAMERA))
{
// Printing toast message after enabling runtime permission.
Toast.makeText(EventActivity.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(EventActivity.this,new String[]{Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
// Upload captured image online on server function.
public void ImageUploadToServerFunction(){
ByteArrayOutputStream byteArrayOutputStreamObject ;
byteArrayOutputStreamObject = new ByteArrayOutputStream();
// Converting bitmap image to jpeg format, so by default image will upload in jpeg format.
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject);
byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);
class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog at image upload time.
progressDialog = ProgressDialog.show(EventActivity.this,"Image is Uploading","Please Wait",
false,false);
}
#Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
// Dismiss the progress dialog after done uploading.
progressDialog.dismiss();
// Printing uploading success message coming from server on android app.
Toast.makeText(EventActivity.this,string1,Toast.LENGTH_LONG).show();
// Setting image as transparent after done uploading.
ImageViewHolder.setImageResource(android.R.color.transparent);
}
#Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String,String> HashMapParams = new HashMap<String,String>();
HashMapParams.put(ImageNameFieldOnServer, GetImageNameFromEditText);
HashMapParams.put(ImageDescOnServer, GetImageDescFromEditText);
HashMapParams.put(ImagePathFieldOnServer, ConvertImage);
String FinalData = imageProcessClass.ImageHttpRequest(ImageUploadPathOnSever, HashMapParams);
return FinalData;
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
public void goBack(View view) {
Intent intent = new Intent(this, IncidentMenuActivity.class);
startActivity(intent);
}
public class ImageProcessClass{
public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url;
HttpURLConnection httpURLConnectionObject ;
OutputStream OutPutStream;
BufferedWriter bufferedWriterObject ;
BufferedReader bufferedReaderObject ;
int RC ;
url = new URL(requestURL);
httpURLConnectionObject = (HttpURLConnection) url.openConnection();
httpURLConnectionObject.setReadTimeout(19000);
httpURLConnectionObject.setConnectTimeout(19000);
httpURLConnectionObject.setRequestMethod("POST");
httpURLConnectionObject.setDoInput(true);
httpURLConnectionObject.setDoOutput(true);
OutPutStream = httpURLConnectionObject.getOutputStream();
bufferedWriterObject = new BufferedWriter(
new OutputStreamWriter(OutPutStream, "UTF-8"));
bufferedWriterObject.write(bufferedWriterDataFN(PData));
bufferedWriterObject.flush();
bufferedWriterObject.close();
OutPutStream.close();
RC = httpURLConnectionObject.getResponseCode();
if (RC == HttpsURLConnection.HTTP_OK) {
bufferedReaderObject = new BufferedReader(new InputStreamReader(httpURLConnectionObject.getInputStream()));
stringBuilder = new StringBuilder();
String RC2;
while ((RC2 = bufferedReaderObject.readLine()) != null){
stringBuilder.append(RC2);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {
StringBuilder stringBuilderObject;
stringBuilderObject = new StringBuilder();
for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {
if (check)
check = false;
else
stringBuilderObject.append("&");
stringBuilderObject.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));
stringBuilderObject.append("=");
stringBuilderObject.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
}
return stringBuilderObject.toString();
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(EventActivity.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(EventActivity.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
}
Is there something I am doing wrong that might of caused it? I have made some research online and this is the same method most of them used.
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