public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private class AsyncImageLoader extends AsyncTask<String, Void, Bitmap[]> {
Bitmap bitmap[];
protected void onPreExecute() {
pDialog.setMessage(getContext().getResources().getString(R.string.please_wait));
showDialog();
}
#Override
protected Bitmap[] doInBackground(String... params) {
hideDialog();
bitmap = new Bitmap[2];
bitmap[0] = getBitmapFromURL(params[0]);
bitmap[1] = getBitmapFromURL(params[1]);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap[] bm) {
imgCover.setImageBitmap(bm[1]);
bm[1].recycle();
imgProfile.setImageBitmap(bm[0]);
bm[0].recycle();
if (MainActivity.PROFILE_UID.equals(MainActivity.USER_UID))
FragmentDrawer.imgProfileNavDrawer.setImageBitmap(bm[0]); // Sol drawer' da çıkan yuvarlak resmi güncellemek için
}
}
01-10 21:11:14.621 7906-8194/project.com.holobech E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:528)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:600)
at project.com.holobech.activity.ProfileFragment.getBitmapFromURL(ProfileFragment.java:508)
at project.com.holobech.activity.ProfileFragment$AsyncImageLoader.doInBackground(ProfileFragment.java:529)
at project.com.holobech.activity.ProfileFragment$AsyncImageLoader.doInBackground(ProfileFragment.java:516)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
It works perfect for Android 5.0 and higher versions. But when i try with 4.2.2 version, that error occure. How can i fix this problem ?
Thanks in advice
This is very common error once you deal with bitmap. Converting bitmap directly from URL is not a good practice. You should use bitmap BitmapFactory.Options feature provided by android by which you can get the size of the bitmap without even creating a bitmap. Now you have to use insamplesize of BitmapFactory Options and re size the images. I guess the size and the quality of image is too high and that's why when you are converting it into bitmap it gives you out of memory. Each Android app has max 50 mb of RAM to use once it cross beyond that limit android system throws out of memory exception. However we can manage it by making an entry of an attribute in manifest in application tag largeHeap to true.
The best practice to deal with android bitmap is available on developer site. You can click here
Note:- largeHeap feature will work only from OS level 3.0 and above.
Related
here I'm trying to convert my image url to bitmap so that I can display in grid view. The log.d part is working fine, I succesffully get my image url in string format ady, but when comes to decodestream part it occurred error.
public class StringtoBitmap extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Bitmap s) {
super.onPostExecute(s);
}
#Override
protected Bitmap doInBackground(String... params) {
try {
String src = params[0];
Log.d("SRC", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
input.reset();
return myBitmap;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public void StringtoBitmap(String img) {
new StringtoBitmap().execute(img);
}
}
some part of android monitor result:
05-09 02:56:21.408 11585-11671/com.comma.androidapp1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.comma.androidapp1, PID: 11585
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:613)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:589)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:627)
at com.comma.androidapp1.StringtoBitmap.doInBackground(StringtoBitmap.java:39)
at com.comma.androidapp1.StringtoBitmap.doInBackground(StringtoBitmap.java:17)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
[ 05-09 02:56:21.418 1556: 1711 D/ ]
HostConnection::get() New Host Connection established 0xb86734b0, tid 1711
You are getting out of memory error ,your bitmap size is to big ,put below code to resolve out of memory error
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap preview_bitmap = BitmapFactory.decodeStream(is, null, options);
It is better to use libraries like Glide or Picasso for all image operations (decoding, resizing, downloading etc.):
Replace path with local folder path or server url
Dependency:
compile 'com.github.bumptech.glide:glide:3.5.2'
Code
Glide.with (context).load (path).into(imageView);
Using Glide to load bitmap into ImageView
Every time I load certain activity called ProductActivity, I encounter the following error:
Fatal Exception: java.lang.OutOfMemoryError: Failed to allocate a 15694612 byte allocation with 2874400 free bytes and 2MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(VMRuntime.java)
at android.graphics.BitmapFactory.nativeDecodeAsset(BitmapFactory.java)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:613)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:446)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:988)
at android.content.res.Resources.createFromResourceStream(Resources.java:2813)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2514)
at android.content.res.Resources.loadDrawable(Resources.java:2416)
at android.content.res.MiuiResources.loadDrawable(MiuiResources.java:393)
at android.content.res.TypedArray.getDrawable(TypedArray.java:751)
at android.view.View.<init>(View.java:3740)
at android.widget.ImageView.<init>(ImageView.java:139)
at android.widget.ImageView.<init>(ImageView.java:135)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:729)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:810)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:508)
at android.view.LayoutInflater.inflate(LayoutInflater.java:418)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at demand.inn.com.quflip.activity.ProductInfoActivity.onCreate(ProductInfoActivity.java:73)
at android.app.Activity.performCreate(Activity.java:6041)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5273)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Now how should I optimize the resources so that I can get rid of this error?
Should I resize the images on the server or should I resize them inside my app to get free from all these.
Currently, I am using picasso to load the images inside my app.
You are trying to load 15694612 bytes = 15 MB weigh image, which is too big. If there is no option to have a separate downsampled resource, then your option is to downsample it programmatically and then load it.
private Bitmap downscaleBitmapUsingDensities(final int sampleSize, final int imageResId) {
final Options bitmapOptions = new Options();
bitmapOptions.inDensity = sampleSize;
bitmapOptions.inTargetDensity = 1;
final Bitmap scaledBitmap = BitmapFactory.decodeResource(getResources(), imageResId, bitmapOptions);
scaledBitmap.setDensity(Bitmap.DENSITY_NONE);
return scaledBitmap;
}
sampleSize is an integer which specifies how many times you want the source bitmap to be downsampled before loading it into memory.
As you are using picasso to load the images, you can get the bitmap from the picasso by using following code:
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// do you compression logic here and apply that bitmap to image
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
void foo() {
Picasso.with(getContext()).load(getUrl()).into(target);
}
The answer provided by #azizbekian will give you scaled version of image, you can further compress it by using simple code mentioned in this link, which considers the orientation, aspect ration of image too.
I got error when I tried to upload all of the images. I use for to loop the process, but still got error in looping. if i don't use for, it still can upload the image but only 1 image that will be uploaded. how can I solve this?
UploadActivity.java
Intent intent = getIntent();
filePath = intent.getStringExtra("filePath");
ArrayList<String> flpath = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("SavedFilePathsJSONArray",
Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
"");
if (!myJSONArrayString.isEmpty()) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(myJSONArrayString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
flpath.add(jsonArray.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
flpath.add(filePath);
JSONArray mJSONArray = new JSONArray(flpath);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SavedFilePathsJSONArray", mJSONArray.toString()).commit();
for (int i = 0; i < flpath.size(); i++) {
imgFile = new File(flpath.get(i));
if (imgFile.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
ImageView myImage = new ImageView(this);
myImage.setMaxHeight(100);
myImage.setMaxWidth(100);
myImage.setImageBitmap(myBitmap);
layout2.addView(myImage);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
for (int i = 0; i < flPath.size(); i++) {
File file = new File( flPath.get(i));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
entity.addPart("image", new FileBody(file));
// 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;
}
Config.Java
public class Config {
public static final String FILE_UPLOAD_URL = "http://....";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "andrd_upload";
}
error logcat
01-27 16:23:45.940: W/dalvikvm(15986): threadid=12: thread exiting with uncaught exception (group=0x40fe7438)
01-27 16:23:45.950: E/AndroidRuntime(15986): FATAL EXCEPTION: AsyncTask #1
01-27 16:23:45.950: E/AndroidRuntime(15986): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.lang.Thread.run(Thread.java:856)
01-27 16:23:45.950: E/AndroidRuntime(15986): Caused by: java.lang.NullPointerException
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:228)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:221)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 16:23:45.950: E/AndroidRuntime(15986): ... 5 more
01-27 16:23:46.130: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.180: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.220: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:25:29.910: D/dalvikvm(15986): WAIT_FOR_CONCURRENT_GC blocked 0ms
01-27 16:25:29.950: D/dalvikvm(15986): GC_EXPLICIT freed 223K, 8% free 15337K/16583K, paused 2ms+4ms, total 38ms
ScreenShoot
Edit: i put the error logcat and the screenshoot of the error page (UploadActivity.java).
ProgressBar in AsyncTask causes crash. This code essentially loads an image from a URL, and while doing so shows a progress spinner. The first image in the group loads fine, but following that the app crashes.
public class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
ProgressBar progressBar;
public LoadImageTask(ImageView bmImage, ProgressBar progressBar) {
this.bmImage = bmImage;
this.progressBar = progressBar;
}
protected Bitmap doInBackground(String... urls) {
progressBar.setVisibility(View.VISIBLE);
String urldisplay = urls[0];
Bitmap scaledImage = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
Bitmap image = BitmapFactory.decodeStream(in);
scaledImage = Bitmap.createScaledBitmap(image, 380, 250, false);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return scaledImage;
}
protected void onPostExecute(Bitmap result) {
progressBar.setVisibility(View.GONE);
bmImage.setImageBitmap(result);
}
}
Console printout:
02-03 02:45:44.014 24125-24375/simplewall.ryandushane.com.simplewall E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5
Process: simplewall.ryandushane.com.simplewall, PID: 24125
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6247)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:867)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.requestLayout(View.java:17364)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
at android.view.View.requestLayout(View.java:17364)
at android.widget.AbsListView.requestLayout(AbsListView.java:1975)
at android.view.View.requestLayout(View.java:17364)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
at android.view.View.requestLayout(View.java:17364)
at android.view.View.setFlags(View.java:9633)
at android.view.View.setVisibility(View.java:6663)
at android.widget.ProgressBar.setVisibility(ProgressBar.java:1563)
at simplewall.ryandushane.com.simplewall.LoadImageTask.doInBackground(LoadImageTask.java:27)
at simplewall.ryandushane.com.simplewall.LoadImageTask.doInBackground(LoadImageTask.java:17)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
CalledFromWrongThreadException: Only the original thread that created
a view hierarchy can touch its views
Because you are calling progressBar.setVisibility method from doInBackground which run on non-ui thread.
Override onPreExecute() method of AsyncTask which run on Main UI Thread to change Visibility of progress bar:
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
You cannot set progressBar.setVisibility(View.VISIBLE); in doInBackground. its a different thread
or
protected Bitmap doInBackground(String... urls) {
runOnUiThread (new Runnable () {
#Override
public void run () {
progressBar.setVisibility(View.VISIBLE);
}
});
String urldisplay = urls[0];
Bitmap scaledImage = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
Bitmap image = BitmapFactory.decodeStream(in);
scaledImage = Bitmap.createScaledBitmap(image, 380, 250, false);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return scaledImage;
}
Move progressBar.setVisibility(View.VISIBLE); in onPreExecute
Put this progressBar.setVisibility(View.VISIBLE) in onPreExecute() method of AsyncTask and remove this line from doInBackground method.
Good day. Please can someone help me with this?
Is it possible to upload images from android to remote database?
I'm able to communicate with my remote database and perform simple operations like read, write, and delete from database but I have a problem when it comes to uploading images. I'v spent my whole day searching trying and reading methods to accomplish this from stackoverflow and other websites.
This is what I have tried
public class MainActivity extends Activity {
Bitmap bitmap1;
byte[]image1byte;
...
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_1) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap1 = BitmapFactory.decodeFile(picturePath);
image1 = (ImageView) findViewById(R.id.imageView1);
image1.setImageBitmap(bitmap1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG,100,stream);
image1byte=stream.toByteArray();
}
and my AsyncTask task is;
class CreateNewMessage extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute(){
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setMessage("Uploading Message...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String topic=inputTopic.getText().toString();
String message=inputMessage.getText().toString();
String other=inputOther.getText().toString();
List<NameValuePair>params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("topic",topic));
params.add(new BasicNameValuePair("message",message));
params.add(new BasicNameValuePair("details",details));
params.add(new BasicNameValuePair("image",sendImage1));
JSONObject json=jsonParser.makeHttpRequest(url_create_message,"GET",params);
try {
response=json.getString(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response",json.toString());
return response;
}
protected void onPostExecute(String response) {
Toast.makeText(getBaseContext(),"Finished..Response= "+response,Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
but I get the following error;
12-12 16:22:47.017 15942-15985/com.example.mcleroy.studentboxadminpanel E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
Process: com.example.mcleroy.studentboxadminpanel, PID: 15942
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.doInBackground(MainActivity.java:119)
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.doInBackground(MainActivity.java:96)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
12-12 16:22:48.286 15942-15942/com.example.mcleroy.studentboxadminpanel E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.mcleroy.studentboxadminpanel.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4261d878 V.E..... R......D 0,0-684,192} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:376)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.onPreExecute(MainActivity.java:104)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.mcleroy.studentboxadminpanel.MainActivity.createMessage(MainActivity.java:94)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3846)
at android.view.View.performClick(View.java:4466)
at android.view.View$PerformClick.run(View.java:18537)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Please please can anyone look into my code and tell me what I am not doing write, as I really need to be able to upload and download images from my app to remote database nd from remote database to app respectively. or is it impossible to accomplish this?
Here is my PHP script
<?php
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
$response = array();
$topic = $_GET['name'];
$message = $_GET['price'];
$details = $_GET['description'];
$image=$_GET['image'];
$con = mysql_connect($servername,$username,$password) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("INSERT INTO messages(topic, messages, others,image) VALUES('$name', '$price',`` '$description','$image')");
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Message successfully created.";
// echoing JSON response
echo json_encode($response);
}
?>
Thanks alot in advance as you try to help;