This is the error that I'm getting everytime I press the upload button after selecting an image from the device
I/System.out:e:java.lang.ClassNotFoundException:com.mediatek.cta.CtaHttp
W/System: ClassLoader referenced unknown path:system/framework/mediatek-cta.jar
While trying to upload an image with a text parameter from the app to SQL database.
MainAtivity.java
package com.example.veekalp.imageupload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}
}
}
Related
I have 2 activity, Tambah and Tampil activity.
I use Tambah activity to add new data (form and button submit), and after submit, it will move to Tampil activity. in Tampil activity will show the list view of data (i'm using Volley). all script works, no error. but in Tampil activity only showing old data (like before add), not showing the newest data.
here my Tambah acitivity
package com.example.arif.upload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class Tambah extends AppCompatActivity implements View.OnClickListener{
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Konfigurasi.url_tambah_tentor)
.addFileToUpload(path, "foto") //Adding file
.addParameter("nama", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
Intent move = new Intent(getApplicationContext(),Tampil.class);
startActivity(move);
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}
}
}
and here Tampil activity
package com.example.arif.upload;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Tampil extends AppCompatActivity {
ListView list_tentor;
ArrayList<String>nama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tampil);
list_tentor = (ListView)findViewById(R.id.list_tentor);
nama = new ArrayList<String>();
list_tentor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent pindah = new Intent(Tampil.this,Tambah.class);
pindah.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(pindah);
finish();
}
});
RequestQueue req = Volley.newRequestQueue(getApplicationContext());
StringRequest sr = new StringRequest(Request.Method.GET, Konfigurasi.url_tampil_tentor, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
JSONArray tentor = jo.getJSONArray("tentor");
for (int i = 0; i < tentor.length(); i++){
JSONObject pertentor = tentor.getJSONObject(i);
nama.add(pertentor.getString("nama"));
}
Tampiladapter ta = new Tampiladapter(getApplicationContext(),nama);
list_tentor.setAdapter(ta);
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
req.add(sr);
}
}
how can when Intent from Tambah activity to Tampil activity, the Tampil activity reload all data include newest data)?
It seems that you are not waiting until data is uploaded and redirecting to next screen.
Try this answer
Implementing ProgressDialog in Multipart Upload Request
onCompleted redirect to next screen
I am developing an android mobile application in which i am trying to upload the picture on server from android app. The .php files are working fine but the java code is not working and showing error that path is null. I have tried the several types of code but not working at all. Please help.
Thank you
Here is the code.
package com.example.pt_connect.attachmentuploadingandgetting;
import android.Manifest;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
**public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(MainActivity.this,filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}**
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}Error
}
}
You have to get the file path like below
String FilePath = data.getData().getPath();
String FileName = data.getData().getLastPathSegment();
on the onActivityResult. I made change to your code. Check below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
filePath = data.getData().getPath();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think it will work. If not comment here, we will go for another method
This is my MainActivity file. I am trying to select an Image file from external storage and upload it to server with percentage progress.
I want to add ProgressDialog to it , i attempted to add but it throwing run time error.
package com.example.panchayat.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.Manifest;
import android.util.Log;
import android.widget.Toast;
import android.content.pm.PackageManager;
import android.content.Intent;
import android.net.Uri;
import java.io.File;
import java.io.IOException;
import android.database.Cursor;
import android.provider.MediaStore;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.OkHttpClient;
import okhttp3.Callback;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import android.os.Handler;
import android.app.ProgressDialog;
import com.example.panchayat.myapplication.CountingFileRequestBody;
import com.example.panchayat.myapplication.CountingFileRequestBody.ProgressListener;
import com.example.panchayat.myapplication.ProgressRequestBody.Listener;
import com.example.panchayat.myapplication.ProgressRequestBody;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
//finishAffinity();
//System.exit(0);
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == 1) {
if (data != null) {
Uri uri = data.getData();
File myFile = new File(getRealPathFromURI(uri));
final OkHttpClient client = new OkHttpClient();
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png", RequestBody.create(MEDIA_TYPE_PNG, myFile))
.build();
//CountingFileRequestBody ok = new CountingFileRequestBody(requestBody, "image/jpg",progressListener);
ProgressRequestBody ioo = new ProgressRequestBody(requestBody,progressListener);
Toast.makeText(MainActivity.this, myFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
Request request = new Request.Builder()
.url("http://bmi.ir/multi.php")
.post(ioo)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d("ok",e.getMessage());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("ok",response.body().string());
//Toast.makeText(MainActivity.this, response.body().string(), Toast.LENGTH_SHORT).show();
}
}
);
}
}
}
final Listener progressListener = new Listener() {
#Override public void onProgress(int bytesRead) {
//Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
final String myString = Long.toString(bytesRead);
final int per = bytesRead;
Log.d("ok", myString);
}
};
private String getRealPathFromURI(Uri contentURI)
{
String result = null;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null)
{ // Source is Dropbox or other similar local file path
result = contentURI.getPath();
}
else
{
if(cursor.moveToFirst())
{
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
}
cursor.close();
}
return result;
}
}
How to get the progress % from the listener and update the ProgressDialog?
#Override
public void onProgress(int bytesRead) {
//Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
double percentage = 100 * bytesRead/fileLength;
Log.d(TAG,"Progress percentage: " + percentage);
}
I have problem, that I have been searching for whole week. I'm creating app that sends photo and some data to server. The problem is that when I start activity, camera has to start but, for some devices app crashes. I cant describe the error because devices are in other cities. I have LG G3 and HUAWEI P7 on both of them works fine. I think this might be something wrong with permissions but I'm not sure.
package com.fishingtournaments.ZvejysZvejui;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.support.v4.os.EnvironmentCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.Semaphore;
public class SendImageActivity extends AppCompatActivity implements View.OnClickListener {
public static final int CAMERA_PERMISSION_REQUEST_CODE = 8675809;
TextView fish_n, fish_s, points;
public static final int REQUEST_CAPTURE = 1;
public static String path;
public String fish_name, fish_length, fish_points, colleague_id, fish_size, fish_photo, fish_id,
user_id, user_name = "";
//Declaring views
private Button buttonUpload;
private ImageView imageView;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
//Uri to store the image uri
private Uri imageUri; /*, uriSavedImage*/
private File imagesFolder, image;
private String fixedURI;
//----------------------------------//
// Storage for camera image URI components
private final static String CAPTURED_PHOTO_PATH_KEY = "mCurrentPhotoPath";
private final static String CAPTURED_PHOTO_URI_KEY = "uriSavedImage";
// Required for camera operations in order to save the image file on resume.
private String mCurrentPhotoPath = null;
private Uri uriSavedImage = null;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (mCurrentPhotoPath != null) {
savedInstanceState.putString(CAPTURED_PHOTO_PATH_KEY, mCurrentPhotoPath);
}
if (uriSavedImage != null) {
savedInstanceState.putString(CAPTURED_PHOTO_URI_KEY, uriSavedImage.toString());
}
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(CAPTURED_PHOTO_PATH_KEY)) {
mCurrentPhotoPath = savedInstanceState.getString(CAPTURED_PHOTO_PATH_KEY);
}
if (savedInstanceState.containsKey(CAPTURED_PHOTO_URI_KEY)) {
uriSavedImage = Uri.parse(savedInstanceState.getString(CAPTURED_PHOTO_URI_KEY));
}
super.onRestoreInstanceState(savedInstanceState);
}
//-++-+-+-+-+-+-+-+-+-+-+-+-+---//
#Override
protected void onCreate(Bundle savedInstanceState) {
//Requesting storage permission
//TODO INTERFACE,
//TODO CHECK PERMISSIONS
//TODO TEST ON OTHER PHONES
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
setContentView(R.layout.activity_send_image);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload.setOnClickListener(this);
} else {
setContentView(R.layout.activity_send_image);
if (ContextCompat.checkSelfPermission(SendImageActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imagesFolder = new File(Environment.getExternalStorageDirectory(), "FishingTournament");
image = new File(imagesFolder, "QR_" + timeStamp + ".png");
uriSavedImage = Uri.fromFile(image);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(i, REQUEST_CAPTURE);
} else {
String[] permissionRequest = {Manifest.permission.CAMERA};
ActivityCompat.requestPermissions(SendImageActivity.this, permissionRequest, CAMERA_PERMISSION_REQUEST_CODE);
}
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload.setOnClickListener(this);
}
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", "asd") //Adding text parameter to the request
.addParameter("colleague_id", colleague_id)
.addParameter("fish_length", fish_size)
.addParameter("fish_points", fish_points)
.addParameter("fish_photo", fish_photo)
.addParameter("fish_id", fish_id)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CAPTURE) {
if (data != null) {
fixedURI = String.valueOf(uriSavedImage);
fixedURI = fixedURI.replace("file://", "");
path = fixedURI;
// Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(path);
// imageView.setImageBitmap(bitmap);
} else {
fixedURI = String.valueOf(uriSavedImage);
fixedURI = fixedURI.replace("file://", "");
path = fixedURI;
// Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(path);
// imageView.setImageBitmap(bitmap);
}
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
//Requesting permission
private void requestStorageReadPermission() {
if (ContextCompat.checkSelfPermission(SendImageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(SendImageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
Toast.makeText(SendImageActivity.this, "Norint siųsti nuotrauką reikalingas leidimas prie failų saugyklos", Toast.LENGTH_SHORT).show();
}
//And finally ask for the permission
ActivityCompat.requestPermissions(SendImageActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonUpload) {
uploadMultipart();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
onBackPressed();
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
final String user_name = getIntent().getStringExtra("user_name");
final String colleague_id = getIntent().getStringExtra("colleague_id");
final String user_id = getIntent().getStringExtra("user_id");
Intent intent = new Intent(SendImageActivity.this, ChooseFishActivity.class);
intent.putExtra("colleague_id", colleague_id);
intent.putExtra("user_name", user_name);
intent.putExtra("user_id", user_id);
startActivity(intent);
finish();
}
}
It might look dumb why I have if in onCreate() method, it's because in my LG G3 camera is restarting on taking photo. And thats why my onActivityResult() method looks strange.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fishingtournaments.ZvejysZvejui">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/descicon"
android:label="Žvejys žvejui"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ChooseFishActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ResultActivity"
android:configChanges="orientation"
android:parentActivityName=".ChooseFishActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ShowResultsActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
<activity android:name=".SendImageActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
</application>
</manifest>
P.S. My code might look unclean, sorry for that, I have been doing everything and testing everything to solve that problem.
BTW I'm requesting permission for storage in my LoginActivity and there I'm creating folder for photos.
LoginActivity
package com.fishingtournaments.ZvejysZvejui;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class LoginActivity extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE = 123;
EditText qrCode_edit;
Button check_button;
// Button result_button;
public String colleague_id;
public String colleague_name;
public String user_id, user_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if(ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Užklausa permissionų", Toast.LENGTH_SHORT).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(LoginActivity.this, "Norint siųsti nuotrauką reikalingas leidimas prie failų saugyklos", Toast.LENGTH_SHORT).show();
}
//And finally ask for the permission
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}else{
Toast.makeText(LoginActivity.this, "Teisės suteiktos", Toast.LENGTH_SHORT).show();
}
File direct = new File(Environment.getExternalStorageDirectory()+"/FishingTournament");
if(!direct.exists()) {
if (direct.mkdir())
Toast.makeText(LoginActivity.this, "Direktorija sukurta", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(LoginActivity.this, "Nesukurta direktorija, nes ji jau egzistuoja", Toast.LENGTH_SHORT).show();
}
// it will create two folder in your internal storage first is specifyfoldername and another one inside the mentioned folder which is nestedfoldername
qrCode_edit = (EditText) findViewById(R.id.qrCode_editText);
check_button = (Button) findViewById(R.id.check_button);
// result_button = (Button) findViewById(R.id.results);
//QR Code
final Activity activity = this;
/**
* Button for scanning QR code
*
*/
check_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check_button.setEnabled(false);
String qrCode = qrCode_edit.getText().toString();
//QR Code
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Užveskite kamerą ant QR kodo");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
check_button.setEnabled(true);
//---
/*Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(LoginActivity.this, ChooseFishActivity.class);
colleague_id = jsonResponse.getString("colleague_id");
colleague_name = jsonResponse.getString("colleague_name");
user_id = jsonResponse.getString("user_id");
intent.putExtra("colleague_id",colleague_id);
intent.putExtra("user_name",colleague_name);
intent.putExtra("user_id",user_id);
startActivity(intent);
// finish();
//startActivity(new Intent(LoginActivity.this, ChooseFishActivity.class));
}else{
String message = jsonResponse.getString("message");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
*//*ats.setText(message);*//*
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(qrCode, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);*/
}
});
/**
* Button for launching ShowResultsActivity
*/
/*result_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, ShowResultsActivity.class);
startActivity(intent);
finish();
}
});*/
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents()==null){
Toast.makeText(this, "Atšaukėte skanavimą", Toast.LENGTH_LONG).show();
}else{
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
/*If correct QR-code*/
if (success){
Intent intent = new Intent(LoginActivity.this, ChooseFishActivity.class);
colleague_id = jsonResponse.getString("colleague_id");
colleague_name = jsonResponse.getString("colleague_name");
user_id = jsonResponse.getString("user_id");
user_name = jsonResponse.getString("user_name");
intent.putExtra("colleague_id",colleague_id);
intent.putExtra("user_name",colleague_name);
intent.putExtra("user_id",user_id);
Toast.makeText(getApplicationContext(),"Sveiki, " + user_name,Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}else{
String message = jsonResponse.getString("message");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(result.getContents(), responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
So I figured out where the problem was.
The error was exposed beyond app through ClipData.Item.getUri() . Basicly the problem was in this line i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);. After searching for this error I found solution in this post
I am working on a simple blog app that allows the user to upload photo from phone gallery and descriptions to the Firebase Server. I am trying to modify my current project to allow the user to capture photo from camera and uploading it to the firebase server.
Currently, I am able to display the image that i have captured into imagebutton, however i am unable to post my image to the firebase server (The "submit post" button does not react to my onclick function).
I am suspecting there is some error in my startPosting() function or i did not encode the image correctly? Please help.
package simpleblog2.emily.example.com.simpleblog2;
import android.app.ProgressDialog;
import android.content.ContentProvider;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import java.io.File;
public class PostActivity extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostTitle;
private EditText mPostDesc;
private Button mSubmitBtn;
private ProgressDialog mProgress;
private DatabaseReference mDatabase;
private Uri mImageUri = null;
private static final int GALLERY_REQUEST = 1;
private static final int CAMERA_REQUEST_CODE = 1;
private StorageReference mStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_REQUEST_CODE);
intent1.setType("image/*");
/*
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
*/
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting() {
mProgress.setMessage("Posting to blog...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
/* mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
*/
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
mSelectImage.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
I have found a solution to my question, i realized that i can get my captured data using the function of data.getData() instead of using the Bitmap function:
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
Also, Previously i did not realized that my 'crop' function could not work because i am missing of:
mImageUri = resultUri;
I realized that there is an issue that if i did not crop my captured image, the fire-base could not handle the high resolution (Or storage size? and it will be loading very slow/image did not appear), This can be resolve by the 'cropping' function.
The final code is stated below:
Thanks all for your help.
package simpleblog2.emily.example.com.simpleblog2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
public class PostActivity extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostTitle;
private EditText mPostDesc;
private Button mSubmitBtn;
private ProgressDialog mProgress;
private DatabaseReference mDatabase;
private Uri mImageUri = null;
private static final int GALLERY_REQUEST =1;
private static final int CAMERA_REQUEST_CODE=1;
private StorageReference mStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
//startActivityForResult(intent,CAMERA_REQUEST_CODE);
/*
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
*/
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting(){
mProgress.setMessage("Posting to blog...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if(!TextUtils.isEmpty(title_val)&&!TextUtils.isEmpty(desc_val) && mImageUri != null){
mProgress.show();
StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl =taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(PostActivity.this,MainActivity.class));
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
/* Bitmap mImageUri1 = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri1);
Toast.makeText(this, "Image saved to:\n" +
data.getExtras().get("data"), Toast.LENGTH_LONG).show();
*/
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
mSelectImage.setImageURI(resultUri);
mImageUri = resultUri;
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
Before it was if auth != null but I changed it to if true so the if will always evaluate true.
private void uploadFile() {
//if there is a file to upload
if (filePath != null) {
//displaying a progress dialog while upload is going on
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference riversRef = storageReference.child("Blog_Images.jpg");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successfull
//and displaying a success toast
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successfull
//hiding the progress dialog
progressDialog.dismiss();
//and displaying error message
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
//if there is not any file
else {
//you can display an error toast
}
}
Your class field mImageUri is never initialized. You put received bitmap in local field, called the same as the class field.
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
Therefore, the condition is never true.
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null)
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
/* mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
*/
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
}
There is a chance that your URI is null. I assume, this is the problem.
Unless you do it somewhere else?
The image might be loaded because the requestCode = CAMERA_REQUEST_CODE but NOT CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE.
I am going to post below a code I used to do what you ask, but first few things you need to understand.
From android version 7 using Uri.parseFromFile(file) return a error because google want to restrict your access. From now on if you want to get file uri you should use FileProvider
declare permmisions and FileProvider in your manifest:
//File provider declaration in manifest.
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.hadas.yotam.manchworkers.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
//in new xml file define the location you need permmision to, the code below give you permmision for any external file.
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
so now when you upload use the global Uri variable if onActivityResault is successful, here is the code:
if(Build.VERSION.SDK_INT>=24) {
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
Then in your onActivityResult you do check if your photoURI = null, if its true (its null)
use photoURI = data.getData();
//if phone android version greater or equal to Marshmelo
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M){
//check if have permmission to write to external + permmision to camera
if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
//if its have permission then new intent to capture image
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//if android version >= 24 (Android Nugget)
if(Build.VERSION.SDK_INT>=24) {
//create new String to pictures directory and set the file name to current_time.jpg
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
//set GLOBAL variable Uri from the file using FileProvider
photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file1);
//add the file location the intent (the picture will be save to this file)
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
tagIntent = CAPTURE_RESAULT;
//else - dont have permission, request for permission
}else{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},CAPTURE_RESAULT);
}
else -
}else{
// same thing only without FileProvider (FileProvider only required since Nugget)
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
photoURI = Uri.fromFile(file1);
intent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
tagIntent = CAPTURE_RESAULT;
}
//if phone can handle the intent, start the intent for resault.
if(intent.resolveActivity(getPackageManager())!=null) {
startActivityForResult(intent,tagIntent);
}