Running multiple Asyntask simultaneously - java

I have server client communication program at server side I have camera and that camera I am controlling by my android application as client it is working but the problem is when the server memory is full then server is stopping the camera and sending a message to client and and if client want to stop camera by it self then client is sending command to server and server stop the camera .
The problem is there only I am not getting the massage if I am getting the massage of "memory full" then I am not getting the massage "stopping camera "when user want to kill by itself and if am manage to get the "stopping camera " message then I am not getting the "memory full massage "
here is my code please help me
thanks in advance
/** here is the recording start button I am calling a asyntask for recording
* Record and store video at battery control unit(server end) at background
*/
record=(ImageButton)findViewById(R.id.record);
record.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(socket==null){
Toast.makeText(getApplicationContext(), "connection not establised", Toast.LENGTH_SHORT).show();
}
else{
pDialog.show();
suspended=false;
start=false;
new CommunicationTaskrec().execute();
}
}
});
/**
* Async task for the record, which runs on back ground.
*/
public class CommunicationTaskrec extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String str = "3";
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (IOException e1) {
e1.printStackTrace();
}
out.println(str);
String resultrec="testing the UI Thread update";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
resultrec = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Log.d("inside bg thread", resultrec);
mHandler.obtainMessage(MESSAGE_READ, resultrec).sendToTarget();
out.flush();
// new Thread(new RecThread()).start();
// new CommunicationTaskmemorycheck().execute();
return resultrec;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
//here is the message handler case
/**
* Creating a dialog box which shows a timer for the recording time
*/
case MESSAGE_READ:
final String readBuf = (String) msg.obj;
String string1 ="no enough space left on device";
if(readBuf !=null){
if(readBuf.equalsIgnoreCase(string1))
{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "NO Enough Space Left for Recording Please Remove some files at server end.", Toast.LENGTH_LONG).show();
}
else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, readBuf, Toast.LENGTH_LONG).show();
//here is the dialog box where I have a stop button also by which user stopping the ///camera manually
View viewlist=MainActivity.this.getLayoutInflater().inflate(R.layout.timer, null);
dialog = new Dialog(MainActivity.this);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
dialog.setContentView(viewlist);
dialog.setTitle("Status.....");
dialog.setCancelable(false);
TextView text = (TextView) dialog.findViewById(R.id.valuerec);
text.setText("Want to stop the Recording ?");
TextView cur_val = (TextView) dialog.findViewById(R.id.curvaluerec);
cur_val.setText("Recording Duration..");
Button stop = (Button) dialog.findViewById(R.id.start);
mChronometer = (Chronometer) dialog.findViewById(R.id.chronometer);
mChronometer.start();
dialog.show();
//here a asyntask and it is used for getting the memory full message
//it run contentiously on background and when the memory is full it //recieve "memory full massage"
task = new AsyncTask<Void, Void, Void>() {
String result=null;
protected Void doInBackground(Void... params) {
Runnable action = new Runnable() {
public void run() {
mHandler.obtainMessage(MESSAGE_READcreate, result).sendToTarget();
}
};
try {
do {
//Pause work if control is paused.
//tControl.waitIfPaused();
//Stop work if control is cancelled.
if (tControl.isCancelled()) {
suspended=true;
break;
}
while(!suspended){
String string1 ="memory full";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
result = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if((result!=null && result.equalsIgnoreCase(string1)) )
{
mHandler.obtainMessage(MESSAGE_READcreate, result).sendToTarget();
result=null;
suspended=true;
start=true;
runOnUiThread(action);
break;
}
}
}while (!suspended);
} catch (Exception e) {
}
return null;
}
};
task.execute();
//here is the dialog box stop button where I have a runnable thread which is used for send //command to server when user want to stop recording manually
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
task.cancel(true);
tControl.cancel();
suspended=true;
dialog.dismiss();
dialog=null;
mChronometer.stop();
pDialog.show();
//this is the runnable thread where I am getting "stopping //camera "massage
new Thread(new Runnable() {
#SuppressLint("ShowToast")
public void run() {
while (true) {
String str = "8";
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (IOException e) {
e.printStackTrace();
}
out.println(str);
String resultcap=null;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
resultcap = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
mHandler.obtainMessage(MESSAGE_READstoprunning, resultcap).sendToTarget();
out.flush();
//suspended=false;
break;
}
}
}
).start();
}
});
}
}
else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "error server not respondingrec", Toast.LENGTH_LONG).show();
}
break;

change execute() to executeOnExecutor(AsynTask.ThreadpoolExecutor)

AsyncTasks doc
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke
executeOnExecutor(java.util.concurrent.Executor, Object[])
with THREAD_POOL_EXECUTOR.

Related

How to download multiple images and have one progressBar using AsynTask (Android)

I want my program to download many images (around 500) from the internet and store them in my external storage. Currently when I download a single image, it shows a progressBar and downloads the image properly. However when I am trying to replicate w/ two images, it gives the Toast for "Download complete" for both images being downloaded, however no progressBar for either image is shown and only the first image is properly downloaded.
Here is the code for my onCreate method for activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove Title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//force portrait orientation. (No landscape orientation).
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_quran);
//Instantiate ProgressDialog (Used for downloading quran pages).
myProgressDialog = new ProgressDialog(QuranActivity.this);
myProgressDialog.setMessage("Downloading Quran");
myProgressDialog.setIndeterminate(true);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setCancelable(true);
//execute when the downloader must be fired.
final DownloadTask downloadTask = new DownloadTask(QuranActivity.this);
DownloadTask second = new DownloadTask(getApplicationContext());
myHTTPURL = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0001.jp2&scale=1&rotate=0";
myHTTPURL2 = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0002.jp2&scale=1&rotate=0";
//First check if the file has already been created. (Only need to download 1ce, or
//in the case where the user deleted the files, we reinstall them again).
if (isExternalStorageWritable()) {
File makeDirectory = getQuranStorageDir(QuranActivity.this, "Quran_Pages");
for (int i = 0; i < 2; i++) {
Bundle myBundle = new Bundle();
myBundle.putInt("i", i);
if (i == 0) {
downloadTask.execute(myHTTPURL);
try {
downloadTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
myProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
} else {
/*if (downloadTask.getStatus() == AsyncTask.Status.FINISHED) {
downloadTask.execute(myHTTPURL2);
} else if (downloadTask.getStatus() == AsyncTask.Status.RUNNING) {
try {
downloadTask.execute(myHTTPURL2).wait(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} */
second.execute(myHTTPURL2);
try {
second.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// downloadTask.execute(myHTTPURL2);
}
}
}
and this is the code for my AsynTask Class.
#TargetApi(Build.VERSION_CODES.FROYO)
private class DownloadTask extends AsyncTask {
private Context context;
private PowerManager.WakeLock myWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#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.setDoOutput(true);
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
//Display download percentage.
int fileLength = connection.getContentLength();
//create folder to place the downloaded file in.
// File Path:E:\Android\data\com.syedabdullah.syed.quran_memorization_application
// \files\Quran Memorization Application\Quran_Pictures
//So first create a root folder Quran Memorization Application then inside that
//folder we create another folder named Quran Pictures.
/* File rootFolder = new File(getExternalFilesDir("Quran Memorization Application"),
"Quran_Pages"); */
//Here we insert inside the Quran_Pictures folder the quran_pages.
//String myFileName = "quran_01.jpg";
Bundle y = new Bundle();
int retrievePos = y.getInt("i");
String quranFilePageName = "_" + retrievePos + ".jpg";
// String fileName = "justwork.jpg";
File sup = new File(getExternalFilesDir("Quran Memorization Application"), "Quran_Pages");
File myFile = new File(sup, quranFilePageName);
myFile.createNewFile();
//downlaod the file.
input = connection.getInputStream();
output = new FileOutputStream(myFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
//allow cancel with back button.
if (isCancelled()) {
input.close();
return null;
}
total += count;
//publish the progress.
if (fileLength > 0) {
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(myFile));
QuranActivity.this.sendBroadcast(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
#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);
myWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
myWakeLock.acquire();
myProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
//If we get here length is known, so setIndertimante to false.
myProgressDialog.setIndeterminate(false);
myProgressDialog.setMax(100);
myProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
myWakeLock.release();
myProgressDialog.dismiss();
if (result != null) {
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Download Complete", Toast.LENGTH_SHORT).show();
}
}
} }
I was hoping to have a for loop that would create hundreds of downloadTasks and download all the images I need, and then I would call the get method. However in order for that to work, I first need too know why when I try for 2 images only the first one gets downloaded and why no progressbar shows up. Also if possible if I could get a hint as to how I can make my progressBar update for all the images and not be designed for just 1. Thanks in advance. (Note all URLs are currect.)
Thank you so much! figured out that my loops were suppose to go inside doInBackground. Also to anyone else having a similar issue. To download multiple files and display a decent progressBar, here is a very great tutorial: http://theopentutorials.com/tutorials/android/dialog/android-download-multiple-files-showing-progress-bar/

How to implement ASyncTask in my code

in my app I am trying to read a string out of a text file located online, and then save the contents to a variable. Here is my current code:
download.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
URL site = new URL("http://m.uploadedit.com/b029/1393133970157.txt");
Scanner s = new Scanner(site.openStream());
String num = s.nextLine();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "String from file is: " + num,
Toast.LENGTH_LONG).show();
}
});
However this is giving me a force close. Here is the log: http://pastebin.com/2nsxmJz1
I believe that I need to implement an ASyncTask, but not sure how to go about doing so.
You can't use network communications on UI thread. As u correctly mentions you should use AsyncTask for such cases:
final AsyncTask<Object,Object,String> task = new AsyncTask<Object,Object,String>() {
protected String doInBackground(Object... o) {
try {
URL site = new URL("http://m.uploadedit.com/b029/1393133970157.txt");
Scanner s = new Scanner(site.openStream());
return s.nextLine();
}
catch(MalformedURLException e) {
throw new RuntimeException("Incorrect URL", e);
}
catch(IOException e) {
throw new RuntimeException("Can't fetch file content from url", e);
}
}
protected void onPostExecute(String r) {
Toast.makeText(getApplicationContext(), "String from file is: " + r,
Toast.LENGTH_LONG).show();
}
};
task.execute();

Android progress dialog not closing

I want to show progress dialog in the page layout. I implemented in the following code. Progress Dialog is not closed and it keeps running.When I click an image in the previous page it will navigate to the next layout and I want this layout to show progress dialog before all the data is downloaded from server and show it in the list of the current layout. Progress dialog is displayed and list is displayed in the background but progress dialog keeps on running and it does not get closed. I don't know where i am going wrong. Help please.
ProgressDialog pg;
String[] ar;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.filename);
pg=ProgressDialog.show(this, "ABC", "Downloading .....",true);
Thread dt= new Thread(new Runnable()
{
public void run()
{
try
{
String addr=Util.url;
URL url = new URL(urlname);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String x = "";
String total = "";
int i=0;
ArrayList<String> content = new ArrayList();
while((x = r.readLine()) != null)
{
content.add(x);
}
in.close();
r.close();
ar= content.toArray(new String[content.size()]);
}
catch(Exception e1){
handler.sendEmptyMessage(0);
}
}
});
dt.start();
try{
dt.join();
}catch(Exception e){
handler.sendEmptyMessage(0);
}
try{
if(ar[0].toString().trim()!="")
{
android.view.Display display1 = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
TableLayout tbl1 = (TableLayout)findViewById(R.id.tableLayout2);
TableRow newRow1 = (TableRow) new TableRow(this);
TextView txt=(TextView) new TextView(this);
txt.setText("No");
txt.setGravity(Gravity.LEFT);
txt.setTextColor(Color.RED);
txt.setTextSize(18);
TextView txt1=(TextView) new TextView(this);
txt1.setText("NAME");
txt1.setTextColor(Color.RED);
txt1.setTextSize(18);
txt1.setGravity(3);
TextView txt2=(TextView) new TextView(this);
txt2.setText("DATE");
txt2.setTextColor(Color.RED);
txt2.setTextSize(18);
txt.setGravity(3);
TextView txt3=(TextView) new TextView(this);
txt3.setText("VALUE");
txt3.setTextColor(Color.RED);
txt3.setTextSize(18);
txt3.setGravity(Gravity.RIGHT);
txt.setWidth((int)(display1.getWidth()/4));
txt1.setWidth((int)(display1.getWidth()/4));
txt3.setWidth((int)(display1.getWidth()/4));
txt2.setWidth((int)(display1.getWidth()/4));
newRow1.addView(txt2);
newRow1.addView(txt);
newRow1.addView(txt1);
newRow1.addView(txt3);
tbl1.addView(newRow1);
for(int t=0;t<(ar.length);t++)
{
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
TableLayout tbl = (TableLayout)findViewById(R.id.tableLayout1);
TableRow newRow = (TableRow) new TableRow(this);
newRow.setClickable(true);
TextView tx=(TextView) new TextView(this);
String temp=ar[t].toString();
tx.setText(temp);
tx.setTextColor(Color.WHITE);
tx.setGravity(Gravity.LEFT);
tx.setTextSize(15);
t=t+1;
TextView tx1=new TextView(this);
tx1.setText(ar[t].toString());
tx1.setGravity(Gravity.LEFT);
tx1.setTextColor(Color.WHITE);
tx1.setTextSize(15);
t=t+1;
TextView tx2=new TextView(this);
tx2.setText(ar[t].toString());
tx2.setGravity(Gravity.LEFT);
tx2.setTextColor(Color.WHITE);
tx2.setTextSize(15);
t=t+1;
TextView tx3=new TextView(this);
tx3.setText(ar[t].toString());
tx3.setGravity(Gravity.RIGHT);
tx3.setTextColor(Color.WHITE);
tx3.setTextSize(15);
tx3.setWidth((int)(display.getWidth()/4));
tx.setWidth((int)(display.getWidth()/4));
tx1.setWidth((int)(display.getWidth()/4));
tx2.setWidth((int)(display.getWidth()/4));
newRow.addView(tx);
newRow.addView(tx2);
newRow.addView(tx1);
newRow.addView(tx3);
newRow.setId(t);
tbl.addView(newRow);
}
}
}
catch(Exception e){
pg.dismiss();
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Toast.makeText(this,"Network not available!.... ", Toast.LENGTH_LONG).show();
}
};
Add this line to where ever you want to dismiss your dialog.
if(pg.isShowing())pg.dismiss();
You are closing the ProgressDialog on Exception of Try clause
catch(Exception e){
pg.dismiss();
handler.sendEmptyMessage(0);
}
That's why without Exception this won't close
replace this :
catch(Exception e){
pg.dismiss();
handler.sendEmptyMessage(0);
}
to this :
catch(Exception e){
handler.sendEmptyMessage(0);
}
pg.dismiss();
try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
Sample code:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
//Show UI
//Start your progress bar
showProgress();
}
#Override
protected Void doInBackground(Void... arg0) {
// do your bg process
return null;
}
#Override
protected void onPostExecute(Void result) {
//Show UI
//dismiss your progress bar
hideProgress();
}
};
task.execute((Void[])null);
Show and hide progress dialog code
public void showProgress() {
progressDialog = ProgressDialog.show(this, "",
"Loading. Please wait...");
progressDialog.setCancelable(false);
}
public void hideProgress() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
I have go through your code, your progress dialog will exit if and only if your program throws an exception. put it out side of the catch block(after the catch block)
following code
catch(Exception e){
pg.dismiss();
handler.sendEmptyMessage(0);
}
should be changed to
catch(Exception e){
handler.sendEmptyMessage(0);
}finally{
pg.dismiss();
}
if above is not working try to shift the finally block to inside the thread's run method as shown in following..
Thread dt= new Thread(new Runnable()
{
public void run()
{
try
{
String addr=Util.url;
URL url = new URL(urlname);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String x = "";
String total = "";
int i=0;
ArrayList<String> content = new ArrayList();
while((x = r.readLine()) != null)
{
content.add(x);
}
in.close();
r.close();
ar= content.toArray(new String[content.size()]);
}
catch(Exception e1){
handler.sendEmptyMessage(0);
}finally{
pg.dismiss();
}
}
});
Use an AsyncTask and move all the network related code in doInBackground(). Show the ProgressDialog in onPreExecute() of AsyncTask and hide it in onPostExecute().
public class DownloadTask extends AsyncTask<String, Void, Response> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog(R.string.please_wait);
}
#Override
protected Response doInBackground(String... params) {
try {
// Do the network stuff here
} catch (Exception ex) {
// Handle exception
}
return result;
}
#Override
protected void onPostExecute(Response result) {
super.onPostExecute(result);
hideProgressDialog();
// Do the response handling here
}
}
private void showProgressDialog(int resId) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.setMessage(getString(resId));
} else {
progressDialog = ProgressDialog.show(this, "", getString(resId), false);
}
}
private void hideProgressDialog() {
try {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage(), ex);
}
}
Hope it helps.
I finally found the solution. I preferred to go for threads since the data to fetch from the server is huge and need to be dynamically assigned to fields.
Thread thread = new Thread() {
public void run () {
try
{
pg.show();
//long running task
}
catch(){
}
handler.post(new Runnable() {
#Override
public void run() {
//code for Update UI after the long running task
// dismiss the progress dialog on UI thread
pg.dismiss();
}
});
}
};
thread.start();

Android, how to display a dialog from error of a try catch?

In my app I connect to a website to collect some information at start with a AsyncTask, using a try catch, from here I can display in my catlog the error if any at connection, but I have been trying with out luck to show a dialog displaying the connection failure with options to reconnect or quit, please check my code and tell me what I'm doing wrong or an idea of how to accomplish this
//this is our download file asynctask
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsiteaddress");
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream webs = entity.getContent();
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(webs, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
webs.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
webResult resultRow = new webResult();
//infotodownload
arrayOfWebData.add(resultRow);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
// this is the line of code that sends a real error message to the
// log
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
// this is the line that prints out the location in
// the code where the error occurred.
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d(LOG_TAG,progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
//our progress bar settings
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("Conectando al Servidor");
mProgressDialog.setMessage("Cargando informacion...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
EDIT:
then I have try adding the next code as of suggested by Arun
catch (Exception e) {
// this is the line of code that sends a real error message to the
// log
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
// this is the line that prints out the location in
// the code where the error occurred.
e.printStackTrace();
return "ERROR_IN_CODE";
}
return null; // if I place here return "ERROR_IN_CODE" it calls the dialog but it gets always called so I don't need it here
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
if(unused.equals("ERROR_IN_CODE")){ //I get a system crash here!
errornote();
}
}
}
public void errornote() {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("No se a podido descargar la informacion de los medios, deseas reintentarlo, o salir?").setCancelable(false)
.setPositiveButton("Conectar de Nuevo", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
new DownloadFileAsync().execute();
}
})
.setNegativeButton("Salir", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
finish();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Error en la Conexion!");
// Icon for AlertDialog
alert.setIcon(android.R.drawable.ic_dialog_alert);
alert.show();
}
but not working either, my app crashes in the if statement line in onPostExecute. I still need help.
Since you are returning a String object from the protected String doInBackground(String... aurl) return some custom Error String from the catch block and access it in the protected void onPostExecute(String unused). Check if the returned String object is the Custom Error String and show the dialog in protected void onPostExecute(String unused) but only after dismissing the progressDialog i.e. after this line dismissDialog(DIALOG_DOWNLOAD_PROGRESS); show the error dialog.
EDIT
When the control enters the Catch block return some simple String like the one you used "ERROR_IN_CODE".
catch (Exception e) {
// this is the line of code that sends a real error message to the
// log
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
// this is the line that prints out the location in
// the code where the error occurred.
e.printStackTrace();
return "ERROR_IN_CODE";
}
And in the onPostExecute(String unused) check for the following
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
if(unused != null && unused.equals("ERROR_IN_CODE")){
showDialog(SOME_DIALOG_TO_SHOW_ERROR);
}
}
Try calling your activities runOnUiThread() method
activity.runOnUiThread(new Runnable() {
public void run() {
//your alert dialog builder here
});
you are not using the builder to create AlertDialog
remove the line builder.show() and add
AlertDialog alert = builder.create();
alert.show();
I will also recommend that do the UI updates through progressUpdate() or preExecute() and 'postExecute()' of the asyc task.
Implementation
#ReactMethod
public void showCustomAlert(String msg){
final String message = msg;
this.reactContext.runOnUiQueueThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder myDialogBox = new AlertDialog.Builder(reactContext.getCurrentActivity());
myDialogBox.setTitle(Html.fromHtml("<font color='#0037FF'>Konnect</font>"));
myDialogBox.setMessage(message);
myDialogBox.setCancelable(true);
myDialogBox.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
AlertDialog alertDialog = myDialogBox.create();
if (Build.VERSION.SDK_INT <= 23) {
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}else {
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
}
alertDialog.show();
WindowManager.LayoutParams wmlp = alertDialog.getWindow().getAttributes();
wmlp.gravity = Gravity.TOP | Gravity.LEFT;
wmlp.x = 25; //x position
wmlp.y = 450; //y position
wmlp.height = 380;
alertDialog.show();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
}
});
}

Prompted for Bluetooth PIN when connecting to already paired device on Android

I am developing an Android app to connect to a simple device that supports the bluetooth serial port profile (SPP). I am able to successfully connect and exchange data, but each time I connect the user is prompted to enter the PIN for the device.
In the bluetooth settings I can see that the device is 'paired by not connected'.
The prompt is an issue because if the user is not quick enough in entering the PIN, the socket connect times out and the user must try again.
Relevant bits of code below...
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scanlayout);
...
_Context = this;
_ActivityCreated = true;
_ReceivedText = (TextView)findViewById(R.id._Scan_Results);
_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
_BluetoothDevice = _BluetoothAdapter.getRemoteDevice(_DeviceAddress);
_BusySpinner = ProgressDialog.show(_Context, "", "Connecting to scanner...");
new ConnectToScannerTask().execute(_BluetoothDevice);
}
private final Handler scanReceivedHandler = new Handler()
{
#Override
public void handleMessage(Message message)
{
String receivedText = (String)message.obj;
_ReceivedText.setText(receivedText);
}
};
private class ConnectToScannerTask extends AsyncTask<BluetoothDevice, Void, InputStream>
{
#Override
protected InputStream doInBackground(BluetoothDevice... params)
{
BluetoothDevice device = params[0];
try
{
_Socket = device.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
_BluetoothAdapter.cancelDiscovery();
_Socket.connect();
return _Socket.getInputStream();
}
catch (IOException e)
{
Log.d("ScanActivity.ConnectToScannerTask.doInBackground", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(final InputStream result)
{
_BusySpinner.dismiss();
if (result == null)
{
_ReceivedText.setText("Failed to connect to scanner.");
return;
}
Thread thread = new Thread()
{
#Override
public void run()
{
byte[] buffer = new byte[1024];
try
{
while (_ActivityCreated)
{
Arrays.fill(buffer, (byte) 0);
int bytesRead = result.read(buffer);
if (bytesRead > 0)
{
Message message = scanReceivedHandler.obtainMessage(1, new String(buffer));
message.sendToTarget();
Log.e("ScanActivity", "Received: " + new String(buffer));
}
if (bytesRead < 0)
{
break;
}
}
Message message = scanReceivedHandler.obtainMessage(1, "End of Stream");
message.sendToTarget();
Log.e("ScanActivity", "End of Stream");
}
catch (Exception e)
{
Message message = scanReceivedHandler.obtainMessage(1, "Connection to scanner lost");
message.sendToTarget();
Log.e("ScanActivity", e.getMessage());
}
try
{
_Socket.close();
}
catch (IOException e)
{
Log.e("ScanActivity", e.getMessage());
}
}
};
thread.start();
}
}
As long as the user is quick about entering the PIN, the connect succeeds and I can receive data. My hunch is that I am missing a setup step. I'm not that familiar with the specifics of BT, though, so I am not sure if this might be an issue where the device is forcing the PIN to be entered?
This might be a problem with the remote device that does not keep the device bonded, (meaning storing the link key to be used in subsequent connect) that will result in re-pairing each time and requiring the PIN to be entered.
Android should typically store the bonding information once it has paired successfully.

Categories

Resources