Android: can not show dialog from AsyncTask class - java

I've builded Updates class for my Android app. It works fine except Download inner AsyncTask-class.
I wanted to display progress dialog in LoadingActivity while file is downloading.
Firstly, I invoke the Updates class in onCreate method. As a parameter I send activity context. Then in Updates class constructor I invoke Check inner class (AsyncTask), which parse JSON response from URL (works properly) and invoke Download (next Updates inner class) and here it's problem.
When I'm trying to create ProgressDialog object, the compiler throws:
04-01 02:53:56.864 24393-24425/pl.com.mpkostrowiec.schedule E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
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:838)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:197)
at android.os.Handler.<init>(Handler.java:111)
at android.app.Dialog.<init>(Dialog.java:107)
at android.app.AlertDialog.<init>(AlertDialog.java:114)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at pl.com.mpkostrowiec.schedule.DownloadAsync.<init>(DownloadAsync.java:30)
at pl.com.mpkostrowiec.schedule.Updates$Check.doInBackground(Updates.java:128)
at pl.com.mpkostrowiec.schedule.Updates$Check.doInBackground(Updates.java:74)
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:838)
I thought that ProgressDialog constructor can't access context variable from Updates class, so I tried to send it as parameter, but it doesn't resolve the problem.
LoadingActivity class:
package pl.com.mpkostrowiec.schedule;
import ...
public class LoadingActivity extends Activity {
private final Preferences preferences = new Preferences(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
preferences.savePreference("Preferences", "firstRun", "1");
// Check if first run
if (preferences.readPreference("Preferences", "firstRun").equals("0")) {
System.out.println("****************** Not first run");
} else {
// Create directory
File dir = this.getDir("Versions", MODE_PRIVATE);
new Updates(this);
}
}
}
Update class:
package pl.com.mpkostrowiec.schedule;
import ...
interface AfterExecuteListener {
public void afterDownload(String[] versionData, int type);
}
public class Updates implements AfterExecuteListener{
private static VersionsTable versionsTable;
private Context context;
public static Boolean status_current = false;
public static Boolean status_new = false;
private final int TYPE_CURRENT = 0;
private final int TYPE_NEW = 1;
private static final String URL = "http://www.mpkostrowiec.com.pl/preview/";
private static final String GET_VERSIONS = "includes/android/versions.php";
private static final String RESOURCES = "resources/android/versions/";
private static final String EXTENSION = ".db";
public Updates(Context context) {
this.context = context;
versionsTable = new VersionsTable(this.context);
new Check(TYPE_CURRENT).execute();
}
public final void afterDownload(String[] versionData, int type) {
// Add version data to DB
versionsTable.open();
versionsTable.add(versionData);
versionsTable.close();
// Set status
if (type == TYPE_CURRENT) {
System.out.println("****************** Downloaded: " + type);
status_current = true;
} else if (type == TYPE_NEW) {
System.out.println("****************** Downloaded: " + type);
status_new = true;
}
Schedule();
}
private void Schedule() {
if (status_current) {
if (status_new) {
System.out.println("****************** SUCCESS");
} else {
new Check(TYPE_NEW).execute();
}
}
}
private class Check extends AsyncTask<String, Integer, String> {
public AfterExecuteListener mListener;
private int type;
public Check(int type) {
this.type = type;
}
#Override
protected String doInBackground(String... Url) {
String[] typeStr = {"current", "new"};
// Get versions form URL
JSONObject json = null;
String versions = null;
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(URL + GET_VERSIONS);
try {
response = myClient.execute(myConnection);
versions = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject jObject = new JSONObject(versions);
json = jObject.getJSONObject(typeStr[type]);
if (json.length() > 1) {
String[] versionData = {json.getString("id"),
json.getString("name"),
json.getString("expDate")};
versionsTable.open();
Boolean idExist = versionsTable.check(versionData[0]);
versionsTable.close();
// Check version
if (!idExist) {
// Start downloading
Download download = new Download(versionData, type);
download.setListener(Updates.this);
download.execute(URL + RESOURCES + versionData[0] + EXTENSION);
}
} else {
// If array contains only false field then do not update
if (type == TYPE_CURRENT) {
Updates.status_current = true;
} else if (type == TYPE_NEW) {
Updates.status_new = true;
}
Schedule();
}
} catch ( JSONException e) {
e.printStackTrace();
}
return null;
}
}
private class Download extends AsyncTask<String, Integer, String> {
public ProgressDialog mProgressDialog;
public AfterExecuteListener mListener;
private String[] versionData;
private int type;
public Download(String[] versionData, int type) {
this.versionData = versionData;
this.type = type;
// Create progress dialog
mProgressDialog = new ProgressDialog(context);
// Set your progress dialog Title
mProgressDialog.setTitle("Updating...");
// Set your progress dialog Message
mProgressDialog.setMessage("Update in progress. Please wait.");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Show progress dialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... Url) {
try {
java.net.URL url = new URL(Url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// Detect the file lenghth
int fileLength = connection.getContentLength();
// Locate storage location
String filepath = context.getApplicationInfo().dataDir + "/Versions";
// Download the file
InputStream input = new BufferedInputStream(url.openStream());
// Save the downloaded file
OutputStream output = new FileOutputStream(filepath + "/" + versionData[0] + ".db");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
} catch (Exception e) {
// Error Log
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// Update the progress dialog
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
// Dismiss the progress dialog
mProgressDialog.dismiss();
mListener.afterDownload(versionData, type);
}
private void setListener(AfterExecuteListener listener) {
mListener = listener;
}
}
}

Related

How to Cast Fragment to Async Constructor?

I want to cast SlideshowDialogFragment to context in my asynctask in DdownloadTask.java but when i write
final DownloadTask downloadTask = new
DownloadTask(myActivity.this);
SlideshowDialogFragment instead of myActivity , android show warning and say
warning android
i don't know what am i do ?? thx for help me
public class SlideshowDialogFragment extends DialogFragment{
ArrayList<Image> images;
ViewPager viewPager;
MyViewPagerAdapter myViewPagerAdapter;
TextView lblCount,lblTitle,lblDate;
Button btn_set;
Button btn_download;
int selectedPostition;
DownloadManager downloadManager;
public static ProgressDialog mProgressDialog;
static SlideshowDialogFragment newInstance(){
SlideshowDialogFragment f=new SlideshowDialogFragment();
return f;
}
#Override
public View onCreateView (LayoutInflater inflater,ViewGroup container,Bundle saveInstanceState)
{
View v=inflater.inflate(R.layout.fragment_image_slider,container,false);
viewPager=(ViewPager)v.findViewById(R.id.view_pager);
lblTitle=(TextView)v.findViewById(R.id.title);
lblDate=(TextView)v.findViewById(R.id.date);
btn_set=(Button)v.findViewById(R.id.btn_set);
btn_download=(Button)v.findViewById(R.id.btn_download);
images=(ArrayList<Image>) getArguments().getSerializable("images");
selectedPostition=getArguments().getInt("position");
myViewPagerAdapter=new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
displayInfo(position);
//setWallpaper(position);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
setCurrentItem(selectedPostition);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
download(selectedPostition);
}
});
return v;
}
void download (int position){
Image image=images.get(position);
String large = image.getlarge();
final DownloadTask downloadTask = new
DownloadTask(**SlideshowDialogFragment**.this);
downloadTask.execute(large);
}
And this is DownloadTask Activity with constructor i write AsyncTask in this class:
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"خطای دانلود "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"دانلود با موفقیت انجام شد",
Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/tabriz.jpg");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
what am i do for casting SlideshowDialogFragment to Async ?
You need to pass a Context as you defined your constructor like that. A Fragment does not have a Context, but the Activity has it. Since Fragment is a part of an Activity you can access it with
SlideshowDialogFragment.this.getActivity();
You could also use it directly with DownloadTask(getActivity())

SkImageDecoder: Factory returned null

I'm using a MySQL server to fetch images from database to android to display in an ImageView. However, I receive the following error:
SkImageDecoder:: Factory returned null
This has been answered before, but I call .decodeStream once? It would be appreciated if you could help me
MainActivty.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://thakurnigamananda.com/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
Logcat:
12-25 22:01:30.150 30009-30009/com.example.ayush.testingfordata I/ViewRootImpl: ViewRoot's Touch Event : Touch Down
12-25 22:01:30.180 30009-30009/com.example.ayush.testingfordata I/ViewRootImpl: ViewRoot's Touch Event : Touch UP
12-25 22:01:30.340 30009-30225/com.example.ayush.testingfordata D/libc: getaddrinfo called from pid =30009
12-25 22:01:30.340 30009-30225/com.example.ayush.testingfordata E/DataScheduler: isDataSchedulerEnabled():false
12-25 22:01:30.340 30009-30225/com.example.ayush.testingfordata D/libc: getaddrinfo called from pid =30009
12-25 22:01:31.080 30009-30225/com.example.ayush.testingfordata D/libc: dnsproxy getaddrinfo returns 0
12-25 22:01:31.800 30009-30282/com.example.ayush.testingfordata D/skia: --- SkImageDecoder::Factory returned null
fixed, error in PHP scripts and database.

Can you show me why these methods are out of scope?

I am using a tutorial to create a download class and it uses a progress dialog. The show and dissmiss methods are in protected classes inside of the asynchTask class. The IDE is telling me that it can not resolve them
public class DownloadHandler {
private Context mContext;
public String filename;
private String remotePath;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
public DownloadHandler(String rp, String f, Context c) throws Exception {
mContext = c;
remotePath = rp;
filename = f;
}
private void startDownload() {
String url = "http://example.com/"+remotePath+"/"+filename+".pdf";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//===================showDialog can not be resolved============================
showDialog(DIALOG_DOWNLOAD_PROGRESS);
//========================================================================
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lengthOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
//write it to the internal storage
OutputStream output = new FileOutputStream(filename+".pdf");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
//=========dismissDialog can not be resolved ==================
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
//=============================================================
}
}
}
Does it have something to do with the protected class?
showDialog and dismissDialog are in the Activity class. In the tutorial, it shows that the class Download extends activity, which the inner class can then use.
Have Download extend Activity. As for the methods being deprecated, this is because you should be using a DialogFragment. Apparently, the tutorial you are following is outdated, and you should look into how to use a DialogFragment

ImageDownload asynctask is getting start before test asynctask complted

public class DetailsActivity extends Activity {
private ArrayAdapter<Imageclass> adapter;
ArrayList<String> imageselect = new ArrayList<String>();
private ArrayList<Imageclass> array1;
private ArrayList<Imageclass> list = new ArrayList<Imageclass>();
//private ArrayList<Imageclass> array;
ArrayList<String> imagetest = new ArrayList<String>();
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
int id;
int pid;
int val;
int val_new;
double lati;
double longi;
String imagename;
//private ImageView image;
//public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
ImageView image;
static Bitmap bm;
ProgressDialog pd;
BitmapFactory.Options bmOptions;
public class test extends AsyncTask<Void, Void, InputStream>{
ArrayList<Imageclass> str;
private DetailsActivity activity;
public test(DetailsActivity activity){
this.activity = activity;
}
#Override
protected InputStream doInBackground(Void... params) {
//String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id);
Log.e("Checking id",""+id);
String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id);
URL url;
try {
stringURL=stringURL.replaceAll(" ", "%20");
url = new URL(stringURL);
Log.e("URL",""+ url);
URLConnection conn= url.openConnection();
Log.e("URLConnection",""+conn );
InputStream stream= conn.getInputStream();
Log.e("URLStream",""+stream );
return stream;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("Excepiton", ""+e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
Log.e("Result", ""+result);
StringBuilder builder = new StringBuilder();
Log.e("Builder", ""+ builder);
BufferedReader reader = new BufferedReader(new InputStreamReader(result));
Log.e("Reader", ""+ reader);
String line = null;
try {
while((line = reader.readLine()) != null) {
Log.e("Result11", ""+ builder.append(line));
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String jsonString = builder.toString();
Log.e("image", jsonString);
try {
JSONObject rootObject = new JSONObject(jsonString);
Log.e("JSOnObject",""+ rootObject);
JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images");
//array1.clear();
ArrayList<String> imagearray = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
Imageclass imageinstance = new Imageclass();
JSONObject object = (JSONObject) jsonArray.get(index);
Log.e("Image test", "" + object);
imageinstance.image = object.getString("file_name");
//### this contain the image name
Log.e("Imageinstance.image",""+imageinstance.image);
imagename = imageinstance.image;
imagearray.add(imageinstance.image);
array1.add(imageinstance);
//array1.add(imagearray);
Log.e("array1","test"+array1);
}
Log.e("IMAGES",""+array1);
activity.setlist(array1);
}
catch (JSONException e) {
Log.e("this Exception",""+ e);
e.printStackTrace();
}
catch (Exception e) {
Log.e("NULL","NULL"+e);
}
// adapter.notifyDataSetChanged();
}
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... param) {
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
Log.e("inside img",""+Finalname);
Log.e("inside img_val",""+val);
Log.e("Check","check"+imageUrl);
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
Log.e("Test","Test"+ imageUrl.equals(""));
image.setImageBitmap(bm);
} else {
Toast.makeText(DetailsActivity.this,
"test", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
String Finalname;
//String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname;
public void setlist(ArrayList<Imageclass> list)
{
this.list= list;
Log.e("LIST",""+ this.list);
String imagename1 = list.toString();
Log.e("image new value",""+imagename1);
this.list= list;
Log.e("testing",""+ this.list);
for (int i=0; i < list.size(); i++)
{
Log.e("new check",""+list.get(i));
//String test2= list.get(i).toString();
imagetest.add(list.get(i).toString());
Finalname = list.get(i).toString();
getimage_name(Finalname);
Log.e("Come",""+list.get(i).toString());
Log.e("Finalname",""+Finalname);
}
}
//String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
private void getimage_name(String finalname2) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
image = (ImageView)findViewById(R.id.imageView2);
// getMenuInflater().inflate(R.menu.details);
//R.id.textDetailPlace
textView1 = (TextView)findViewById(R.id.textDetailPlace);
textView2 = (TextView)findViewById(R.id.textDetailAddress );
textView3 = (TextView)findViewById(R.id.textCapacity);
// textView4 = (TextView)findViewById(R.id.textDetailContactNo);
textView5 = (TextView) findViewById(R.id.textViewDescription);
textView1.setText(getIntent().getExtras().getString("test"));
textView2.setText(getIntent().getExtras().getString("test2"));
textView3.setText(getIntent().getExtras().getString("test3"));
//textView4.setText(getIntent().getExtras().getString("test4"));
textView5.setText(getIntent().getExtras().getString("test5"));
id = getIntent().getExtras().getInt("test6");
Log.e("ID value",""+id);
pid = getIntent().getExtras().getInt("test7");
Log.e("PID value",""+pid);
lati = getIntent().getExtras().getDouble("testlat");
Log.e("long",""+lati);
longi = getIntent().getExtras().getDouble("testlong");
Log.e("long",""+longi);
val=pid;
Log.e("val",""+val);
ActionBar actionBar = getActionBar();
actionBar.hide();
pd = ProgressDialog.show(DetailsActivity.this, null, null,true);
pd.setContentView(R.layout.progress);
array1 = new ArrayList<Imageclass>();
//new test(this).execute();
new test(this).execute();
here test asynctask is called
Log.e("JUST","CHECK");
Log.e("JUST","CHECK");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here imageDownload asynctask is getting called::
new ImageDownload().execute();
Log.e("imagename",""+imagename);
}
}
here before ImageDownload is start executing before test async task is complete
and i am not able to get the status of the task can u tell how it is done
whatever i understood from this you want to execute your ImageDownload thread after the task thread,so start the ImageDownload Thread from the onPostExecute() of your task thread
When executing an async task a new thread is started, but your current thread keeps running. It immediately runs into your thread.sleep(1000) just after starting test.async.
It looks like your doing some internet downloading in test.async, and as you might have guessed, it takes longer than 1000 milliseconds (1 second). This means 1 second later, your other async is starting, before the first completed.
I assume you want to stagger them. In the postExecute of the first async, you can spawn the second async. A more stylistically correct method would be to implement an interface on your activity that takes a callback on Async completion, then upon receiving the call back, launch your second async.
An example of how to structure this is below.
interface AsyncCallback{
void onAsyncComplete();
}
public class ExampleActivity extends Activity implements AsyncCallback {
....
public void launchFirstAsync(){
new Task(this).execute();
}
#Override
public void onAsyncComplete() {
//todo launch second asyncTask;
}
}
class Task extends AsyncTask<Void, Void, Void>{
AsyncCallback cb;
Task(AsyncCallback cb){
this.cb = cb;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
cb.onAsyncComplete();
}
}
Have a look here, This Help me for same..Pass your url to GetTemplateImageController and get the result in Bitmap array
GetTemplateImageController Class:
public class GetTemplateImageController extends AsyncTask<String, Void, Bitmap[]>
{
Context mcontext;
private ProgressDialog pDialog;
public static String[] imageurls;
public static Bitmap bm[]=new Bitmap[15];
// URL to get JSON
private static final String url= "http://xxx.xxx.xxx.xxx/image_master.php?";
private static final String TEMPLATE = "Template_images";
private static final String IMAGEURLS = "tempimagename";
// JSONArray
JSONArray loginjsonarray=null;
//result from url
public GetTemplateImageController(Context c) {
this.mcontext=c;
}
protected void onPreExecute() {
// Showing progress dialog
super.onPreExecute();
pDialog=new ProgressDialog(mcontext);
pDialog.setMessage("Loading");
pDialog.setCancelable(true);
pDialog.setIndeterminate(true);
pDialog.show();
}
protected Bitmap[] doInBackground(String... arg) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("templateMasterId",arg[0].toString()));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, params);
Log.d("Response: ", ">"+jsonstr);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(TEMPLATE);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(IMAGEURLS);
}
for(int i=0;i<imageurls.length;i++){
bm[i]=DownloadImage(imageurls[i]);
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Toast.makeText(mcontext,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return bm;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch(Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Integer result) {
// Dismiss the progress dialog
pDialog.dismiss();
if(result != null)
Toast.makeText(mcontext,"Download complete", Toast.LENGTH_SHORT).show();
//}
}
}
ServiceHandler Class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpEntity httpEntity=null;
HttpResponse httpResponse=null;
// Checking http request method type
if(method==POST){
HttpPost httpPost=new HttpPost(url);
if(params!=null)
{
//adding post params
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse=httpClient.execute(httpPost);
}
else if(method==GET)
{
// appending params to url
if(params!=null)
{
String paramString=URLEncodedUtils.format(params, "utf-8");
url +="?"+paramString;
}
HttpGet httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
}
Over time there have been several changes to the way Android deals with AsyncTasks that run concurrently. In very old Android versions (pre-1.6 afaik) multiple AsyncTasks were executed in sequence. That behavior has been changed to run the AsyncTasks in parallel up until Android 2.3. Beginning with Android 3.0 the the Android team decided that people were not careful enough with synchronizing the tasks that run in parallel and switched the default behavior back to sequential execution. Internally the AsyncTask uses an ExecutionService that can be configured to run in sequence (default) or in parallel as required:
ImageLoader imageLoader = new ImageLoader( imageView );
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );

Android: Progress Bar to Upload Data to the Server

In my application some data is there which is wrapped into an object.
I am sending this object to the server. Everything work correctly.
Here I want to show progress bar when the data is loading to the server.
For this I am using this code:
ProgressThread progThread;
ProgressDialog progDialog;
int typeBar;
int delay = 40;
int maxBarValue = 200;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
progDialog = new ProgressDialog(this);
progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progDialog.setMax(maxBarValue);
progDialog.setMessage("Data uploading to the Server..");
progThread = new ProgressThread(handler);
progThread.start();
return progDialog;
default:
return null;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// Get the current value of the variable total from the message data
// and update the progress bar.
int total = msg.getData().getInt("total");
progDialog.setProgress(total);
if (total <= 0) {
dismissDialog(typeBar);
progThread.setState(ProgressThread.DONE);
}
}
};
private class ProgressThread extends Thread {
final static int DONE = 0;
final static int RUNNING = 1;
Handler mHandler;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
#Override
public void run() {
mState = RUNNING;
total = maxBarValue;
while (mState == RUNNING) {
connectServerClass.saveOnServer(Object);
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total--; // Count down
}
}
public void setState(int state) {
mState = state;
}
}
When user click on button then:
typeBar = 1;
showDialog(typeBar);
connectServerClass.saveOnServer(Object)
by the above line I am sending object to the server. Actually I am sending data to the other class which is connectServerClass and this class send object to the server.
but this code not work correctly. This code connect to the server lots of time.
I use the following Code :
private class Uploader extends AsyncTask<Void, String, Integer>
{
private List<File> files;
private boolean canceled;
private int uploaded;
private Account account;
private ProgressDialog uploadSeekBar;
public Uploader(Account a, List<File> files)
{
this.account = a;
this.files = files;
}
#Override
protected void onPreExecute()
{
uploadSeekBar.setMax(files.size());
uploadSeekBar.setProgress(0);
uploadSeekBar.setVisibility(View.VISIBLE); //Error: the method setVisibility is undefined
}
#Override
protected void onPostExecute(Integer result)
{
uploadSeekBar.setVisibility(View.INVISIBLE);
Toast.makeText(Upload.this, result + " files uploaded", // Error: Upload cannot be resolved to a type
Toast.LENGTH_LONG).show();
}
#Override
protected void onCancelled()
{
// XXX need a way to actually cancel the last upload
Toast.makeText(Upload.this, "canceling upload", Toast.LENGTH_LONG)
.show();
this.canceled = true;
uploadSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected Integer doInBackground(Void... voids)
{
uploaded = 0;
try
{
Iterator<File> it = this.files.iterator();
while (!canceled && it.hasNext())
{
File file = it.next();
it.remove();
String msg = "";
try
{
if (debugMode) // what is this debugMode
{
//Put your uploading code here.
msg = ("fake uploading " + file);
Thread.sleep(3000);
} else
{
msg = ("uploading: " + file);
controller.uploadFile(file, this.account); //Error: controller cannot be resolved
}
uploaded++;
publishProgress(msg);
} catch (IOException e)
{
controller.te("error uploading file: " + file);
controller.te("error uploading file: " + e);
} catch (InterruptedException e)
{
}
}
} catch (Exception e)
{
publishProgress("error uploading: " + e);
}
return uploaded;
}
#Override
protected void onProgressUpdate(String... strings)
{
uploadSeekBar.setProgress(uploaded);
updateUploadMessage(files.size());
Toast.makeText(Upload.this, strings[0], Toast.LENGTH_LONG).show(); //Error: The method updateUploadMessage(int) is undefined for the type FirstActivity.Uploader
}
}
But I facing some error which I mention as comment in the right side of that line. Please suggest me.
I will strongly recommend you to Use AsyncTask.
Below Code snippet will help you on How your AsyncTask should look like.
package org.sample;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import android.accounts.Account;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Toast;
private class Uploader extends AsyncTask<Void, String, Integer>
{
private List<File> files;
private boolean canceled;
private int uploaded;
public Uploader(Account a, List<File> files)
{
this.account = a;
this.files = files;
}
#Override
protected void onPreExecute()
{
uploadSeekBar.setMax(files.size());
uploadSeekBar.setProgress(0);
uploadSeekBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Integer result)
{
uploadSeekBar.setVisibility(View.INVISIBLE);
Toast.makeText(Upload.this, result + " files uploaded",
Toast.LENGTH_LONG).show();
}
#Override
protected void onCancelled()
{
// XXX need a way to actually cancel the last upload
Toast.makeText(Upload.this, "canceling upload", Toast.LENGTH_LONG)
.show();
this.canceled = true;
uploadSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected Integer doInBackground(Void... voids)
{
uploaded = 0;
try
{
Iterator<File> it = this.files.iterator();
while (!canceled && it.hasNext())
{
File file = it.next();
it.remove();
String msg = "";
try
{
if (debugMode)
{
//Put your uploading code here.
msg = ("fake uploading " + file);
Thread.sleep(3000);
} else
{
msg = ("uploading: " + file);
controller.uploadFile(file, this.account);
}
uploaded++;
publishProgress(msg);
} catch (IOException e)
{
controller.te("error uploading file: " + file);
controller.te("error uploading file: " + e);
} catch (InterruptedException e)
{
}
}
} catch (Exception e)
{
publishProgress("error uploading: " + e);
}
return uploaded;
}
#Override
protected void onProgressUpdate(String... strings)
{
uploadSeekBar.setProgress(uploaded);
updateUploadMessage(files.size());
Toast.makeText(Upload.this, strings[0], Toast.LENGTH_LONG).show();
}
}

Categories

Resources