What is wrong with progress dialog in AsyncTask - android

Am using Async Task in my application to get response from web service using restful web service. My code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_page);
_mContext = this;
new JSONParserTask().execute();
}
asynctask class
private class JSONParserTask extends AsyncTask<Void, Void, ListAdapter >{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// dialog = new ProgressDialog(_mContext);
// dialog.setMessage("Loading...");
// dialog.show();
super.onPreExecute();
}
#Override
protected ListAdapter doInBackground(Void... arg0) {
ListAdapter adapter = null;
itemsList = new ArrayList<HashMap<String, String>>();
jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(Constants.JsonURL);
if(json == null){
Log.v(TAG, "----------- null");
return null;
}
try {
// Getting Array of Items
items = json.getJSONArray(TAG_ITEMS);
// looping through All items
for(int i = 0; i < items.length(); i++) {
JSONObject itemsObj = items.getJSONObject(i);
JSONObject products = null;
products = itemsObj.getJSONObject(TAG_PRODUCT);
Log.d(TAG,"product array "+products.toString());
JSONArray images = products.getJSONArray(TAG_IMAGES);
JSONObject imagesObj = images.getJSONObject(0);
Log.d(TAG, "......."+ imagesObj.getString(TAG_LINK));
String imageUrl = imagesObj.getString(TAG_LINK);
// Storing each json item in variable
String kind = itemsObj.getString(TAG_KIND);
String id = itemsObj.getString(TAG_KID);
String selfLink = itemsObj.getString(TAG_SELFLINK);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_KIND, kind);
map.put(TAG_KID, id);
map.put(TAG_SELFLINK, selfLink);
// adding HashList to ArrayList
itemsList.add(map);
}
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(_mContext, itemsList,
R.layout.list_item_row,
new String[] { TAG_KIND, TAG_SELFLINK }, new int[] {
R.id.name, R.id.mobile });
} catch(JSONException e){
e.printStackTrace();
}
return adapter;
}
#Override
protected void onPostExecute(ListAdapter adapter) {
lv.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// some action
}
});
//dialog.dismiss();
}
}
with this code every thing working fine without using progress dialog. If u found, the code related to progress dialog is commented in above class.
If i uncomment progress dialog code, am not getting any response from server. I have tried with debugging also but never get any idea to remove this error.
Can some one tell what wrong am doing here.

ok the reason for that is you are updating you are adapter in your doInBackground() method
adapter = new SimpleAdapter(_mContext, itemsList,
R.layout.list_item_row,
new String[] { TAG_KIND, TAG_SELFLINK }, new int[] {
R.id.name, R.id.mobile });
This code is related to the MAIN THREAD and shouldn't be called here in the background thread, remove it from here, and add it to the onPostExecute() , just pass an array list from the Background thread and do other UI related stuff in the onPostExecute()

Try this
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog= ProgressDialog.show(getApplicationContext(),"", getString(R.string.dialog_wait_message));
super.onPreExecute();
}
protected void onPostExecute(Void result) {
if(mProgressDialog!=null){
mProgressDialog.dismiss();
}
}

Try this one, rather
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog= ProgressDialog.show(getApplicationContext(),"", getString(R.string.dialog_wait_message));
super.onPreExecute();
}
#Override
protected ListAdapter doInBackground(Void... arg0){
//do your stuff here
}
#Override
protected void onPostExecute(Void result) {
if(mProgressDialog!=null && mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}

Try this
#Override
protected void onPreExecute() {
pd=new ProgressDialog(m_context);
pd.setTitle("Authenticating");
pd.show();
}
#Override
protected Void doInBackground(Void... args) {
//your stuff
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
}

Related

doInBackground() method in an AsyncTask doesn't work when the activity is being re-opened

In my Android app, I have an activity which executes an AsyncTask<Void, Void, Void> named Scan using this code: new Scan().execute();.
In the onPreExecute() method, it starts a progress dialog, on the doInBackground(Void... voids) method it scans a table from DynamoDB, and on the onPostExecute(Void aVoid) method, it dismisses the progress dialog, and views the results of the DB scan in a ListView using a custom BaseAdapter class.
When I open the activity, everything runs great, but when I press the back button, and enter the activity again, then only the onPreExecute() and the onPostExecute(Void aVoid) methods are being executed, while doInBackground(Void... voids) isn't being executed, so it just shows and dismisses the progress dialog, and nothing else is being viewed on the screen.
How can I fix this?
Code:
MessagesListAdapter messages;
ListView messagesLv;
public static ArrayList<Message> arrayList;
public static ProgressDialog progressDialog;
public static DynamoDBScanExpression dbScanExpression;
public static List<Message> messageList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
new Scan().execute();
}
private class Scan extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(TestActivity.this);
progressDialog.setTitle(name);
progressDialog.setMessage("Searching for messages...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
dbScanExpression = new DynamoDBScanExpression();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.EQ)
.withAttributeValueList(new AttributeValue().withS(MainActivity.msgId));
dbScanExpression.addFilterCondition("msgId", condition);
messageList = MainActivity.mapper.scan(Message.class, dbScanExpression);
arrayList = new ArrayList<Message>();
for (Message msg : messageList) {
if (msg.getUserId() == null || msg.getUserId().equals(MainActivity.userId)) {
msg.setMsgId(msg.getMsgId());
msg.setDate(msg.getDate());
msg.setTime(msg.getTime());
msg.setMessage(msg.getMessage());
msg.setUserId(msg.getUserId());
arrayList.add(msg);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (!messageList.isEmpty()) {
messagesLv = (ListView) findViewById(R.id.messagesListView);
messages = new MessagesListAdapter(MinaActivity.this, arrayList);
messagesLv.setAdapter(messages);
progressDialog.dismiss();
} else {
TextView tv = (TextView) findViewById(R.id.noMessages);
tv.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
}
}
The reason that it couldn't find any messages, was that I checked if the user ID of the message equals to the user ID of the registered user. The problem was that it was taken from MainActivity.java which got it from an Intent extra, therefore, when I have left the activity, the variable has been erased.
What I did is to refer to the user ID from the SharedPreferences and suddenly it worked.
try to add messages.notifyDataSetChanged(); in onPostExecute() method.
or use below code
MessagesListAdapter messages;
ListView messagesLv;
public static ArrayList<Message> arrayList;
public static ProgressDialog progressDialog;
public static DynamoDBScanExpression dbScanExpression;
public static List<Message> messageList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
messagesLv = (ListView) findViewById(R.id.messagesListView);
messages = new MessagesListAdapter(MinaActivity.this, arrayList);
messagesLv.setAdapter(messages);
new Scan().execute();
}
private class Scan extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(TestActivity.this);
progressDialog.setTitle(name);
progressDialog.setMessage("Searching for messages...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
dbScanExpression = new DynamoDBScanExpression();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.EQ)
.withAttributeValueList(new AttributeValue().withS(MainActivity.msgId));
dbScanExpression.addFilterCondition("msgId", condition);
messageList = MainActivity.mapper.scan(Message.class, dbScanExpression);
arrayList = new ArrayList<Message>();
for (Message msg : messageList) {
if (msg.getUserId() == null || msg.getUserId().equals(MainActivity.userId)) {
msg.setMsgId(msg.getMsgId());
msg.setDate(msg.getDate());
msg.setTime(msg.getTime());
msg.setMessage(msg.getMessage());
msg.setUserId(msg.getUserId());
arrayList.add(msg);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (!messageList.isEmpty()) {
messages.notifyDataSetChanged();
progressDialog.dismiss();
} else {
TextView tv = (TextView) findViewById(R.id.noMessages);
tv.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
}
}

do not load the data in android-pulltorefresh-and-loadmore library

I downloaded and imported the library [https://github.com/shontauro/android-pulltorefresh-and-loadmore][1]
Everything works fine. but when I try to change the code in my error output.
comment out what works. what appear below my not work. Even the logs are not shown. what am I doing wrong?
public class LoadMoreExampleActivity extends ListActivity {
// list with the data to show in the listview
private LinkedList<String> mListItems;
// The data to be displayed in the ListView
private String[] mNames = { "Fabian", "Carlos", "Alex", "Andrea", "Karla",
"Freddy", "Lazaro", "Hector", "Carolina", "Edwin", "Jhon",
"Edelmira", "Andres" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadmore);
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mNames));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);
setListAdapter(adapter);
// set a listener to be invoked when the list reaches the end
((LoadMoreListView) getListView())
.setOnLoadMoreListener(new OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
}
private class LoadDataTask extends AsyncTask<String, Void, String> {
String[] mass;
#Override
protected String doInBackground(String... strings) {
Document doc;
if (isCancelled()) {
return null;
}
// Simulates a background task
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// }
// for (int i = 0; i < mNames.length; i++)
// mListItems.add("string"+i);
try {
doc = Jsoup.connect(link).get();
Elements eName = doc.select("name");
for (int i = 0; i < eName.size(); i++) {
mListItems.add(eName.get(i).ownText());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMoreListView) getListView()).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMoreListView) getListView()).onLoadMoreComplete();
}
}
}
And you do not forget to connect to the internet?
<uses-permission android:name="android.permission.INTERNET"/>

Android - PullToRefreshListView shows make sure your adapter calls notifyDatasechanged

When i was refresh listview multiple times it shows following exception.
Here is the Exception : 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. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(16908298, class com.handmark.pulltorefresh.library.PullToRefreshListView$InternalListViewSDK9) with Adapter(class android.widget.HeaderViewListAdapter)]
Here is code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyLog.i(TAG, "============oncreate===========");
this.history = new ArrayList();
group = this;
Dataengine.whichtab=0;
View vdw = LayoutInflater.from(getApplicationContext()).inflate(
R.layout.home_tab, null);
replaceView(vdw);
// setContentView(R.layout.home_tab);
adapter = new SampleAdapter(HOme.this);
list = (PullToRefreshListView) vdw.findViewById(R.id.listone);
settings = (ImageView) vdw.findViewById(R.id.settings);
stampd=(TextView)vdw.findViewById(R.id.stampdtext);
stampd.setTypeface(Dataengine.isTypeface(this, "condensed"));
list.setAdapter(adapter);
parserobject = new DomParserUserlist(HOme.this);
loginuser = UserData.newInstance();
new Dobackground("norefresh").execute();
list.setOnItemClickListener(itemclicklistener);
settings.setOnClickListener(this);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20))
.build();
Log.v("srinu", "-------------onCreate----------------");
list.setMode(Mode.PULL_DOWN_TO_REFRESH); // mode refresh for top and bottom
list.setShowIndicator(false); //disable indicator
list.setPullLabel("Loading");
// Set a listener to be invoked when the list should be refreshed.
list.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
//limit=limit+10;
offset=offset+limit;
new Dobackground("refresh").execute();
}
});
/*list.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
#Override
public void onLastItemVisible() {
MyLog.i(TAG, "=============77777&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&==========" );
//Toast.makeText(MainActivity.this, "End of List!", Toast.LENGTH_SHORT).show();
}
});*/
}
list = (PullToRefreshListView) vdw.findViewById(R.id.listone);
list.setMode(Mode.PULL_DOWN_TO_REFRESH); // mode refresh for top and bottom
list.setShowIndicator(false); //disable indicator
list.setPullLabel("Loading");
// Set a listener to be invoked when the list should be refreshed.
list.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
//limit=limit+10;
offset=offset+limit;
new Dobackground("refresh").execute();
}
});
class Dobackground extends AsyncTask<Void, Void, Void> {
String pullref;
public Dobackground(String string) {
pullref=string;
}
// private ProgressDialog pd;
#Override
protected void onPreExecute() {
if(!pullref.equalsIgnoreCase("refresh"))
showDialog(MYDIALOG);
//list.setVisibility(View.GONE);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
MyLog.i(TAG, "============doInBackground=== date========"+strDate);
if(null!=data)
data.clear();
String urls=Dataengine.FriendsAvilableInVenue+"?userid="+
Dataengine.showPreferences(HOme.this,Dataengine.USERID)+"&date="+strDate+"&limit="+limit+"&offset=0";
urls=urls.replace(" ","%20");
if(Dataengine.isConnectingToInternet(HOme.this)){
data = parserobject.getData(urls,"home");
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Dataengine.ShowDialog(HOme.this,"No Internet Connection");
}
});
}
// MyLog.i(TAG, "============doinbackgrund list size==========="+ data.size());
return null;
}
#Override
protected void onPostExecute(Void result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try{
if(null!=data&&data.size()>0){
adapter.notifyDataSetChanged();
}else{
//Dataengine.ShowDialog(HOme.this,"No Data is Avilable");
}
}catch(Exception e){
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
list.requestLayout();
}
});
if(!pullref.equalsIgnoreCase("refresh"))
removeDialog(MYDIALOG);
list.onRefreshComplete();
super.onPostExecute(result);
}
}
Try this. It's your AsyncTask which i tweaked a little.
class Dobackground extends AsyncTask<Void, Void, boolean> {
String pullref;
public Dobackground(String string) {
pullref=string;
}
// private ProgressDialog pd;
#Override
protected void onPreExecute() {
if(!pullref.equalsIgnoreCase("refresh"))
showDialog(MYDIALOG);
//list.setVisibility(View.GONE);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
MyLog.i(TAG, "============doInBackground=== date========"+strDate);
if(null!=data)
data.clear();
String urls=Dataengine.FriendsAvilableInVenue+"?userid="+
Dataengine.showPreferences(HOme.this,Dataengine.USERID)+"&date="+strDate+"&limit="+limit+"&offset=0";
urls=urls.replace(" ","%20");
if(Dataengine.isConnectingToInternet(HOme.this)){
data = parserobject.getData(urls,"home");
}else{
return false;
}
// MyLog.i(TAG, "============doinbackgrund list size==========="+ data.size());
return true;
}
#Override
protected void onPostExecute(Void result) {
if(result){
if(null!=data&&data.size()>0){
adapter.notifyDataSetChanged();
}else{
//Dataengine.ShowDialog(HOme.this,"No Data is Avilable");
}
}else{
Dataengine.ShowDialog(HOme.this,"No Internet Connection");
}
list.requestLayout();
if(!pullref.equalsIgnoreCase("refresh"))
removeDialog(MYDIALOG);
list.onRefreshComplete();
super.onPostExecute(result);
}
}

Android loading listview with progress dialog

this is my code to load listview items
#SuppressLint("DefaultLocale")
public class SearchList extends Activity {
private ArrayList<String> founded = new ArrayList<String>();
private OrderAdapter m_adapter;
ListView lv;
/** Called when the activity is first created. */
#SuppressLint("DefaultLocale")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchlist);
lv = (ListView) findViewById(R.id.listView1);
new Load().execute();
m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}
private class Load extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(SearchList.this);
progress.setMessage("loading....");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
for (int i = 0; i <500000; i++) {
founded.add("String "+i);
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
}
}
when i run the code the progress dialog already appear but after its dismiss i found that the list is empty no items added to it i do not know what is the problem and why the list is empty after the dialog loading .Pls need help
thanks in advance.
Set listadapter in onPostExecute Because you Are using AsyncTask to get adapter data and setting ListAdapter before Completing AsyncTask So Try to Set ListAdapter after Completing AsyncTask
So add these
m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
lines in onPostExecute method instead of onCreate Method
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
m_adapter = new OrderAdapter(YourActivity.this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}

How do I set up my doInBackground's params in my AsyncTask?

my screen when I click on a button is slow to load (because of downloading images? the image files are really small though) so I tried to use AsyncTask to help. The program works, but I moved the image loading to an AsyncTask to see if it would load faster and the app crashes every time. I'm guessing it has to do with the way I have it set up. How would I fix it? Would using a runnable thread be better instead? Thanks!
The class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// no title
requestWindowFeature(Window.FEATURE_NO_TITLE);
// set full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// inflate listview
setContentView(R.layout.gmg);
**new Load.execute(); // executes AsyncTask**
...
gmgListView = (ListView) findViewById(R.id.gmg_list2);
GMGListViewAdapter adapter = new GMGListViewAdapter(this,
R.layout.gmg_list_row, rowItems);
gmgListView.setAdapter(adapter);
gmgListView.setOnItemClickListener(this);
}
The AsyncTask:
private class Load extends AsyncTask<String, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(GMGListViewActivity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Doing something...");
Dialog.show();
}
#Override
protected Void doInBackground(String... params) {
SparseArray<Spanned> gmgText = null;
Integer[] right = null;
SparseArray<Drawable> appIcon = null;
try {
gmgText = ParseContent.queryGMGText();
right = ParseContent.queryGMGRight();
appIcon = ParseContent.queryDrawable();
} catch (ParseException e) {
e.printStackTrace();
}
// Inflate GMG's rows
rowItems = new ArrayList<GMGRowItem>();
for (int i = 0; i < gmgText.size(); i++) {
GMGRowItem item = new GMGRowItem(appIcon.get(i), gmgText.get(i), right[i]);
rowItems.add(item);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
}
}
You need to apply some changes in your code like...
need to set list adapter in onPostExecute method and remove it from onCreate().
After completing background process it will interact with ui thread.
protected void onPostExecute(Void unused) {
Dialog.dismiss();
GMGListViewAdapter adapter = new GMGListViewAdapter(this,
R.layout.gmg_list_row, rowItems);
gmgListView.setAdapter(adapter);
}
Try this and let me know if you got any isssue.

Categories

Resources