Android progress dialog not closing - java

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();

Related

Asking the user for a URL to receive a JSON

Just as a practicing exercise i'm trying to make an app that fetches a JSON from a URL.
I found the following code in other thread here in stackoverflow and it works just fine. My problem is that the URL is hardcoded, and i need it to be an input by the user. What should i change/add?
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("Url address here");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response..... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
This is the thread where i got that code from:
Get JSON Data from URL Using Android?
Create a constructor in your async Task
private class JSONTask extends AsyncTask<String, String, String> {
String url;
public JSONTask(String url){
this.url=url;
}
use the url string in place of params[0]
And wherever you call your async task do it like this
new JSONTask(textView.getText()).execute()
This should solve it.
Else you can directly use the do in background variable params.
So the problem is that you are using a TextView. TextView does not recieve inputs.
EditText does.
Make these Changes:
TextView txtJson;
In your OnCreate change this:
txtJson = (EditText) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute(txtJson.getText());
}
});
Now in your xml file change the Button to EditText.
Hope this helps.

How do i set an ImageView to show an image from an image url?

When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.

Returning a bitmap file from AsyncTask freezes UI thread

I have created a simple Activity. The activity is responsible for downloading data from parse.com database and populating a linear layout. In the process, I am dynamically creating the linear layout with TextViews and ImageViews according according to the content.
The problem is that, whenever I try to download an image, I use as AsyncTask Downloading class, which results in slowing down the UI thread! I am currently trying to return the bitmap file from the AsyncTask Image downloading class using: returnedBitmap = new LoadImage().execute(src).get(); which might be responsible for slowing down the UI thread. I have to do this because the caller method geneterImageView will return an imageview when it receives the bitmap file.
The complete Activity code:
public class MainActivity extends ActionBarActivity {
ArrayList<String> heightList = new ArrayList<String>();
ArrayList<String> reversedList = new ArrayList<String>();
ImageView imageView1;
Bitmap bitmap;
RelativeLayout parent_layout;
ParseObject user;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// imageView1 = (ImageView)findViewById(R.id.imageView1);
parent_layout = (RelativeLayout) findViewById(R.id.parent_layout);
login("xyz#xyz.com", "xyz");
}
private void loopThroughArrayAndAttach(){
LinearLayout llInner = new LinearLayout(this);
llInner.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
parent_layout.addView(llInner);
for (int i = 0; i < heightList.size(); i++) {
if (hasNoImagess(heightList.get(i)) == true) {
// No images.
TextView myText = geneterTextView(heightList.get(i));
llInner.addView(myText);
// geneterTextView(heightList.get(i));
} else {
ImageView myImage = geneterImageView(heightList.get(i));
llInner.addView(myImage);
// geneterImageView(heightList.get(i));
}
}
}
public static boolean hasNoImagess(String contents){
Document doc = Jsoup.parse(contents);
Element element = doc.body();
Elements elements = element.select("img");
if (elements.isEmpty()) {
return true;
} else {
return false;
}
}
public ImageView geneterImageView(String imgContent){
// Will need to run via background thread - like aysnc
// Extract the image file via jsoup
// Insert it into a imagevieww
// Inser that into a layout.
Log.d("IN IMAGE ", " " + imgContent);
Document doc = Jsoup.parse(imgContent);
Elements img = doc.getElementsByTag("img");
Bitmap returnedBitmap = null;
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("src attribute is : " + src);
// new DownloadImageTask((ImageView)
// findViewById(R.id.imageView1)).execute(src);
try {
returnedBitmap = new LoadImage().execute(src).get();
// imageView1.setImageBitmap(returnedBitmap);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageView iv = new ImageView(this);
iv.setImageBitmap(returnedBitmap);
return iv;
}
public TextView geneterTextView(String textContent){
// Will need to run via background thread.
Log.i("In TEXT ", " " + textContent);
TextView tv = new TextView(this);
tv.setText(Html.fromHtml(textContent));
return tv;
}
// to download images
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
protected Bitmap doInBackground(String... args){
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image){
if (image != null) {
} else {
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
// to login to parse
private void login(final String username, String password){
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e){
if (e == null) {
// if login sucess
// Start intent
// loginSuccess();
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
CloudCallStudentPosts(user);
} else {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
}
});
}
// //to get data from parse
public void CloudCallStudentPosts(ParseObject s){
setRichStory(s);
}
private void setRichStory(ParseObject s){
// Simialr to setStory, once implemented delete setStory()
new AddStoryAsync(s).execute();
}
class AddStoryAsync extends AsyncTask<Void, Object, Void> {
private static final String TAG = "LazyListView";
ParseObject s;
public AddStoryAsync(ParseObject s) {
this.s = s;
Log.w("In richStory", "ParseObject Id: " + s.getObjectId());
}
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... unused){
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userid", this.s.getObjectId());
params.put("skip", 0);
ParseCloud.callFunctionInBackground("studentsPosts", params, new FunctionCallback<List<List<ParseObject>>>() {
#Override
public void done(List<List<ParseObject>> postList, com.parse.ParseException arg1){
if (postList == null) {
} else {
if (postList.size() > 0) {
// CustomWebView cwb;
for (int i = 0; i < postList.size(); i++) {
// final Post post = new Post();
if (postList.get(i).get(0).get("htmlContent") == null) {
}
if (postList.get(i).get(0).get("htmlContent") != null) {
Log.e("htmlContent parse", postList.get(i).get(0).get("htmlContent").toString());
// Parse HTML String using JSoup library
String HTMLSTring = postList.get(i).get(0).get("htmlContent").toString();
Document html = Jsoup.parse(HTMLSTring);
Elements paragraphs = html.getElementsByTag("p");
for (org.jsoup.nodes.Element paragraph : paragraphs) {
String paragraphText = paragraph.toString();
Log.e("paragraphText", paragraphText);
heightList.add(paragraphText);
}
loopThroughArrayAndAttach();
}
}
}
}
}
});
return (null);
}
#Override
protected void onProgressUpdate(Object... object){
Log.w("onProgressUpdate ", " " + object[0].getClass());
Log.w("adding to arrayPostList ", " " + object[0].getClass());
}
#Override
protected void onPostExecute(Void unused){
}
}
}
Is there any substitute for getting the bitmap from the AsyncTask and set it in the imageview? Should there be a logical alteration in the approach?
try this :
dont call get() #praveen. instead pass the imageview Reference in the constructor
WorkerThread mWorkerThread = new WorkerThread(mImageView);
mWorkerThread.execute(src);
private class WorkerThread extends AsyncTask<String, String, Bitmap> {
private WeakReference<ImageView> imageViewReference;
public WorkerThread(ImageView imageView) {
super();
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... args) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null && imageViewReference.get() != null) {
imageViewReference.get().setImageBitmap(result);
}
}
}
Don't call get() method on AsyncTask it makes main thread to wait for AsyncTask to complete. If you really want to start something only after AsyncTask completes put that into onPostExecute() of your AsynTask
As others have mentioned, your code has several design flaws which makes it difficult to provide you a solution to your problem.
The whole purpose of an AsyncTask is to execute on a background thread. Executing networking and bitmap processing on the main thread will never work. You must refactor your code to accommodate this. Consider the following solution to this particular problem at least:
// to download images
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... args) {
String imgContent = args[0];
Document doc = Jsoup.parse(imgContent);
Elements img = doc.getElementsByTag("img");
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("src attribute is : " + src);
try {
return BitmapFactory.decodeStream((InputStream) new URL(src).getContent());
} catch (Exception e) {
// log
}
}
return null;
}
protected void onPostExecute(Bitmap b) {
ImageView iv = new ImageView(MainActivity.this);
iv.setImageBitmap(b);
llInner.addView(iv);
}
}
You can then do something like:
for (int i = 0; i < heightList.size(); i++) {
new LoadImage(heightList.get(i)).execute();
}
However, this may not be desirable depending on how many AsyncTasks you end up creating. But this is the idea.

Running multiple Asyntask simultaneously

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.

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));
}
});
}

Categories

Resources