Android - PullToRefreshListView shows make sure your adapter calls notifyDatasechanged - android

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

Related

Single button multiple action

I am using a single button to do two task.
Watson Conversation.
Watson Text to Speech.
My code is executing only if my TextView has some Text name (string), but the Text to Speech is playing the last conversation response even though the new conversation response is updated at TextView display on my phone UI.. Continuation of this here Race condition with UI thread issue.
Also I found out, if I keep my TextView empty i get error this:
Code here:
private class ConversationTask extends AsyncTask<String, Void, String> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
reply.setText(textResponse);
System.out.println(textResponse);
}
#Override
public void onFailure(Exception e) {
}
});
return textResponse;
}
}
//
private class WatsonTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(final String... textToSpeak) {
/* runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(" ");
}
});*/
TextToSpeech textToSpeech = initTextToSpeechService();
streamPlayer = new StreamPlayer();
streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute());
return "Text to Speech Done";
}
/*#Override protected void onPostExecute(String result) {
textView.setText("");
}*/
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register the UI controls.
input = (EditText) findViewById(R.id.input);
send = (ImageButton) findViewById(R.id.send);
textView = (TextView) findViewById(R.id.textView);
reply = (TextView) findViewById(R.id.reply);
play = (ImageButton) findViewById(R.id.play);
new ConversationTask().execute("");
//Button function
send.setOnClickListener(action3);
}
//five actions on button click
public void action5() {
String textResponse = new String();
System.out.println("Text to Speech:" + reply.getText());
//textView.setText("");
WatsonTask task = new WatsonTask();
task.execute(String.valueOf(reply.getText()));
//new WatsonTask().execute(reply.getText().toString());
}
View.OnClickListener action3 = new View.OnClickListener() {
public void onClick(View v) {
//action here//
new ConversationTask().execute(input.getText().toString());
action5();
}
};
}
Please help.
Action 3
View.OnClickListener action3 = new View.OnClickListener() {
public void onClick(View v) {
//action here//
new ConversationTask().execute(input.getText().toString());
}
};
Action 5
public void action5(String replyString) {
WatsonTask task = new WatsonTask();
task.execute(replyString);
}
Conversation Task
private class ConversationTask extends AsyncTask<String, Void, String> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
reply.setText(textResponse);
action5(textResponse);
}
#Override
public void onFailure(Exception e) {
}
});
return textResponse;
}
}
WatsonTask
private class WatsonTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(final String... textToSpeak) {
reply.setText(textToSpeak[0]);
TextToSpeech textToSpeech = initTextToSpeechService();
streamPlayer = new StreamPlayer();
streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute());
return textToSpeak[0];
}
}
And for the sake of completeness address to the comment by Marcin Jedynak
I think your program scenario will follow next sequences:
Enter text to conversation task.
Get conversation result from GLS_service.message().
Input the result from sequence 2, for make the voice.
So try to change your code like this.
// There is no need to return String. Just send result to TextToSpeech.
//private class ConversationTask extends AsyncTask<String, Void, String> {
private class ConversationTask extends AsyncTask<String, Void, Void> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
reply.setText(textResponse);
System.out.println(textResponse);
action5(textResponse); // It is real result that you want.
}
#Override
public void onFailure(Exception e) {
}
});
//return textResponse; // Not necessary.
}
}
//
private class WatsonTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(final String... textToSpeak) {
/* runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(" ");
}
});*/
TextToSpeech textToSpeech = initTextToSpeechService();
streamPlayer = new StreamPlayer();
streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute());
return "Text to Speech Done";
}
/*#Override protected void onPostExecute(String result) {
textView.setText("");
}*/
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register the UI controls.
input = (EditText) findViewById(R.id.input);
send = (ImageButton) findViewById(R.id.send);
textView = (TextView) findViewById(R.id.textView);
reply = (TextView) findViewById(R.id.reply);
play = (ImageButton) findViewById(R.id.play);
new ConversationTask().execute("");
//Button function
send.setOnClickListener(action3);
}
//five actions on button click
// Need a parameter to get String.
//public void action5() {
public void action5(String text) {
// String textResponse = new String(); // Replace to parameter as "text".
//System.out.println("Text to Speech:" + reply.getText());
System.out.println("Text to Speech:" + text);
//textView.setText("");
WatsonTask task = new WatsonTask();
//task.execute(String.valueOf(reply.getText()));
task.execute(text); // Replace to parameter as "text".
//new WatsonTask().execute(reply.getText().toString());
}
View.OnClickListener action3 = new View.OnClickListener() {
public void onClick(View v) {
//action here//
new ConversationTask().execute(input.getText().toString());
// action5(); // This invoking is not necessary at this point.
// Try to invoke this method after you get conversation result.
}
};
If it is not working even you changed, I want to know how you implement initTextToSpeechService() method.
Hope this helps you.

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"/>

create new async task with sending callback to ui

i have listview and the content of listview change depend on user interface
and i need to know how to create new instance of async task if i implement callback receiver
public interface CallbackReciever {
public void receiveData(String result);
}
and the async task class
public abstract class ConnectDB extends AsyncTask<String, String, String> implements CallbackReciever {
ProgressDialog pDialog;
Context context;
public String resString;
public ConnectDB(Context context)
{
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
public abstract void receiveData(String object);
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args)
{
// getting JSON string from URL
resString =Connection.Get(path);
return resString;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url)
{
// dismiss the dialog after getting all products
pDialog.dismiss();
if(resString!=null)
{
receiveData(resString);
}
}
}
and the MainActivity class
public class MainActivity extends Activity {
ListView list;
MovieAdapter adapter;
public ArrayList<Movie> data=new ArrayList<Movie>();
public ConnectDB conDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context t=this.getApplicationContext();
setContentView(R.layout.activity_main);
conDB= new ConnectDB(MainActivity.this) {
#Override
public void receiveData(String result) {
// TODO Auto-generated method stub
try {
Log.d("ds", result);
JSONObject json = null;
JSONArray jArray = new JSONArray(result);
int i=0;
while ( i< jArray.length())
{
final Movie tmp=new Movie();
json = jArray.getJSONObject(i);
tmp.setName(json.getString("name"));
tmp.setUrl(json.getString("image"));
tmp.setDescription(json.getString("desc"));
tmp.setTime(json.getString("time"));
tmp.setTime(Utils.ChangeTolocaclTime(tmp.getTime()));
tmp.setWatch(Utils.CanWatch(tmp.getTime()));
data.add(tmp);
i++;
}
}
catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
if(data.size()==0)
{
Toast.makeText(t, "Server Error", Toast.LENGTH_SHORT).show();
list.setVisibility(View.INVISIBLE);
}
// Create custom adapter for listview
adapter=new MovieAdapter(MainActivity.this, data,t);
//Set adapter to listview
list.setAdapter(adapter);
}
};
conDB.execute("MBC2");
}
The activity should implement the receiver and the async task should call it, something like this:
public class MyActivity extends Activity implements CallbackReceiver{
#Override
public void onCreate(Bundle savedInstanceState) {
//Set everything up
MyAsyncTask task = new MyAsyncTask();
task.setOnDataReceivedListener(this);
task.execute();
}
#Override
public void onReceiveData(String data){
//Do something with the data
}
}
Then, in the async task, you can call the receiver method in onPostExecute
public abstract class MyAsyncTask extends AsyncTask<String, String, String>{
private CallbackReciever receiver = null;
public void setOnDataReceivedListener(CallbackReciever receiver){
this.receiver = receiver
}
protected void onPostExecute(String file_url)
{
if(receiver != null){
receiver.onReceiveData(file_url);
}
}
}
The second way to do this is to simply make an anonymous inner class of your async task and override onPostExecute:
public class MyActivity extends Activity implements CallbackReceiver{
#Override
public void onCreate(Bundle savedInstanceState) {
//Set everything up
MyAsyncTask task = new MyAsyncTask(){
#Override
protected void onPostExecute(String file_url){
//Do what you want with your data here
}
};
task.execute();
}
}

Android can't create handler inside that has not called Looper.loop

i am getting friends list from facebook and populating in list view it works fine but now i am trying to add Progress bar till the list view populates but getting exception i have tried searching but not found solution for my issue, here is my code:
public class FriendsProgress extends AsyncTask<Object, Void, Boolean>
{
#Override
protected Boolean doInBackground(Object... Params)
{
try
{
getFriendList();
friendAdapter = new FriendAdapter(Friends.this, R.layout.activity_friends, friendsList);
Friends.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
list.setAdapter(friendAdapter);
//list.setOnItemClickListener(EditStaff.this);
}
});
}
catch (Exception e)
{
System.out.println("StaffProgess Exception Caught:"+e.getMessage());
}
return Boolean.TRUE;
}
#Override
protected void onPreExecute()
{
friendsProgress=new ProgressDialog(Friends.this);
friendsProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
friendsProgress.setIndeterminate(true);
friendsProgress.setMessage("Loading...");
friendsProgress.setOwnerActivity(Friends.this);
friendsProgress.show();
}
#Override
protected void onPostExecute(Boolean Result)
{
friendsProgress.dismiss();
friendAdapter.notifyDataSetChanged();
}
}
here is getFriendsList function implementation:
public void getFriendList(){
Request request = Request.newMyFriendsRequest(Session.getActiveSession(), new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
// TODO Auto-generated method stub
for(int i=0; i<users.size();i++)
{
GraphUser user = users.get(i);
Friend objFriend = new Friend();
objFriend.setFriendID(user.getId());
objFriend.setFriendName(user.getName());
Drawable dd =Friends.LoadImageFromWebOperations("http://graph.facebook.com/" + objFriend.getFriendID() + "/picture");
objFriend.setFriendPic(dd);
//objFriend.setFriendPic("http://graph.facebook.com/" + objFriend.getFriendID() + "/picture");
friendsList.add(objFriend);
//friendAdapter.notifyDataSetChanged();
Log.d("Friend's Id", objFriend.getFriendID());
Log.d("Friend's Name", objFriend.getFriendName());
//Log.d("Friend's Pic", objFriend.getFriendPic());
Log.d("Friend's List Count", Integer.toString(friendsList.size()));
}
}
});
Request.executeBatchAsync(request);
You shouldn't instantiate an Adapter and link it to a ListView inside the doInBackground() method, because it's running on a worker thread, and no operations connected to Android Views are permitted to be executed on a worker thread. Instead you might want to move this code
friendAdapter = new FriendAdapter(Friends.this, R.layout.activity_friends, friendsList);
Friends.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
list.setAdapter(friendAdapter);
//list.setOnItemClickListener(EditStaff.this);
}
});
to the onPostExecute() method. This is surely a better designed solution. Hope this helps.
Try this,
ProgressDialog dialog;
protected void onPreExecute()
{
dialog = new ProgressDialog(Friends.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMax(100);
dialog.show();
}
Run Ui Thread inside onPostExecute() method as follows :
runOnUiThread(new Runnable() {
#Override
public void run() {
friendAdapter = new FriendAdapter(Friends.this, R.layout.activity_friends, friendsList);
list.setAdapter(friendAdapter);
friendsProgress.dismiss();
friendAdapter.notifyDataSetChanged();
}
});

What is wrong with progress dialog in AsyncTask

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

Categories

Resources