Upload Image from gallery to server in android - android

I am creating an android app. I need to implement a code for uploading profile pic either from gallery or from by capturing from camera.An alert will be shown on clicking the part where picture to be uploaded. It consists of three options One to capture from camera,One to take from gallery,One to cancel.I can successfully
image captured from camera buy when I try to upload Image from gallery i got this error
E/MainActivity: Response from server: java.io.FileNotFoundException: /storage/emulated/0/Pictures/Upload/IMG_20170227_142713.jpg (No such file or directory)
This is the code I used to for alert builder to show options and also to open image gallery or to launch camera
//code to choose profile pic
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*Toast.makeText(getApplicationContext(),
"Please choose a photo", Toast.LENGTH_LONG)
.show();*/
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(LeftMenusMediaActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
//define the file-name to save photo taken by Camera activity
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
} else if (items[item].equals("Choose from Library")) {
try {
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gintent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
});
This is my onActivity result function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
selectedImageUri = null;
String filePath = null;
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
selectedImageUri = data.getData();
// getPath(selectedImageUri);
launchUploadActivity(true);
Toast.makeText(this, selectedImageUri.toString(), Toast.LENGTH_SHORT).show();
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = imageUri;
launchUploadActivity(true);
/*Bitmap mPic = (Bitmap) data.getExtras().get("data");
selectedImageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mPic, getResources().getString(R.string.app_name), Long.toString(System.currentTimeMillis())));*/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
This is my function to launch upload activity
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(LeftMenusMediaActivity.this, UploadActivity.class);
i.putExtra("filePath", selectedImageUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
This the my Upload activity class
public class UploadActivity extends Activity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
private String filePath = null;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Changing action bar background color
/* getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor(getResources().getString(
R.color.action_bar))));*/
// Receiving the data from previous activity
Intent i = getIntent();
// image or video path that is captured in previous activity
filePath = i.getStringExtra("filePath");
// boolean flag to identify the media type, image or video
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image or video on the screen
//previewMedia(isImage);
new UploadFileToServer().execute();
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
}
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
// progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConfig.URL_PHOTO);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
;
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
/**
* Method to show alert dialog
* */
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
What are the changes needed to make upload from gallery working

My app is working now. I made following changes to my code.
On activity result part
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
selectedImageUri = null;
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
launchUploadActivity2(true);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
iv.setImageBitmap(bitmap);
Toast.makeText(this, selectedImageUri.toString(), Toast.LENGTH_SHORT).show();
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = imageUri;
imagepath2=selectedImageUri.getPath();
launchUploadActivity(true);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath2);
iv.setImageBitmap(bitmap);
Log.d(TAG,selectedImageUri.toString());
Toast.makeText(this, selectedImageUri.toString(), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
I made two separate functions for launching upload activity.
Function for launching upload activity class for uploading image from gallery to server is this
private void launchUploadActivity2(boolean isImage){
filePath=imagepath;
if (filePath != null) {
// Displaying the image or video on the screen
//previewMedia(isImage);
new UploadImageToServer1().execute();
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
}
Function for uploading activity class for uploading image by capturing to server
private void launchUploadActivity(boolean isImage){
filePath=selectedImageUri.getPath();
if (filePath != null) {
// Displaying the image or video on the screen
//previewMedia(isImage);
new UploadImageToServer().execute();
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
}
Upload activity class
private class UploadImageToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
// progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConfig.URL_PHOTO);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
;
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("userid",
new StringBody(session.getuid()));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
super.onPostExecute(result);
}
}
This is the function to create path to a particular folder while capturing image
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
AppConfig.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ AppConfig.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
Now I can upload from both gallery and camera

Please check the permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope this helps.:)

this blog and this repo will be help to you
https://onurgurbuz.github.io/android-ftp-server-kullanimi
https://github.com/onurgurbuz/AndroFTP

OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("SessionId", "")
.addFormDataPart("UserDeviceGuid", "")
.addFormDataPart("UserPhoto", "photo.png", RequestBody.create(MEDIA_TYPE_PNG, new File(path)))
.build();
serverURL = serverURL + "/FileUpload/UserPhotoUpload";
Request request = new Request.Builder().url(serverURL).post(requestBody).build();
try {
Response response = client.newCall(request).execute();
String strResponse = response.body().string();
Log.d("upload image", "Response" + strResponse);
if (!response.isSuccessful()) {
} else {
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(strResponse);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonResponse != null && jsonResponse.has("Success") && jsonResponse.getBoolean("Success")) {
isSuccess = true;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
to get retrofit object
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
Interface
#GET("/photos")
Call<List> getAllPhotos();
get galary image path
private Context context;
/* Get uri related content real local file path. */
public String getUriRealPath(Context ctx, Uri uri, int type) {
this.context = ctx;
String ret = "";
if (isAboveKitKat()) {
// Android OS above sdk version 19.
ret = getUriRealPathAboveKitkat(ctx, uri, type);
} else {
// Android OS below sdk version 19
ret = getImageRealPath(context.getContentResolver(), uri, null);
}
return ret;
}
public Uri getImageUri(Context context, Bitmap bitmap) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, "img", null);
return Uri.parse(path);
} catch (IllegalArgumentException e) {
} catch (Exception e) {
}
return null;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private String getUriRealPathAboveKitkat(Context ctx, Uri uri, int type) {
String ret = "";
if (ctx != null && uri != null) {
if (type == 1) {
if (isFileUri(uri)) {
ret = uri.getPath();
} else if (isDocumentUri(ctx, uri)) {
ret = getPath(uri);
} else if (isGooglePhotoDoc(uri.getAuthority())) {
ret = uri.getLastPathSegment();
} else if (uri.toString().startsWith("content://com.google.android.apps.photos.contentprovider")){
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri); // context needed
File photoFile = createTemporalFileFrom(inputStream);
ret = photoFile.getPath();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (isContentUri(uri)) {
if (isGooglePhotoDoc(uri.getAuthority())) {
ret = uri.getLastPathSegment();
} else if (uri.toString().startsWith("content://com.google.android.apps.photos.contentprovider")){
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri); // context needed
File photoFile = createTemporalFileFrom(inputStream);
ret = photoFile.getPath();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (uri.toString().startsWith("content://com.google.android.apps.photos.content")){
try {
InputStream is = context.getContentResolver().openInputStream(uri);
if (is != null) {
Bitmap pictureBitmap = BitmapFactory.decodeStream(is);
ret = getImageUri(context, pictureBitmap).toString();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
ret = getImageRealPath(context.getContentResolver(), uri, null);
}
} else if (isFileUri(uri)) {
ret = uri.getPath();
} else if (isDocumentUri(ctx, uri)) {
ret = getPath(uri);
}
}
return ret;
}
private File createTemporalFileFrom(InputStream inputStream) throws IOException {
File targetFile = null;
if (inputStream != null) {
int read;
byte[] buffer = new byte[8 * 1024];
targetFile = createTemporalFile();
OutputStream outputStream = new FileOutputStream(targetFile);
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
outputStream.flush();
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return targetFile;
}
private File createTemporalFile() {
return new File(context.getExternalCacheDir(), "tempFile.jpg"); // context needed
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private String getPath(Uri uri) {
String ret = "";
// Get uri related document id.
String documentId = DocumentsContract.getDocumentId(uri);
// Get uri authority.
String uriAuthority = uri.getAuthority();
if (isMediaDoc(uriAuthority)) {
String idArr[] = documentId.split(":");
if (idArr.length == 2) {
// First item is document type.
String docType = idArr[0];
// Second item is document real id.
String realDocId = idArr[1];
// Get content uri by document type.
Uri mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
if ("image".equals(docType)) {
mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(docType)) {
mediaContentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(docType)) {
mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
// Get where clause with real document id.
String whereClause = MediaStore.Images.Media._ID + " = " + realDocId;
ret = getImageRealPath(context.getContentResolver(), mediaContentUri, whereClause);
}
} else if (isDownloadDoc(uriAuthority)) {
// Build download uri.
Uri downloadUri = Uri.parse("content://downloads/public_downloads");
// Append download document id at uri end.
Uri downloadUriAppendId = ContentUris.withAppendedId(downloadUri, Long.valueOf(documentId));
ret = getImageRealPath(context.getContentResolver(), downloadUriAppendId, null);
} else if (isExternalStoreDoc(uriAuthority)) {
String idArr[] = documentId.split(":");
if (idArr.length == 2) {
String type = idArr[0];
String realDocId = idArr[1];
if ("primary".equalsIgnoreCase(type)) {
ret = Environment.getExternalStorageDirectory() + "/" + realDocId;
}
}
}
return ret;
}
/* Check whether current android os version is bigger than kitkat or not. */
private boolean isAboveKitKat() {
boolean ret = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
return ret;
}
/* Check whether this uri represent a document or not. */
#TargetApi(Build.VERSION_CODES.KITKAT)
private boolean isDocumentUri(Context ctx, Uri uri) {
boolean ret = false;
if (ctx != null && uri != null) {
ret = DocumentsContract.isDocumentUri(ctx, uri);
}
return ret;
}
/* Check whether this uri is a content uri or not.
content uri like content://media/external/images/media/1302716
*/
public boolean isContentUri(Uri uri) {
boolean ret = false;
if (uri != null) {
String uriSchema = uri.getScheme();
if ("content".equalsIgnoreCase(uriSchema)) {
ret = true;
}
}
return ret;
}
/* Check whether this uri is a file uri or not.
file uri like file:///storage/41B7-12F1/DCIM/Camera/IMG_20180211_095139.jpg
*/
public boolean isFileUri(Uri uri) {
boolean ret = false;
if (uri != null) {
String uriSchema = uri.getScheme();
if ("file".equalsIgnoreCase(uriSchema)) {
ret = true;
}
}
return ret;
}
/* Check whether this document is provided by ExternalStorageProvider. */
private boolean isExternalStoreDoc(String uriAuthority) {
boolean ret = false;
if ("com.android.externalstorage.documents".equals(uriAuthority)) {
ret = true;
}
return ret;
}
/* Check whether this document is provided by DownloadsProvider. */
private boolean isDownloadDoc(String uriAuthority) {
boolean ret = false;
if ("com.android.providers.downloads.documents".equals(uriAuthority)) {
ret = true;
}
return ret;
}
/* Check whether this document is provided by MediaProvider. */
private boolean isMediaDoc(String uriAuthority) {
boolean ret = false;
if ("com.android.providers.media.documents".equals(uriAuthority)) {
ret = true;
}
return ret;
}
/* Check whether this document is provided by google photos. */
private boolean isGooglePhotoDoc(String uriAuthority) {
boolean ret = false;
if ("com.google.android.apps.photos.content".equals(uriAuthority)) {
ret = true;
}
return ret;
}
/* Return uri represented document file real local path.*/
public String getImageRealPath(ContentResolver contentResolver, Uri uri, String whereClause) {
String ret = "";
// Query the uri with condition.
Cursor cursor = contentResolver.query(uri, null, whereClause, null, null);
if (cursor != null) {
boolean moveToFirst = cursor.moveToFirst();
if (moveToFirst) {
// Get columns name by uri type.
String columnName = MediaStore.Images.Media.DATA;
if (uri == MediaStore.Images.Media.EXTERNAL_CONTENT_URI) {
columnName = MediaStore.Images.Media.DATA;
} else if (uri == MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) {
columnName = MediaStore.Audio.Media.DATA;
} else if (uri == MediaStore.Video.Media.EXTERNAL_CONTENT_URI) {
columnName = MediaStore.Video.Media.DATA;
}
// Get column index.
int imageColumnIndex = cursor.getColumnIndex(columnName);
// Get column value which is the uri related file local path.
ret = cursor.getString(imageColumnIndex);
}
}
if (cursor != null){
cursor.close();
}
return ret;
}

Below code get image from gallery and go to show in image view
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1111:
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri selectedImage = data.getData();
if (selectedImage == null) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String name = "" + System.currentTimeMillis();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, name, null);
selectedImage = Uri.parse(path);
}
if (selectedImage != null) {
adapter.dataList.get(index).setUri(selectedImage);
adapter.notifyDataSetChanged();
gotoUploadImage(selectedImage);
}
}
}
break;
}
}

Below code is to get list from web server
GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
Call<List<RetroPhoto>> call = service.getAllPhotos();
call.enqueue(new Callback<List<RetroPhoto>>() {
#Override
public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {
progressDoalog.dismiss();
generateDataList(response.body());
}
#Override
public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
progressDoalog.dismiss();
Toast.makeText(HomeScreenActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});

Related

How to take picture and send to wamp server

I want to send the data(picture taken to wampserver). How does it work?
public class MainActivity extends Activity {
ImageView picture;
Button button;
static final int CAM_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePicture = (Button) findViewById(R.id.button);
ImageView picture = (ImageView) findViewById(R.id.imageView);
takePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getfile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//startActivityForResult(intent, 0);
startActivityForResult(intent, CAM_REQUEST);
}
});
}
private File getfile()
{
File folder = new File ("localhost:8080/sampleTest.php");
if (!folder.exists())
{
folder.mkdir();
}
File image_file = new File(folder, "cam_image.jpg");
return image_file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
//Bitmap bitmap = (Bitmap)data.getExtras().get("data");
//picture.setImageBitmap(bitmap);
String path = "localhost:8080/sampleTest.php/cam_image.jpg";
picture.setImageDrawable(Drawable.createFromPath(path));
}
}
I expect the output to take a picture. After taking a picture, send the picture to "localhost:8080/sampleTest.php". However, what i am getting is that i am only able to take a picture, I could not send the picture to wampserver.
Call camera app with intent:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
Get the thumbnail returned from the camera:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}}
If you want to get an image with better quality, you need to provide an image saving path to the camera app.
Therefore, add the permissions to AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Improve the intent:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
Intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(intent, 0);
Decode the image file when the result is returned:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
setPic();
}}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);}
Image Transmission from Android Client to Server
Now, we can combine the two functionalities to enhance the Android application.
To access the Internet, add the following permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Refer to this blog, create a class MultipartEntity:
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}}
Use AsyncTask to process the uploading work:
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://192.168.8.84:8003/savetofile.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile",
System.currentTimeMillis() + ".jpg", in);
httppost.setEntity(reqEntity);
Log.i(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null)
Log.i(TAG, "response " + response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, R.string.uploaded, Toast.LENGTH_LONG).show();
}
}

How to work with android camera app using external/internal storage?

I am working on android camera app in which i have to capture selfie image/video and send to the server. I have used intent to open the camera. I have implemented the code at below but this code is working fine for those devices who have external storage but for those devices who have no external storage, app has stooped working at this line of code Environment.getExternalStorageState().
Please give me suggestions how i can complete my scenario?
private static final int PICK_FILE_REQUEST = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private String selectedFilePath;
ImageView bimage, bvideo;
ArrayList imageList;
TextView bimage_gallery, bvideo_gallery;
//ProgressDialog dialog;
PowerManager.WakeLock wakeLock;
String flag_value, thumbnail, email;
private static final String EXTRA_FILENAME = "com.commonsware.android.camcon.EXTRA_FILENAME";
private static final String FILENAME = "CameraContentDemo.jpeg";
private static final int CONTENT_REQUEST = 1337;
private File output = null;
private Uri outputUri = null;
public static final int MEDIA_TYPE_IMAGE = 1;
Uri fileUri;
int dialog_nbr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFrstAttemp();
occupyFullScreen();
setContentView(R.layout.home_screen);
getRefereces();
}
// is this first attemp of user, please first register yourself
public void isFrstAttemp() {
SharedPreferences mSharedPreferences = getSharedPreferences("filter", MODE_PRIVATE);
email = mSharedPreferences.getString("isRegistered", "no");
if (email.equals("no")) {
Intent intent = new Intent(MainActivity.this, SignUp.class);
startActivity(intent);
finish();
}
}
//set full screen
public void occupyFullScreen() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
//get references
public void getRefereces() {
bimage = (ImageView) findViewById(R.id.camera);
bvideo = (ImageView) findViewById(R.id.videos);
bimage_gallery = (TextView) findViewById(R.id.img_gallery);
bvideo_gallery = (TextView) findViewById(R.id.videos_gallery);
bimage.setOnClickListener(this);
bimage_gallery.setOnClickListener(this);
bvideo_gallery.setOnClickListener(this);
bvideo.setOnClickListener(this);
imageList = new ArrayList<>();
}
// Create a file Uri for saving an image or video
private Uri getOutputMediaFileUri(int type) {
if (getOutputMediaFile(type)==null){
dialog_nbr=6;
storageProblem();
return null;
}
else{
Uri path= Uri.fromFile(getOutputMediaFile(type));
return path;
}
}
private File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
else {
return null;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.camera:
imageCapture();
break;
case R.id.videos:
videocapture();
break;
case R.id.img_gallery:
if (haveNetworkConnection()) {
Intent intent = new Intent(MainActivity.this, Gallery_images.class);
startActivity(intent);
} else {
dialog_nbr=1;
openDialog();
}
break;
case R.id.videos_gallery:
if (haveNetworkConnection()) {
Intent intent2 = new Intent(MainActivity.this, Gallery_videos.class);
startActivity(intent2);
} else {
dialog_nbr=1;
openDialog();
}
break;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(EXTRA_FILENAME, output);
}
public void imageCapture() {
flag_value = "1";
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
if (fileUri!=null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CONTENT_REQUEST);
}
}
private void videocapture() {
flag_value = "2";
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
startActivityForResult(intent, PICK_FILE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (haveNetworkConnection()) {
if (requestCode == PICK_FILE_REQUEST) {
if (data == null) {
return;
}
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
wakeLock.acquire();
Uri selectedFileUri = data.getData();
selectedFilePath = FilePath.getPath(this, selectedFileUri);
if (flag_value == "2") {
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(selectedFilePath,
MediaStore.Images.Thumbnails.MICRO_KIND);
flag_value = getStringImage(thumb);
}
Log.i(TAG, "Selected File Path:" + selectedFilePath);
if (selectedFilePath != null) {
new Thread(new Runnable() {
#Override
public void run() {
try {
uploadFile(selectedFilePath);
} catch (OutOfMemoryError e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Insufficient Memory!", Toast.LENGTH_SHORT).show();
}
});
// dialog.dismiss();
}
}
}).start();
} else {
Toast.makeText(MainActivity.this, "Please choose a File First", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CONTENT_REQUEST) {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
wakeLock.acquire();
new Thread(new Runnable() {
#Override
public void run() {
try {
//creating new thread to handle Http Operations
uploadFile(fileUri.getPath());
} catch (OutOfMemoryError e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog_nbr=2;
openDialog();
}
});
}
}
}).start();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Cancelled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
}
}
else {
dialog_nbr=1;
openDialog();
}
}
}
public int uploadFile(final String selectedFilePath) {
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
if (!selectedFile.isFile()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "suurce file does not exist", Toast.LENGTH_SHORT).show();
}
});
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(Constant.SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", selectedFilePath);
dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable, maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
try {
dataOutputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
dialog_nbr=2;
openDialog();
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"email\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(email);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"flag\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(flag_value);
dataOutputStream.writeBytes(lineEnd);
// get server ok responce
try {
serverResponseCode = connection.getResponseCode();
} catch (OutOfMemoryError e) {
dialog_nbr=2;
openDialog();
}
//response code of 200 indicates the server status OK
if (serverResponseCode == 200) {
// imageList.add(selectedFilePath);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
//reading server echo responce
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog_nbr=4;
openDialog();
}
});
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
if (wakeLock.isHeld()) {
wakeLock.release();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "File Not Found", Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "URL Error!", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
return serverResponseCode;
}
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
public void openDialog() {
View dialogView=null;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
if (dialog_nbr==1)
dialogView = inflater.inflate(R.layout.dialog_connection, null);
else if (dialog_nbr==2){
dialogView = inflater.inflate(R.layout.dialog_insufficeint_memory, null);
}
else if (dialog_nbr==3){
dialogView = inflater.inflate(R.layout.dialog_server_error, null);
}
else if (dialog_nbr==4){
dialogView = inflater.inflate(R.layout.dialog_file_uploaded, null);
}
else if (dialog_nbr==5){
dialogView = inflater.inflate(R.layout.dialog_exit, null);
}
dialogBuilder.setView(dialogView);
final AlertDialog findMeDialog = dialogBuilder.create();
findMeDialog.show();
LinearLayout reset_btn = (LinearLayout) dialogView.findViewById(R.id.ok);
reset_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findMeDialog.dismiss();
}
});
}
public void storageProblem(){
View dialogView=null;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
dialogView = inflater.inflate(R.layout.dialog_external_storage_error, null);
dialogBuilder.setView(dialogView);
final AlertDialog findMeDialog = dialogBuilder.create();
findMeDialog.show();
LinearLayout reset_btn = (LinearLayout) dialogView.findViewById(R.id.ok);
reset_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findMeDialog.dismiss();
System.exit(0);
}
});
}
#Override
public void onBackPressed() {
dialog_nbr=3;
View dialogView=null;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
dialogView = inflater.inflate(R.layout.dialog_exit, null);
dialogBuilder.setView(dialogView);
final AlertDialog findMeDialog = dialogBuilder.create();
findMeDialog.show();
TextView cancel_btn = (TextView) dialogView.findViewById(R.id.cancel);
TextView exit_btn = (TextView) dialogView.findViewById(R.id.exit);
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findMeDialog.dismiss();
}
});
exit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findMeDialog.dismiss();
finish();
}
});
}
}
This code is working fine on my device but App is crashing when my client is testing on huawei p9 lite at Environment.getExternalStorageState() it's saying you have not mounted the sd card. please give me a solution how this code will worik fine for those devices who have not external storage

Realm file created with Android in a project is not valid in Another

The realm version is the latest jar I compiled from source (github).
I am using an Android project to create a realm file from a json file.
In this project all seems well and the realm is fine. Here is the code:
public class MainActivity extends Activity {
private static final String REALM_DB_FILE = "categories.realm";
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(REALM_DB_FILE)
.setModules(new CurrencyModule())
.build();
Realm realm = Realm.getInstance(realmConfiguration);
RealmResults<RLMCategory> r = realm.where(RLMCategory.class).findAll();
if(r != null && r.size()> 0){
Log.d(TAG, "items : "+r.size());
realm.beginTransaction();
r.clear();
realm.commitTransaction();
Log.d(TAG, "items : " + r.size());
}
String json = getJsonStringFromRawFile(this, R.raw.categories);
try {
JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("results");
for(int i = 0; i<arr.length(); i++){
realm.beginTransaction();
RLMCategory category = createFromJson((JSONObject) arr.get(i), i);
RLMCategory categoryRLM = realm.copyToRealm(category);
realm.commitTransaction();
}
} catch (JSONException e) {
Log.e(TAG, "onCreate");
}
String path = realm.getPath();
Log.d(TAG, "insert finished : path "+path);
r = realm.where(RLMCategory.class).findAll();
Log.d(TAG, "items : "+r.size());
for (RLMCategory category : r){
Log.d(TAG, toString(category));
}
realm.close();
sendDatabaseByEmail();
}
public void sendDatabaseByEmail() {
// init realm
// Realm realm = Realm.getInstance(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(REALM_DB_FILE)
.setModules(new CurrencyModule())
.build();
Realm realm = Realm.getInstance(realmConfiguration);
File exportRealmFile = null;
try {
// get or create an "export.realm" file
exportRealmFile = new File(getExternalCacheDir(), REALM_DB_FILE);
// if "export.realm" already exists, delete
exportRealmFile.delete();
// copy current realm to "export.realm"
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
realm.close();
// init email intent and add export.realm as attachment
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, "valeria#letgo.com");
intent.putExtra(Intent.EXTRA_SUBJECT, REALM_DB_FILE +" database");
intent.putExtra(Intent.EXTRA_TEXT, "datatabse");
Uri u = Uri.fromFile(exportRealmFile);
intent.putExtra(Intent.EXTRA_STREAM, u);
// start email intent
startActivity(Intent.createChooser(intent, "Send database"));
}
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public String toString(RLMCategory rlmCategory) {
return "RLMCategory{" +
"id=" + rlmCategory.getId() +
", name='" + rlmCategory.getName() + '\'' +
", description='" + rlmCategory.getDescription() + '\'' +
", image_src='" + rlmCategory.getImage_src() + '\'' +
", category_id=" + rlmCategory.getCategory_id() +
", name_dirify='" + rlmCategory.getName_dirify() + '\'' +
", objectId='" + rlmCategory.getObjectId() + '\'' +
'}';
}
#Nullable
public static String getJsonStringFromRawFile(Context context, int resId) {
InputStream is = context.getResources().openRawResource(resId);
return getJsonStringFromIS(is);
}
private static String getJsonStringFromIS(InputStream inputStream){
String jsonStr = null;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
if (inputStream == null) {
// Nothing to do.
jsonStr = null;
} else {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
jsonStr = null;
} else {
jsonStr = buffer.toString();
}
} catch (IOException e) {
Log.e(TAG, "getJsonStringFromIS", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}
return jsonStr;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static RLMCategory createFromJson(JSONObject obj, int id){
RLMCategory category = null;
try {
category = new RLMCategory();
category.setName(obj.getString("name"));
category.setId(id);
category.setCategory_id(obj.getInt("category_id"));
category.setDescription(obj.getString("description"));
category.setName_dirify(obj.getString("name_dirify"));
category.setImage_src(obj.getString("image"));
category.setObjectId(obj.getString("description"));
} catch (JSONException e) {
Log.e(TAG, "createFromJson : " +obj, e );
}
return category;
}
#RealmModule(classes = {RLMCategory.class})
public class CurrencyModule {
}
}
On my other project I am adding the categories.realm to raw folder and then I am copying it to a normal folder:
Utils.copyRealmDb(context, REALM_DB_FILE, CATEGORIES_RES);
RealmConfiguration realmConfiguration2 = new RealmConfiguration.Builder(context)
.name(REALM_DB_FILE)
.setModules(new CategoryModule())
.build();
this.realm = Realm.getInstance(realmConfiguration2); //crash here
}
public static void copyRealmDb(Context context, String realmDbFile, #RawRes int rarResFile) {
File f = context.getFilesDir();
File targetFile = new File(f, realmDbFile);
if(targetFile.exists()){
targetFile.delete();
}
if(!targetFile.exists()){
InputStream is = context.getResources().openRawResource(rarResFile);
FileOutputStream os = null;
try {
os = new FileOutputStream(targetFile);
copyStream(is, os);
} catch (FileNotFoundException e) {
Timber.e(e, "Unable to copy database from raw");
} finally {
try {
if(is != null){
is.close();
}
} catch (IOException e) {
Timber.e(e, "Unable to close inputStream");
}
try {
if(os != null){
os.close();
}
} catch (IOException e) {
Timber.e(e, "Unable to close outputStream");
}
}
}
}
I get a crash on trying to get the instance of the database and the error I get is:
Caused by: java.lang.IllegalArgumentException: Illegal Argument: Invalid format of Realm file.
at io.realm.internal.SharedGroup.createNativeWithImplicitTransactions(Native Method)
at io.realm.internal.SharedGroup.<init>(SharedGroup.java:60)
at io.realm.Realm.<init>(Realm.java:189)
at io.realm.Realm.createAndValidate(Realm.java:557)
at io.realm.Realm.create(Realm.java:525)
at io.realm.Realm.getInstance(Realm.java:498)
I have no idea how to fix it. Any ideas? Thks
EDIT: I am able to open the created realm file with a Mac and it seems fine.
EDIT 2: Here is the missing method:
public static void copyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}

Best method to download image from url in Android

I'm using below method to download single image from url
public static Bitmap getBitmap(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap d = BitmapFactory.decodeStream(is);
is.close();
return d;
} catch (Exception e) {
return null;
}
}
Sometimes I get an outofmemory exception.
I am unable to catch outofmemory exception. The app will close. How to prevent this?
Is there a better method for downloading images that is also faster?
public void DownloadImageFromPath(String path){
InputStream in =null;
Bitmap bmp=null;
ImageView iv = (ImageView)findViewById(R.id.img1);
int responseCode = -1;
try{
URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
iv.setImageBitmap(bmp);
}
}
catch(Exception ex){
Log.e("Exception",ex.toString());
}
}
Step 1: Declaring Permission in Android Manifest
First thing to do in your first Android Project is you declare required permissions in your ‘AndroidManifest.xml’ file.
For Android Download Image from URL, we need permission to access the internet to download file and read and write internal storage to save image to internal storage.
Add following lines of code at the top of tag of AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Step 2: Request required permission from user
Android allows every app to run in a sandbox. If an app needs to access certain resources or information outside that sandbox, it needs to request permission from user.
From Android 6.0 onward, Google wants developers to request permission from user from within the app, for more details on permissions read this.
Therefore for Android Download Image from URL, you’ll need to request Read Storage and Write
For this, we will use the following lines of code to first check if the required permission is already granted by the user, if not then we will request permission for storage read and write permission.
We’re creating a method ‘Downlaod Image’, you can simple call this wherever you need to download the image.
void DownloadImage(String ImageUrl) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
showToast("Need Permission to access storage for Downloading Image");
} else {
showToast("Downloading Image...");
//Asynctask to create a thread to downlaod image in the background
new DownloadsImage().execute(ImageUrl);
}
}
Now that we have requested and been granted the user permission, to start with android download image from url, we will create an AsyncTask, as you are not allowed to run a background process in the main thread.
class DownloadsImage extends AsyncTask<String, Void,Void>{
#Override
protected Void doInBackground(String... strings) {
URL url = null;
try {
url = new URL(strings[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Bitmap bm = null;
try {
bm = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
//Create Path to save Image
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+ "/AndroidDvlpr"); //Creates app specific folder
if(!path.exists()) {
path.mkdirs();
}
File imageFile = new File(path, String.valueOf(System.currentTimeMillis())+".png"); // Imagename.png
FileOutputStream out = null;
try {
out = new FileOutputStream(imageFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(MainActivity.this,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// Log.i("ExternalStorage", "Scanned " + path + ":");
// Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
showToast("Image Saved!");
}
}
In the above give lines of code, a URL and Bitmap is created, using BitmapFactory.decodeStream, file is downloaded.
The File path is created to save the image (We have created a folder named ‘AndroidDvlpr’ in DIRECTORY_PICTURES) and download is initialized.
After downloading the file MediaScannerConnection, is called to read metadata from the file and add the file to the media content provider so the image is available for the user.
In the above lines of code, we have also created a method, showToast() to show Toast. complete code here:
void showToast(String msg){
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
Read more here
Add This Dependency For Android Networking Into Your Project
compile 'com.amitshekhar.android:android-networking:1.0.0'
String url = "http://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/11136/production/_95324996_defoe_rex.jpg";
File file;
String dirPath, fileName;
Button downldImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization Of DownLoad Button
downldImg = (Button) findViewById(R.id.DownloadButton);
// Initialization Of DownLoad Button
AndroidNetworking.initialize(getApplicationContext());
//Folder Creating Into Phone Storage
dirPath = Environment.getExternalStorageDirectory() + "/Image";
fileName = "image.jpeg";
//file Creating With Folder & Fle Name
file = new File(dirPath, fileName);
//Click Listener For DownLoad Button
downldImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AndroidNetworking.download(url, dirPath, fileName)
.build()
.startDownload(new DownloadListener() {
#Override
public void onDownloadComplete() {
Toast.makeText(MainActivity.this, "DownLoad Complete", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(ANError anError) {
}
});
}
});
}
}
After Run This Code
Check Your Phone Memory
You Can See There A Folder - Image
Check Inside This Folder , You see There a Image File with name of "image.jpeg"
Thank You !!!
You can download image by Asyn task
use this class:
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private final MemoryCache memoryCache;
private final BrandItem brandCatogiriesItem;
private Context context;
private String url;
public ImageDownloaderTask(ImageView imageView, String url, Context context) {
imageViewReference = new WeakReference<ImageView>(imageView);
memoryCache = new MemoryCache();
brandCatogiriesItem = new BrandItem();
this.url = url;
this.context = context;
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
memoryCache.put("1", bitmap);
brandCatogiriesItem.setUrl(url);
brandCatogiriesItem.setThumb(bitmap);
// BrandCatogiriesItem.saveLocalBrandOrCatogiries(context, brandCatogiriesItem);
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.placeholder);
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
And call this like:
new ImageDownloaderTask(thumbImage, item.thumbnail, context).execute(item.thumbnail);
I recommend using the altex-image-downloader library, which makes it easy to download images:
AltexImageDownloader.writeToDisk(context, Imageurl, "IMAGES");
Add dependency in app build gradle:
implementation 'com.artjimlop:altex-image-downloader:0.0.4'
The OOM exception could be avoided by following the official guide to load large bitmap.
Don't run your code on the UI Thread. Use AsyncTask instead and you should be fine.
you can use below function to download image from url.
private Bitmap getImage(String imageUrl, int desiredWidth, int desiredHeight)
{
private Bitmap image = null;
int inSampleSize = 0;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = inSampleSize;
try
{
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream stream = connection.getInputStream();
image = BitmapFactory.decodeStream(stream, null, options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
if(imageWidth > desiredWidth || imageHeight > desiredHeight)
{
System.out.println("imageWidth:"+imageWidth+", imageHeight:"+imageHeight);
inSampleSize = inSampleSize + 2;
getImage(imageUrl);
}
else
{
options.inJustDecodeBounds = false;
connection = (HttpURLConnection)url.openConnection();
stream = connection.getInputStream();
image = BitmapFactory.decodeStream(stream, null, options);
return image;
}
}
catch(Exception e)
{
Log.e("getImage", e.toString());
}
return image;
}
See complete explanation here
public class testCrop extends AppCompatActivity {
ImageView iv;
String imagePath = "https://style.pk/wp-content/uploads/2015/07/omer-Shahzad-performed-umrah-600x548.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testcrpop);
iv = (ImageView) findViewById(R.id.testCrop);
imageDownload image = new imageDownload(testCrop.this, iv);
image.execute(imagePath);
}
class imageDownload extends AsyncTask<String, Integer, Bitmap> {
Context context;
ImageView imageView;
Bitmap bitmap;
InputStream in = null;
int responseCode = -1;
//constructor.
public imageDownload(Context context, ImageView imageView) {
this.context = context;
this.imageView = imageView;
}
#Override
protected void onPreExecute() {
}
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap data) {
imageView.setImageBitmap(data);
}
}
}
OUTPUT
I'm still learning Android, so I cannot provide a rich context or reason for my suggestion, but this is what I am using to retrive files from both https and local urls. I am using this in my onActivity result (for both taking pictures and selecting from gallery), as well in an AsyncTask to retrieve the https urls.
InputStream input = new URL("your_url_string").openStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
First Declare Permission in Android Manifest:-
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MainActivityForDownloadImages.java
public class MainActivityForDownloadImages extends AppCompatActivity {
// String urls = "https://stimg.cardekho.com/images/carexteriorimages/930x620/Kia/Kia-Seltos/6232/1562746799300/front-left-side-47.jpg";
String urls = "https://images5.alphacoders.com/609/609173.jpg";
Button button;
public final Context context = this;
ProgressDialog progressDialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_for_download_images);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
progressDialog = new ProgressDialog(context);
button = findViewById(R.id.downloadImagebtn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// initialize the progress dialog like in the first example
// this is how you fire the downloader
Intent intent = new Intent(context, DownloadService.class);
intent.putExtra("url", urls);
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
}
}
}
private class DownloadReceiver extends ResultReceiver {
public DownloadReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
progressDialog.setProgress(progress);
progressDialog.setMessage("Images Is Downloading");
progressDialog.show();
if (progress == 100) {
progressDialog.dismiss();
}
}
}
}
}
DownloadService.java
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
String folder_main = "ImagesFolder";
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
//create url and connect
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
inerDire.createNewFile();
FileOutputStream output = new FileOutputStream(inerDire);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress", (int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
// close streams
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
Try this code to download an image from a URL on Android:
DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
You can use this function to save your bitmap/image in gallery for all android version including Android 11
private fun addImageToGallery(fileName: String, bitmap: Bitmap, ctx: Context) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val fos: OutputStream
val resolver = contentResolver
val values = ContentValues()
values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
values.put(
MediaStore.MediaColumns.RELATIVE_PATH,
Environment.DIRECTORY_PICTURES + File.separator + "EduImages"
)
val imageUri = resolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
fos = resolver.openOutputStream(imageUri!!) as OutputStream
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
fos.close()
Toast.makeText(
ctx, "Saved in gallery",
Toast.LENGTH_SHORT
).show()
} else {
val values = ContentValues()
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.ImageColumns.TITLE, fileName)
val uri: Uri? = ctx.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
uri?.let {
ctx.contentResolver.openOutputStream(uri)?.let { stream ->
val oStream =
BufferedOutputStream(stream)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
oStream.close()
Toast.makeText(ctx, "Saved in gallery", Toast.LENGTH_SHORT)
.show()
}
}
}
} catch (e: Exception) {
Toast.makeText(ctx, e.localizedMessage, Toast.LENGTH_SHORT).show()
}
}

How Can we integrate Sphinx speech recognition for android?

I am developing speech recognition for Java Application Using Sphinx 4. I want speech recognition for ANDroid. Please Help Me :)
//declearation
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
TextToSpeech talker;
//onCreate
Button speakButton=new Button(this);
talker = new TextToSpeech(this, this);
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startVoiceRecognitionActivity();
}
});
} else {
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
//methods
/**
* Fire an intent to start the speech recognition activity.
*/
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
String device = "Bedroom";
String host = "http://web2.anzleads.com/Android/nimboPani/web-service.php?tmote=";
String userCommand = URLEncoder.encode(matches.get(0));
String deviceSelected = "&org=" + device;
res = getServerResponse(host + userCommand + deviceSelected);
say(""+ res);
}
super.onActivityResult(requestCode, resultCode, data);
}
public void say(String text2say){
talker.speak(text2say, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status) {
// TODO Auto-generated method stub
// say("Hello World");
}
public void onDestroy() {
if (talker != null) {
talker.stop();
talker.shutdown();
}
super.onDestroy();
}
public String getServerResponse(String url)
{
String result = "";
HttpClient hc = new DefaultHttpClient();
HttpResponse hr ;
HttpGet hg = new HttpGet(url);
try
{
hr = hc.execute(hg);
if(hr.getStatusLine().getStatusCode() == 200)
{
HttpEntity he = hr.getEntity();
if (he != null)
{
InputStream is = he.getContent();
result = convertStreamToString(is);
is.close();
}
}
}
catch (Exception e) {
// TODO: handle exception
}
return result;
}
private String convertStreamToString(InputStream instream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

Categories

Resources