I want to use progress bar... but As I searched, progress bar can not use with Asynctask.get.But I have to use .get and progress in Asynctask.
I made very simple source.
How can I changed to show progress bar in main thread??
I want to use both get method and ui progress.
public void onCreate(Bundle savedInstanceState) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AAA asyncTask = new AAA();
try {
((AAA) asyncTask).execute(null, null, null,null).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class AAA extends AsyncTask<Object, String, Object> {
private ProgressDialog progDailog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog = new ProgressDialog(ViewTestActivity.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected Object doInBackground(Object... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return params;
}
#Override
protected void onPostExecute(Object result) {
progDailog.dismiss();
}
}
Please help me.
Thanks!!
Do it before calling AsyncTask
private ProgressDialog progDailog = null;
public void onCreate(Bundle savedInstanceState) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AAA asyncTask = new AAA();
try {
progDailog = new ProgressDialog(ViewTestActivity.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
((AAA) asyncTask).execute(null, null, null,null);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class AAA extends AsyncTask<Object, String, Object> {
#Override
protected Object doInBackground(Object... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return params;
}
#Override
protected void onPostExecute(Object result) {
progDailog.dismiss();
}
}
I don't know if there's a standard answer, but I've just done something very similar by setting up listener on the main thread, and sending progress messages to the listener from the async task - actually in my case it was loading asynchronously from a database. Works fine for me.
Try with this :
private ProgressDialog progDailog;
public void onCreate(Bundle savedInstanceState) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
progDailog = new ProgressDialog(ViewTestActivity.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
AAA asyncTask = new AAA(progDialog);
try {
((AAA) asyncTask).execute(null, null, null,null).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class AAA extends AsyncTask<Object, String, Object> {
private ProgressDialog progressDialog;
public AAA (ProgressDialog progressDialog) {
this.progressDialog = progressDialog;
}
#Override
protected Object doInBackground(Object... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return params;
}
#Override
protected void onPostExecute(Object result) {
progressDialog.dismiss();
}
}
you should update your progress bar percentage in onProgressUpdate
See this example AsyncTask with progress bar
Related
I'm a newbie in android development. I have to integrate web service in my app but it doesn't work. can someone help me out to resolve it.
Following is the source code
public class Registration extends Activity {
EditText edfnm,edlnm,edmobile,edemail,edpass;
Button b1;
TextView tv1;
private DefaultHttpClient httpclient;
private HttpPost httppost;
private ArrayList<NameValuePair> lst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
edfnm=(EditText)findViewById(R.id.edfirst);
edlnm=(EditText)findViewById(R.id.edlast);
edmobile=(EditText)findViewById(R.id.edmobile);
edemail=(EditText)findViewById(R.id.edemail);
edpass=(EditText)findViewById(R.id.edpass);
b1=(Button)findViewById(R.id.btnreg);
tv1=(TextView)findViewById(R.id.textView1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
httpclient=new DefaultHttpClient();
httppost=new HttpPost("http://amwaveswellness.com/protocol_suggestion/webservice/register.php");
lst=new ArrayList<NameValuePair>();
lst.add(new BasicNameValuePair("first_name",edfnm.getText().toString()));
lst.add(new BasicNameValuePair("last_name",edlnm.getText().toString()));
lst.add(new BasicNameValuePair("mobile",edmobile.getText().toString()));
lst.add(new BasicNameValuePair("email",edemail.getText().toString()));
lst.add(new BasicNameValuePair("password",edpass.getText().toString()));
try {
httppost.setEntity(new UrlEncodedFormEntity(lst));
new add_data().execute();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class add_data extends AsyncTask<String, integer, String>{
String jsonstring;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
HttpResponse httpresponse=httpclient.execute(httppost);
jsonstring=EntityUtils.toString(httpresponse.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonstring;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
tv1.setText(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
});
}
When I run this code it returnsnull responce
Pl tell me what's going on and how to tackle it.
API request sample
This is a good example to achieve it.
https://www.simplifiedcoding.net/android-volley-tutorial-to-get-json-from-server/
go through it.
I'm trying to learn Android and when I was trying to parse HTML by using Jsoup, I get an error and my app stops. I have a button in my layout and when I click it I want the app to update the TextView and write HTML Page's title. Here is the code (necessary parts):
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Title().execute(new String[] {url}); // I have url of an html address as a string above
}
}
class Title extends AsyncTask <String, Void, String> {
String pageTitle;
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
pageTitle = doc.title();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pageTitle;
}
protected void onPostExecute (String... params) {
MainActivity.title.setText(params[0]);
}
}
When I click the button, it says "Unfortunately, App has stopped."
Can anybody tell me what I am doing wrong?
try this in doInBackground() :
{
String pageTitle;
Element ele;
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
t =doc.select("title");
pageTitle = t.text();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pageTitle;
}
I have an AsyncTask class which parse json data and inserts into an object, when I call it in normal activity classes it shows that data have been parsed but when I execute this on a class which extends Application then it gives zero result. Here is my class
public class AppGlobalData extends Application {
public ArrayList<YoutubeItem> gotItem= new ArrayList<YoutubeItem>();
private YouTubeParser parser;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
new ParserLoader().execute();
}
public class ParserLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.i("Succeed?", "Yes");
parser = new YouTubeParser(
"http://powergroupbd.com/youtube/getyoutubejson.php");
try {
gotItem = parser.parseInitiator();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public ArrayList<YoutubeItem> getGotItem() {
return gotItem;
}
public void setGotItem(ArrayList<YoutubeItem> gotItem) {
this.gotItem = gotItem;
}
}
I cant figure out the problem, can anyone help?
please be noted that this class runs and logs my String but doesnt parse data.
I think what might happen is that when new ParserLoader().execute(); it doing the work asynchronously. When your Activity load and call the getGotItem() the Asynctask might not have finished
I'm trying to develop an android app that could list all app and their cache's.
But I'm facing a problem that whenever I tap on generated list I'm getting force close because
java.lang.IllegalStateException: The content of the adapter has
changed but ListView did not receive a notification.
Make sure the content of your adapter is not modified from a background thread,
but only from the UI thread.
So I'm trying to convert my AsyncTask code to Thread Hadler, can any body please help me out with this problem. Here is my code
public class Messages extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msgList = (ListView) findViewById(R.id.MessageList);
applicationCacheSize = new ArrayList<Long>();
applicationPackageName = new ArrayList<String>();
applicationName = new ArrayList<String>();
cacheApplicationName = new ArrayList<String>();
details = new ArrayList<MessageDetails>();
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(Messages.this, "Loading..",
"Please Wait", true, false);
}// End of onPreExecute method
#Override
protected Void doInBackground(Void... params) {
for (ApplicationInfo packageInfo : packages)
{
try
{
Context mContext = createPackageContext(packageInfo.packageName, CONTEXT_IGNORE_SECURITY);
PackageManager pm = mContext.getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo( mContext.getPackageName(), 0);
} catch (final NameNotFoundException e) {
ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
appNames.add(applicationName);
appPackageName.add(packageInfo.packageName);
appCache.add(mContext.getCacheDir());
}
catch (NameNotFoundException e)
{
e.printStackTrace();
}
}
for(int i=0; i<appCache.size(); i++)
{
try {
final PackageManager pm = getPackageManager();
Method getPackageSizeInfo;
getPackageSizeInfo = pm.getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
getPackageSizeInfo.invoke(pm, appPackageName.get(i), new IPackageStatsObserver.Stub() {
#Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
final String title;
ApplicationInfo applicationInfo;
try {
applicationInfo = pm.getApplicationInfo(pStats.packageName, 0);
title = (String)((applicationInfo != null) ? packageManager.getApplicationLabel(applicationInfo) : "???");
MessageDetails Detail;
Detail = new MessageDetails();
Detail.setIcon(getPackageManager().getApplicationIcon( pStats.packageName ));
Detail.setName(title);
Detail.setSub("Cache Size -> "+(((pStats.cacheSize/1024) > 0)?(pStats.cacheSize/1024):"No Cache"));
details.add(Detail);
if((pStats.cacheSize) != 0 )
{
cacheApplicationName.add(title);
}
} catch (final NameNotFoundException e) {}
}
});
}
catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}// End of doInBackground method
#Override
protected void onPostExecute(Void result) {
CustomAdapter adapter = new CustomAdapter(details, Messages.this);
msgList.setAdapter(adapter);
pd.dismiss();
}// End of onPostExecute method
}.execute((Void[]) null);
}
}
Thanks in advance.
First, do not use detail = new Asyntasck. Create The Asynctask Class below and just use :
AsynTask myTask = new AsynTask();
myTask.execute();
Then your adapter is actually modified from a background thread (asynctask), exactly as the exception suggested. The solution is moving it to UI thread or simply wrapping it with runOnUiThread():
... ...
runOnUiThread(new Runnable() {
public void run() {
details.add(result) //use a foreach here
CustomAdapter adapter = new CustomAdapter(details, Messages.this);
adapter.notifyDataSetChanged();
msgList.setAdapter(adapter);
pd.dismiss();
}
}); // end of runOnUiThread
... ...
I can't explain why onPostExecute is not being called in my code. I have successfully used almost this exact code with a different app before. It prints 'onPreExecute' and the successful result of the JSON fetch from doInBackground just before return result; but then onPostExecute doesn't print anything - with the super call or not - and moreover doesn't return my string to the UI thread. Any ideas?
public class PrivateLoadFromServer extends AsyncTask<String, Integer, String> {
InputStream is = null;
String result = null;
String error_text="";
JSONObject j = null;
String url;
SQLiteOpenHelper helper;
CustomActivity activity;
private Context context;
private ProgressDialog dialog;
private int count;
String employee;
String text;
public PrivateLoadFromServer(CustomActivity activity,String employee,String url){
this.url=url;
this.employee=employee;
this.activity=activity;
}
#Override
protected void onPreExecute() {
system.out.println("onPreExecute");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("onPostExecute");
activity.setJSONResult(result);
/*
if(result!=null){
System.out.println("Task reported successful");
taskHandler.taskSuccessful(this.result);
activity.setJSONResult(this.result);
} else {
taskHandler.taskFailed();
}
*/
//return;
}
#Override
protected String doInBackground(String... params) {
System.out.println("Running aSyncTask");
// Successful code to get JSON result string from server omitted.
System.out.println("Raw at doInBackground: " + result);
return result;
EDIT: Should've posted this originally, I call it as an inner class in CustomActivity like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
helper=new DBHelper(this);
loadBasicData();
}
private void loadBasicData() {
// If you can encode all of these into one JSON Object, cool.
String url="*****" //Omitted URL.
String employee=null;
PrivateLoadFromServer syncTask = new PrivateLoadFromServer(this,employee,url);
syncTask.execute();
try {
syncTask.get(15000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("JSONResult at Activity:"+jsonResult); // jsonResult is null
}
}
public void setJSONResult(String result){
System.out.println("setJSONResult"+result);
this.jsonResult=result; // jsonResult is a field in the Activity.
}
Because you are calling get, the JSON result is also returned from this method (see the source code of AsyncTask.java. So you can call your method directly on the output.
try {
setJSONResult(syncTask.get(15000, TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
Check if your are explicitly cancelling AsyncTask somewhere in the code before it could postExecute.
onPostExecute() is called on the main UI thread. If its not getting called, it means your UI thread is blocked doing something else.