AsyncTask in onCreate method - android

i have a simple application that plays online radio. for showing the title from online php service i use AsyncTask and call it from onCreate method. in android 4 everythin is OK, but in android 2 it's crushed with error
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
then in internet i found, that i must use a code like
new Thread(new Runnable() {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//my code
}
});
}
}).start();
but after i using this tip, a can't see any button and text views in my android 4 and android 2 versions. this is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//thread for update title every second
new Thread(new Runnable() {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
while(true) {
try {
new ShowTitle()
.execute("http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm");
Thread.sleep(1000);
} catch (InterruptedException e) {
String tag = "Update title";
Log.e(tag, "Update title crashed", e);
}
}
}
});
}
}).start();
}
//get title string from online source
private String getMusicTitle(String url) {
Document doc = null;
String title = "Music Title";
try {
url = "http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm";
InputStream input = new URL(url).openStream();
doc = Jsoup.parse(input, "CP1251", url);
title = doc.body().text();//doc.select(".products_name").first().text();
} catch (IOException e) {
Log.e(TAG, "Failed to load HTML code", e);
Toast.makeText(this, "Failed to load title", Toast.LENGTH_SHORT).show();
}
return title;
}
//class for show the audio title
private class ShowTitle extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return getMusicTitle(urls[0]);
}
protected void onPostExecute(final String result) {
lblMusicName.setText(result);
}
}
EDIT: (my working code)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ShowTitle()
.execute("http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm");
}
private String getMusicTitle(String url) {
Document doc = null;
String title = "Music Title";
try {
url = "http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm";
InputStream input = new URL(url).openStream();
doc = Jsoup.parse(input, "CP1251", url);
title = doc.body().text();
} catch (IOException e) {
Log.e(TAG, "Failed to load HTML code", e);
title = "Failed to load title";
}
return title;
}
private class ShowTitle extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
while (true) {
String str = getMusicTitle(urls[0]);
publishProgress(str);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
String tag = "Update title";
Log.e(tag, "Update title crashed", e);
}
}
}
protected void onProgressUpdate(String... result) {
lblMusicName.setText(result[0]);
}
}

In here :
try {
//....your code here
} catch (IOException e) {
Log.e(TAG, "Failed to load HTML code", e);
Toast.makeText(this, "Failed to load title",
Toast.LENGTH_SHORT).show(); //<<< this line
}
you are trying to show Toast Message from doInBackground (from non-ui Thread). use onPostExecute for showing Toast Message or updating UI according to result returned from doInBackground
and second issue is here:
while(true) {
try {
...
Thread.sleep(1000); //<<< here calling Thread.sleep on Main UI Thread
} catch (InterruptedException e) {
String tag = "Update title";
Log.e(tag, "Update title crashed", e);
}
this will always freeze Ui Thread for after AsyncTask execution . so will need to move Thread.sleep(1000) outside runOnUiThread code block

runOnUiThread and AsyncTask are two different things. You are using it in a wrong way.
Try it like this:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ShowTitle().execute("http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm");
}
//get title string from online source
private String getMusicTitle(String url) {
Document doc = null;
String title = "Music Title";
try {
url = "http://info.radiostyle.ru/inc/getinfo.php?getcurentsong=20383&mount=lezgifm";
InputStream input = new URL(url).openStream();
doc = Jsoup.parse(input, "CP1251", url);
title = doc.body().text();//doc.select(".products_name").first().text();
} catch (IOException e) {
Log.e(TAG, "Failed to load HTML code", e);
title = "Failed to load title";
}
return title;
}
//class for show the audio title
private class ShowTitle extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
String str = getMusicTitle(urls[0]);
while(true) {
publishProgress(str);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
String tag = "Update title";
Log.e(tag, "Update title crashed", e);
}
}
return str;
}
#Override
protected void onProgressUpdate(String... progress) {
if(returnVal.startsWith("Failed")) {
Toast.makeText(this, returnVal, Toast.LENGTH_SHORT).show();
} else {
lblMusicName.setText(result);
}
}
}
You must do all the UI related task in onProgressUpdate

Related

Parse a json string from url and store it in empty string

Im trying to parse a json string that is exist in a online server and store in an empty string like this String data = ""; but when i try to parse it and i see the log i see that the response from the server show all the json code (brackets and quotes and jsonobject) when i only need it to parse one specific string to be stored in the empty string. here are the json:
{
"main1": {"bnl":"code"}
}
the httphanlder
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
and this is the mainactivity
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
private NativeExpressAdView mNativeExpressAdView;
// URL of object to be parsed
// This string will hold the results
private String TAG = MainActivity.class.getSimpleName();
String data = "";
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://yourdomain.com/test.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
new GetAd().execute();
LinearLayout layout = (LinearLayout)findViewById(R.id.layoutId);
// Create a native express ad. The ad size and ad unit ID must be set before calling
// loadAd.
mNativeExpressAdView = new NativeExpressAdView(MainActivity.this);
mNativeExpressAdView.setAdSize(new AdSize(AdSize.FULL_WIDTH, 90));
mNativeExpressAdView.setAdUnitId(data);
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
// Start loading the ad.
mNativeExpressAdView.loadAd(adRequestBuilder.build());
// Add the NativeExpressAdView to the view hierarchy.
layout.addView(mNativeExpressAdView);
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "alltext");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFav");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "today");
startActivity(today);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
void startTheThingWithData(){
//Here data has value
Log.e(data, data);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetAd extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject dataa = jsonObj.getJSONObject("main1");
String ad = dataa.getString("bnl");
data = ad;
Log.e(TAG, "Response from url: " + ad);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
startTheThingWithData();
}}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
this is what it shows in the log
E/MainActivity: Response from url: {
"main1": {
"bnl":"code"
}
}
You are printing the jsonStr while the content you want is the data.
AyncTasks runs async, meaning that code runs paralalel: check this simple sample for better undestanding.
String b = "s";
void onCreate(Bundle b) {
afterAsyncHere();
new Task().execute();
afterAsyncHere();
}
void afterAsyncHere() {
Log.e("onCreate", b);
}
class Task extends AsyncTask {
Object doInBackground(Object ... args) {
b ="value b";
try { Thread.sleep(1000); }catch(Exception e) {}
}
void onPostExecute(Object r) {
afterAsyncHere();
}
}
}
The above code will call afterAsyncHere() three times, two in onCreate and one in onPostExecute. The printed result will be:
"s" from onCreate
"s" from onCreate
"value b" from onPostExecute
Note that in onPostExecute your Task was concluded and the value of 'b' was updated.
While in the second call (right after starting the task) the value is still "s".
String ad = dataa.getString("bnl");
data = ad;
Log.e(TAG, "Response.data from url: " + data);
The actual code that would works is:
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// This string will hold the results
String data = "";
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://yourdomain.com/test.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
new GetAd().execute();
}
void startTheThingWithData(){
mNativeExpressAdView.setAdUnitId(data);
//Here data has value
Log.e(data, data);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetAd extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject dataa = jsonObj.getJSONObject("main1");
String ad = dataa.getString("bnl");
data = ad;
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
startTheThingWithData();
}}
Note I added a callback method on the Activity and called it from the onPostExecute

AsyncTask is finishing doInBackground() before the methods inside of it are finished

I'm using Vk Sdk. I have created AsyncTask to load data from the server in background. However, it turns out that doInBackground() is finished before the tasks inside of it are done. The code is below:
#Override
protected Void doInBackground(Void... params) {
Log.v(TAG, "Before Loading in Background");
VKRequest request = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, "-100177655", VKApiConst.OFFSET, "2"));
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
String jsonData = response.responseString;
Log.v(TAG, "json is ready");
try {
Log.v(TAG, "before parsing");
parsePostsData(jsonData);
Log.v(TAG, "after parsing");
} catch (JSONException e) {
Log.v(TAG, "EXCEPTION is thrown");
e.printStackTrace();
}
}
});
Log.v(TAG, "Finished Background Tasks");
return null;
}
I suspect that request.executeWithListener(...) is creating another thread and doing necessary work there. Therefore, AsyncTask thinks that work in his thread is finished. However, I'm not sure. There is nothing in the documentation for this method.
Another question is on which thread onComplete(...) method is running when it is called? On main or the same separate thread created by request?
Any help is appreciated :)
Base on your code, you have 2 different Threads called.
AsynTask is a background thread which will execute first. Then you called VKRequest executeWithListener which will created another thread in doInBackground().
To archive this in single Thread, you should change your execute method to executeSyncWithListener() in VKRequest
#Override
protected Void doInBackground(Void... params) {
Log.v(TAG, "Before Loading in Background");
VKRequest request = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, "-100177655", VKApiConst.OFFSET, "2"));
request.executeSyncWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
String jsonData = response.responseString;
Log.v(TAG, "json is ready");
try {
Log.v(TAG, "before parsing");
parsePostsData(jsonData);
Log.v(TAG, "after parsing");
} catch (JSONException e) {
Log.v(TAG, "EXCEPTION is thrown");
e.printStackTrace();
}
}
});
Log.v(TAG, "Finished Background Tasks");
return null;
}
Hope this will help!
Do something like this:
#Override
protected Void doInBackground(Void... params) {
Log.v(TAG, "Before Loading in Background");
VKRequest request = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, "-100177655", VKApiConst.OFFSET, "2"));
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
String jsonData = response.responseString;
Log.v(TAG, "json is ready");
// YOUR CUSTOM CALLBACK
new Thread(new myCustomRunnable(jsonData)).start();
try {
Log.v(TAG, "before parsing");
parsePostsData(jsonData);
Log.v(TAG, "after parsing");
} catch (JSONException e) {
Log.v(TAG, "EXCEPTION is thrown");
e.printStackTrace();
}
}
});
Log.v(TAG, "Finished Background Tasks");
return null;
}
where myCustomRunnable is a class that implements 'Runnable' interface.
public class myCustomRunnable implements Runnable{
private String msg ="";
public OToast(String msg) {
this.msg = msg;
}
#Override
public void run() {
//here do anything you want
Log.v("mylog",msg);
//or even execute code in main thread:
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code
}
});
}
}
Or even simpler:
#Override
protected Void doInBackground(Void... params) {
Log.v(TAG, "Before Loading in Background");
VKRequest request = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, "-100177655", VKApiConst.OFFSET, "2"));
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
String jsonData = response.responseString;
Log.v(TAG, "json is ready");
// EXECUTE CODE IN MAIN UI THREAD:
final String final_json = jsonData;
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code
textview.setText(final_json);
}
});
try {
Log.v(TAG, "before parsing");
parsePostsData(jsonData);
Log.v(TAG, "after parsing");
} catch (JSONException e) {
Log.v(TAG, "EXCEPTION is thrown");
e.printStackTrace();
}
}
});
Log.v(TAG, "Finished Background Tasks");
return null;
}

Check if URL exists or not on Server

This is my code which I am using to verify, URL exists or not on Server, but always getting not exist however link is alive
Where I am doing mistake in my code, why I am always getting "doesnot exist !"
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
boolean bResponse = exists(customURL);
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
You will get Network On Main Thread Exception
Look at NetworkOnMainThreadException
so your method always returns false because of:
catch (Exception e) {
e.printStackTrace();
return false;
}
quick fix:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
MyTask task = new MyTask();
task.execute(customURL);
}
private class MyTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
boolean bResponse = result;
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
}
}
With a ScheduledThreadPoolExecutor:
but remember to shut down it!!
public class MainActivity extends Activity {
String customURL;
String msg = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(customURL).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
msg = "File exist!";
}else{
msg = "File does not exist!";
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e) {
e.printStackTrace();
return;
}
}
}, 0,10000, TimeUnit.MILLISECONDS);
}
Change your exists() to this
public boolean exists(String url){
HttpURLConnection huc = ( HttpURLConnection ) url.openConnection ();
huc.setRequestMethod ("GET"); //OR huc.setRequestMethod ("HEAD");
huc.connect () ;
int code = huc.getResponseCode() ;
System.out.println(code);
if(code==200)
return true;
else
return false;
}
Use if(bResponse) instead of if(bResponse==true)
you can use the follow code to try.
final String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
URL url = new URL(customURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");
con.connect();
Log.i(TAG, "con.getResponseCode() IS : " + con.getResponseCode());
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
Log.i(TAG, "Sucess");
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "fail");
}
}
}.start();
Reason: After android 2.3, you can't perform a networking operation on its main thread,
if you do so, there will be can exception and you can't get the right result.
So if you want the application to perform a networking operation, you can use another Thread to do it.
I use this code to verify url alive. I have tested this code with image url
Example:
url = "https://ima.vn/wp-content/uploads/2017/11/ima-sofa-titan-trungkinh-1-of-3.jpg"
message = "Image url";
public void assertUrlalive(String url, String message) {
try {
URL myUrl = new URL(url);
HttpURLConnection huc = (HttpURLConnection) myUrl.openConnection();
assertEquals(huc.getResponseCode(), 200, message);
} catch (IOException e) {
e.printStackTrace();
logger.error("Connection Err: " + e.getMessage());
}
}

Toast is not displaying in catch block

Hi ! I'm trying to display a mesage when the network is off or the server is not responding. My messsage is visible in LOG but does not show on screen (is not toasted). I have a sample code which works fine but my code is not.
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {}
public static AgAppHelperMethods getInstance()
{
if(instance == null)
{
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl ()
{
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl)
{
String _node,_element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list=doc.getElementsByTagName("*");
_node=new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
for (int i=0;i<list.getLength();i++)
{
Node value=list.item(i). getChildNodes().item(0);
_node=list.item(i).getNodeName();
_element=value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
}
}
How can I show my toast message on the screen? Thanks.
You can't do that. You can do something like this
boolean flag=true;//take globally
//working thread
.
.
.
catch (Exception e)
{
flag=false;
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
Once your working thread gets over check the flag value and show the Toast.
//Main Thread
if(!flag)
Toast.makeText(getApplicationContext(), "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
note: If you still want to show in NonUI Thread then you can use Handler or runOnUiThread()
Try this
Toast.makeText(AgAppHelperMethods.this, "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
make sure you pass right context, for example:
Toast.makeText(MyActivity.this , "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
I'm surprised this hasn't been answered yet. It appears to me all you need to do is run the Toast on the UI thread. Thus, in your catch block:
runOnUiThread(new Runnable(){
Toast.makeText(...);
});
Declare globally write it in oncreate and only show in catch block.
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
toast = Toast.makeText(ActivityDeliverables.this, "Server is not working, please contact with admin.", Toast.LENGTH_LONG);
}
try{
} catch (Exception e) {
toast.show();
}
This method is working for me if someone still need help:
getActivity().runOnUiThread(Runnable { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show() })
check this its working fine for me
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_finder);
show();
}
public void show()
{
try
{
throw new ArrayIndexOutOfBoundsException() ;
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "HI", Toast.LENGTH_LONG).show();
}
}
}

How to start and finish progressBar dynamically in android

When I skip second activity class from first activity class, I will start imageprocessing on certain image in second activity and then until new image comes to screen I wnt to start progress bar and then finish when the new image comes to screen. How can I do this ?
Use ProgreaaDialog and AsyncTask. you wil get your soultion
Use AsyncTask in doBackInGroundProcess do image processing. and in doPostExecute() exit or cancel the progress dialog
have a look on the sample code.
To start AsyncTsk use new ProgressTask().execute(null); from the activity where you want to do image processing.
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
Have a look here
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
Here is a method which when called starts a progressbar
private void downloadText(String urlStr) {
final String url = urlStr;
progressDialog = ProgressDialog.show(this, "", "Trying to register...");
Log.i("First string", urlStr);
try{
new Thread () {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
try{
msg = Message.obtain();
msg.what=1;
}catch(Exception e)
{
}
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (Exception e) {
//////////////////////////////////////
e.printStackTrace();
}
try{
messageHandler.sendMessage(msg);
}catch(Exception e)
{
}
}
}.start();
}catch(Exception e)
{
}
}
and here is the handler code
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
try{
super.handleMessage(msg);
switch (msg.what) {
case 1:
{
break;
}
}
progressDialog.dismiss();
}catch(Exception e)
{
}
}
};
Try this way
first Intialize your ProgressDialog
progressDialog = ProgressDialog.show(this, "", "Trying to ...");
then start a new thread in which you can write your code which needs to be executed
and finally in the handler handle the code and end the progessDialog

Categories

Resources