I have a zip file which I have to extract information from which I can take specific information . The process of taking out the information takes about .7 of a second estimated. What I did was add in an Asynchronous class inside my ListAdapter (To make multiple threads so it can also load other similar threads) and now in my Asynchronous class it makes multiple threads which causes the database add information to its pre existing information.
Now my question is "How would I make an asynchronous threading on a listadapter without causing duplicates on the database?"
Here is the code:
Map<TextView, String> authorViews=Collections.synchronizedMap(new WeakHashMap<TextView, String>());
Map<TextView, String> dateViews=Collections.synchronizedMap(new WeakHashMap<TextView, String>());
private class PresentInformation extends AsyncTask<Context, Void, Void>{
private TextView Tauthor;
private TextView Tlabel;
String position;
String date = null;
String author = null;
public PresentInformation(TextView author, TextView label, String Position) {
// TODO Auto-generated constructor stub
this.Tauthor = author;
this.Tlabel = label;
this.position = Position;
}
#Override
protected Void doInBackground(Context... params) {
// TODO Auto-generated method stub
Boolean addToDB;
if(author_exist(Tauthor)){
author = getAuthorFName(position);
addToDB = false;
}else{
//Declare an action to test if author does exist
authorViews.put(Tauthor, position);
author = getAuthor(position);
addToDB = true;
}
dateViews.put(Tlabel, position);
if(date_exist(Tlabel)){
date = db.getDate(position);
addToDB = false;
}else{
dateViews.put(Tlabel, position);
date = date/time();
addToDB = true;
}
if(addToDB){//Adds to database if they don't exist
db.addDatabase(new Database(position, author, date));
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if(author == null){
author = "Author not found!";
}
if(date == null){
date = "Date not found!";
}
Tlabel.setText(date);
Tlabel.setText(author);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Tauthor.setText("Loading author please wait...");
Tlabel.setText("Loading date please wait...");
}
public Boolean author_exist(TextView tv){
String temp = authorViews.get(tv);
if(temp ==null)
return true;
return false;
}
public Boolean date_exist(TextView tv){
String temp = dateViews.get(tv);
if(temp ==null)
return true;
return false;
}
}
public class IconicAdapter extends ArrayAdapter<String>{
IconicAdapter() {
super(main.this, R.layout.bookselection_row, R.id.Book_Title, bookLocation);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
if(row == null)
row = super.getView(position, convertView, parent);
icon=(ImageView)row.findViewById(R.id.icon);
author = (TextView)row.findViewById(R.id.book_Author);
date_label = (TextView)row.findViewById(R.id.label);
String path = bookLocation.get(position);
// Collections(path, position, author, date_label);
new PresentInformation(author, date_label, path).execute(main.this);
try{
Log.i("BookString input", bookLocation.get(position));
loadImage.Uploader(bookLocation.get(position), icon);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return row;
}
}
Below is an example of an AsyncTask I'm using in the app I'm currently developing. I hope it helps get you on the right track.
private class prepCombat extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
playerBattlePrep();
findNPC();
return null;}
#Override
protected void onPostExecute(String result) {
new layoutCombat().execute();
}
}
Then when I want to call it...
#Override
protected void onResume() {
new pullCombatActions().execute();
new prepCombat().execute();
super.onResume();}
To insure it doesn't keep adding the same data some If() statements should work. Another option would be to include the data already in your database. If this is data that should always be there, having it already there when the program first runs could save you some trouble.
I see your put statements but I'm not seeing where you tell it which row to place it.
public void updateEntry(int rowId, String str, String cha, String wis, String dex, String name, int damId, int HPId, int npcId, int attId, int dodgeId, int dreadId, int critId) throws SQLException {
ContentValues cvUpdate = new ContentValues();
cvUpdate.put("Str", str);
cvUpdate.put("Cha", cha);
cvUpdate.put("Wis", wis);
cvUpdate.put("Dex", dex);
cvUpdate.put("Name", name);
cvUpdate.put("StatDam", damId);
cvUpdate.put("StatHP", HPId);
cvUpdate.put("HP", HPId);
cvUpdate.put("StatNpc", npcId);
cvUpdate.put("StatAtt", attId);
cvUpdate.put("StatDodge", dodgeId);
cvUpdate.put("StatDread", dreadId);
cvUpdate.put("StatCrit", critId);
cvUpdate.put("Rank", "0");
cvUpdate.put("Lvl", "1");
...
ContentValues csUpdate = new ContentValues();
csUpdate.put("PlayerHp", HPId);
csUpdate.put("CombatFlag", "0");
dbhelper.myDataBase.update(dbhelper.SAVE_TABLE, cvUpdate, "_id" + "=" + rowId, null);
dbhelper.myDataBase.update(dbhelper.COMBATSAVE_TABLE, csUpdate, "_id" + "=" + rowId, null);
}
Would be a method to setup what and where I put the data in my database. Then I can call the method by
updateEntry(slot, String.valueOf(strNumber), String.valueOf(chaNumber), String.valueOf(wisNumber), String.valueOf(dexNumber), nameNumber, damId, HPId, npcId, attId, dodgeId, dreadId, critId);
Whenever you want to preform this save you would call the above code. Likely in a doInBackground()
Related
I am trying to remove an item from view when its flag become 4. I tried mObjects.remove(position) and then notifyDataSetChanged(). but it didn't worked.we tried all the following
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
also this one
// mObjects.remove(position)
// notifyDataSetChanged();
and this one
// mObjects.remove(position);
//remove(position);
//mainObjects.remove(position);
//notifyDataSetChanged();
and this one
// Object toRemove = adapter.getItem(position);
// mObjects.remove(toRemove);
// mObjects.clear();
and all the time we got java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0.Here is the complete adapter class
private class MatchedDataAdapter extends BaseAdapter implements Filterable {
private AQuery aQuery;
private Activity mActivity;
private LayoutInflater mInflater;
private SessionManager sessionManager;
private int uflag;
MyFilter mfilter;
DatabaseHandler db;
ArrayList<LikeMatcheddataForListview> mObjects;
ArrayList<LikeMatcheddataForListview> mainObjects;
Context context;
public MatchedDataAdapter(Activity context,
ArrayList<LikeMatcheddataForListview> objects,
int imageHeigthAndWidth[]) {
this.mObjects = objects;
mainObjects = objects;
//Log.e("size", Integer.toString(mObjects.size()));
this.mActivity = context;
try {
mInflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
catch (Exception e)
{
e.printStackTrace();
}
aQuery = new AQuery(context);
db = new DatabaseHandler(context);
}
#Override
public int getCount() {
return mObjects.size();
}
#Override
public LikeMatcheddataForListview getItem(int position) {
return mObjects.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.matchedlistviewitem,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.userimage);
holder.textview = (TextView) convertView
.findViewById(R.id.userName);
holder.lastMasage = (TextView) convertView
.findViewById(R.id.lastmessage);
holder.imgStatus = (ImageView) convertView
.findViewById(R.id.imgStatus);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview.setText(getItem(position).getUserName());
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
we want to remove Item with flag 4,we are reading this flag with a service from db and onrecive we call class DisplayContentTask as below
class GetLikeMatchedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
new DisplayContentTask(intent).execute();
}
}
how we can get Item position in order to remove the Item with flag 4...or My be another approach to remove Item with flag 4 we don't know but appreciate your help on this
class DisplayContentTask extends AsyncTask<Void, Void, Void> {
Intent intent;
private Ultilities mUltilities = new Ultilities();
private List<NameValuePair> getuserparameter;
private String likedmatchedata, Unmatchedata;
int match1;
private LikedMatcheData matcheData;
private ArrayList<com.appdupe.flamer.pojo.Likes> likesList;
private LikeMatcheddataForListview matcheddataForListview;
DatabaseHandler mDatabaseHandler = new DatabaseHandler(getActivity());
private boolean isResponseSuccess = true;
ArrayList<LikeMatcheddataForListview> tempArray = new ArrayList<LikeMatcheddataForListview>();
#Override
protected void onPreExecute() {
super.onPreExecute();
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPreExecute ");
}
DisplayContentTask(Intent intent) {
this.intent = intent;
}
#Override
protected Void doInBackground(Void... voids) {
try {
File appDirectory = mUltilities
.createAppDirectoy(getResources().getString(
R.string.appdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground appDirectory "
+ appDirectory);
File _picDir = new File(appDirectory, getResources().getString(
R.string.imagedirematchuserdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground ");
// getuserparameter = mUltilities.getUserLikedParameter(params);
likedmatchedata = intent.getStringExtra("GET_MATCHED_RESPONSE");
// Unmatchedata = intent.getStringExtra("GET_UNMATCHED_RESPONSE");//hadi
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likedmatchedata "
+ likedmatchedata);
Gson gson = new Gson();
matcheData = gson.fromJson(likedmatchedata,
LikedMatcheData.class);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground matcheData "
+ matcheData);
// "errNum": "51",
// "errFlag": "0",
// "errMsg": "Matches found!",
if (matcheData.getErrFlag() == 0) {
likesList = matcheData.getLikes();
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList "
+ likesList);
if (tempArray != null) {
tempArray.clear();
}
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList sized "
+ likesList.size());
Log.v("Matches", "" + likesList.size());
match1 = likesList.size();
for (int i = 0; i < likesList.size(); i++) {
Log.d("likelist", likesList.toString());
matcheddataForListview = new LikeMatcheddataForListview();
String userName = likesList.get(i).getfName();
String facebookid = likesList.get(i).getFbId();
// Log.i(TAG, "Background facebookid......"+facebookid);
String picturl = likesList.get(i).getpPic();
int falg = likesList.get(i).getFlag();
// if (likesList.get(i).getFlag()==4) {
// likesList.remove(getId());
// }
Log.i("komak10",""+likesList.get(i).getFlag());
String latd = likesList.get(i).getLadt();
matcheddataForListview.setFacebookid(facebookid);
matcheddataForListview.setUserName(userName);
matcheddataForListview.setImageUrl(picturl);
matcheddataForListview.setFlag("" + falg);
matcheddataForListview.setladt(latd);
// matcheddataForListview.setFilePath(filePath);
File imageFile = mUltilities.createFileInSideDirectory(
_picDir, userName + facebookid + ".jpg");
// logDebug("BackGroundTaskForUserProfile doInBackground imageFile is profile "+imageFile.isFile());
Utility.addBitmapToSdCardFromURL(likesList.get(i)
.getpPic().replaceAll(" ", "%20"), imageFile);
matcheddataForListview.setFilePath(imageFile
.getAbsolutePath());
if (!preferences.getString(Constant.FACEBOOK_ID, "")
.equals(facebookid)) {
tempArray.add(matcheddataForListview);
}
}
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
getActivity());
// SessionManager mSessionManager = new SessionManager(
// MainActivity.this);
String userFacebookid = preferences.getString(
Constant.FACEBOOK_ID, "");
//
boolean isdataiserted = mDatabaseHandler.insertMatchList(
tempArray, userFacebookid);
} else if (matcheData.getErrFlag() == 1) {
if(tempArray!=null)
{
tempArray.clear();
}
} else {
// do nothing
}
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched doInBackground Exception ",
e);
// some thing wrong happend
isResponseSuccess = false;
}
return null;
}
Don't remove the object in getview, if you have to filter it, filter it before sending out to adapter. May be possible that while creating the child view the 1st cell has tag "4" now the view didn't create(since return was not called) but you are trying to remove its position, so it will definitely give you IndexOutOfBoundsException.
My best solution would be, set the adapter with
new ArrayList<LikeMatcheddataForListview>()
whenever you start the screen. Once your AsyncTask completes filter out the child with tags "4"(better filter it out in the asynctask only, less task in ui thread) then refresh the adapter, like
public void refresh(ArrayList<LikeMatcheddataForListview>() arrObjects){
objects = arrObjects;
notifyDataSetChanged();
}
Check it out, it should do the trick
Please try following
Your code
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
}
TO
do not set adapter again to list view
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
notifyDataSetChanged();
}
This may not be correct approach to remove the item form listview.
Whenever your adapter data is getting changed then just check if that flag matches your string i.e. "4" in each item and remove the respective item from the list and just call notifyItemRemoved with position insted of notifyDataSetChanged
Sorry for my bad english.I am new to android and i parsed json data into listview,now i want to put on him a search functionality,but i have a problem,when i entered a words in edittext,then in the listview my items are duplicated,and items has been increases,look my code and screen shots.Thanks in advance and any help will be much appreciated.
My Artist Activity:
public class Artists extends Activity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// This is not using now if you want you can remove its all references :)
ArrayList<HashMap<String, String>> albumsList;
ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
private LazyAdapterArtist mLazyAdatper = null;
private ArrayList<String> array_sort = new ArrayList<String>();
int textlength = 0;
// albums JSONArray
JSONArray albums = null;
LinearLayout ll_artists_chart;
LinearLayout ll_artists_newrelease;
private EditText etSearch;
private static String URL_ALBUMS = "http://triplevmusic.com/dev/webservice/index.php?op=fetch_artists.json";
// JSON Node names
private static final String TAG_CONTACTS = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private ListView lv = null;
EditText et_artists_searchWord;
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.artists);
lv = (ListView) findViewById(R.id.artist_main_list_id);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(Artists.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
/**
* Listview item click listener TrackListActivity will be lauched by
* passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
}
});
ll_artists_chart = (LinearLayout) findViewById(R.id.ll_artists_chart);
ll_artists_newrelease = (LinearLayout) findViewById(R.id.ll_artists_newrelease);
et_artists_searchWord = (EditText) findViewById(R.id.et_artists_searchWord);
et_artists_searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOs, true);
mAdapterDTOs.addAll(list);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
ll_artists_chart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), ChartActivity.class);
startActivity(intent);
// finish();
}
});
ll_artists_newrelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), NewReleases.class);
startActivity(intent);
//finish();
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Artists.this);
pDialog.setMessage("Listing Artists ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
//List<NameValuePair> params = new ArrayList<NameValuePair>();
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_ALBUMS);
// getting JSON string from URL
//String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", params);
// Check your log cat for JSON reponse
Log.i("Albums JSON: ", "> " + json);
try {
//albums = new JSONArray(json);
albums = json.getJSONArray(TAG_CONTACTS);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
/*String EateryThmbnailUrl = c
.getString(TAG_THMBNAIL_URL);*/
// ~\/Uploads\/EateryImages\/\/7\/41283f1f-8e6f-42d4-b3c1-01f990efb428.gif
/*EateryThmbnailUrl = HOST_URL
+ EateryThmbnailUrl.replace("~", "");*/
AdapterDTOArtist adapterDTO = new AdapterDTOArtist();
adapterDTO.setmTag_Id(id);
adapterDTO.setmTag_Name(name);
// adapterDTO.setmImage_URL(EateryThmbnailUrl);
mAdapterDTOs.add(adapterDTO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
albumsList.add(map);
}
} else {
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// updating listview
mLazyAdatper = new LazyAdapterArtist(Artists.this,
mAdapterDTOs);
lv.setAdapter(mLazyAdatper);
// mLazyAdatper.setDataSet(mAdapterDTOs);
}
});
}
}
public static List<AdapterDTOArtist> filter(String string,
Iterable<AdapterDTOArtist> iterable, boolean byName) {
if (iterable == null)
return new LinkedList<AdapterDTOArtist>();
else {
List<AdapterDTOArtist> collected = new LinkedList<AdapterDTOArtist>();
Iterator<AdapterDTOArtist> iterator = iterable.iterator();
if (iterator == null)
return collected;
while (iterator.hasNext()) {
AdapterDTOArtist item = iterator.next();
collected.add(item);
}
return collected;
}
}
}
My AdapterDTOArtist class :
public class AdapterDTOArtist {
private String mTag_Id;
private String mTag_Name;
public String getmTag_Name() {
return mTag_Name;
}
public void setmTag_Name(String mTag_Name) {
this.mTag_Name = mTag_Name;
}
public String getmTag_Id() {
return mTag_Id;
}
public void setmTag_Id(String mTag_Id) {
this.mTag_Id = mTag_Id;
}
}
My LazyAdapterArtist class:
public class LazyAdapterArtist extends BaseAdapter {
private Context mContext = null;
private ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
public LazyAdapterArtist(Context context,
ArrayList<AdapterDTOArtist> mAdapterDTOs2) {
// TODO Auto-generated constructor stub
this.mContext = context;
this.mAdapterDTOs = mAdapterDTOs2;
}
public void setDataSet(ArrayList<AdapterDTOArtist> adapterDTOs) {
this.mAdapterDTOs = adapterDTOs;
notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mAdapterDTOs.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder mHolder = new ViewHolder();
if (row == null) {
// Cell is inflating for first time
row = LayoutInflater.from(mContext)
.inflate(com.whizpool.triplevmusic.R.layout.row_artists,
null, false);
mHolder.mNameTxt = (TextView) row
.findViewById(com.whizpool.triplevmusic.R.id.tv_row_artists);
row.setTag(mHolder);
} else {
// recycling of cells
mHolder = (ViewHolder) row.getTag();
}
mHolder.mNameTxt.setText(mAdapterDTOs.get(position).getmTag_Name());
return row;
}
static class ViewHolder {
TextView mNameTxt = null;
}
}
when parsed json data into listview my app look like this:
when enter word in edittext field then my app look like this:
I just want,when i entered the word for example i enter "D" then in a listview only those words were display which have starting word is "D".Thanks Alot and again sorry for my english.
The problem is that when you filter the data you add again to mAdapterDTOs list the results you need to clear the list before adding the results. To avoid losing your data you have to keep them in a separate list and when user times nothing show them.
Step 1: Use a field for keeping a backup of your data (just as mAdapterDTOs):
ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
ArrayList<AdapterDTOArtist> mAdapterDTOsBackup= null;
Step 2: initialize that field:
mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
mAdapterDTOsBackup = new ArrayList<AdapterDTOArtist>();
Step 3: Fill in all your data to the backup set just after parsing:
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// HERE all your code as it is!!!
// Just before return add a set keeping the backup of your data...
// initialize the set just as mAdapterDTOs
mAdapterDTOsBackup.addAll(mAdapterDTOs);
return null;
}
Step 4: When searching filter data from backup set and then add them on the mAdapterDTOs do not forget to clear it before.
et_artists_searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOsBackup, true);
mAdapterDTOs.clear(); // <--- clear the list before add
mAdapterDTOs.addAll(list); // <--- here is the double add if you do not clear before
mLazyAdatper.setDataSet(mAdapterDTOs);// update the adapter data (edit 2)
}
Edit: split answer in steps in order to be more clear the process also added at least one of your line to show where to add each code snippet.
I want to make my application offline .When I am inserting data from url to database it works fine when internet available but my app not show any thing in gridview when no internet available what is wrong in my app please help me why gridview not loading data from database help me
public class MainActivity extends Activity {
CategoryListAdapter3 cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String URL, URL2;
String SelectMenuAPI;
String _response;
String status;
GridView gridview;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private boolean isUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper=new DbHelper(this);
dataBase=mHelper.getWritableDatabase();
gridview = (GridView) findViewById(R.id.gridview);
cla = new CategoryListAdapter3(MainActivity.this);
new TheTask().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(MainActivity.this,
Subcategory.class);
iMenuList.putExtra("Category_ID", Category_ID.get(position));
iMenuList.putExtra("Category_name", Category_name.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
SelectMenuAPI = "http://www.fff/mobile_api.php?response=getmaincategories";
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("Status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
//
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
String id = object.getString("category_id");
String name =object.getString("name");
String image_path = object.getString("image_path");
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_MYID,id);
values.put(DbHelper.KEY_FNAME,name);
values.put(DbHelper.KEY_LNAME,image_path );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
}
}
else {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
displayData();
}
}
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
//
// Category_ID.clear();
// Category_name.clear();
// Category_image.clear();
if (mCursor.moveToFirst()) {
do {
Category_ID.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
Category_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
Category_image.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
gridview.setAdapter(cla);
mCursor.close();
}
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_MYID="myid";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY
KEY,"+KEY_MYID+" TEXT, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" BLOB)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return MainActivity.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(MainActivity.Category_name.get(position));
a
ndroidAQuery.id(holder.imgThumb).image(MainActivity.Category_image.get(position), true,
true);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
check internet Availability before web service call:
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
You have called displayData() only in onPostExecute, so the data is displayed in grid only when you receive data from that URL.
Solution: Call the displayData() once in onCreate function before new TheTask().execute(). So now data will be displayed from the DB if available and then fetch from that URL using HTTPClient. If no internet then the data will still be displayed.
Note: Make sure the cursor size greater than 0 inside displayData(), else display no data text instead of grid view.
happy coding :)
This is quite obvious, You are actually calling you displayData() in postExecute, but in case of no internet, exception will occur you doInBackgroud and null will be passed to postExecute...Exception again in postExecute and your displayData() will not be called.
So first, implement checks for null values to avoid exceptions, and then close try closing you db in catch block.
I am working on an application that requires data to be displayed on a listview. The data to be displayed on the listview needs to be updated frequently so i created a sync-adapter which will be triggered my a broadcast message from gcm. When this occurs my AsyncTask loader.onContentChanged is called which call the loadinbackground method and all this works properly. The issues i am having is displaying the new data on the listview without restarting the activity. i am trying to get it to work like facebook news feed listview.
Please help me
My codes are as follows
SyncAdapter
#Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
// TODO Auto-generated method stub
Log.d(TAG, "onPerformSync for account[" + account.name + "]");
String theValue = mAccountManager.getUserData(account, "User_ID");
mContentResolver = mContext.getContentResolver();
final RoomListLoader mLoader = new RoomListLoader(mContext, theValue);
mLoader.onContentChanged();
}
Loader
public class RoomListLoader extends AsyncTaskLoader<List<RoomList>> {
private static String url = "********************";
int success;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
JSONParser jsonParser = new JSONParser();
JSONObject json;
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
RoomList details;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
Context mContext;
//private final Handler observerHandler;
public RoomListLoader(Context context,String nuser_id) {
super(context);
// TODO Auto-generated constructor stub
//mRoomList = nRoomList;
this.user_id = nuser_id;
this.mContext = context;
//observerHandler = new Handler();
}
#Override
public List<RoomList> loadInBackground() {
// TODO Auto-generated method stub
mRoomList.clear();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", user_id));
json = jsonParser.makeHttpRequest(url, "POST", params);
// final Context context = getContext();
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
rooms = json.getJSONArray(TAG_ROOMS);
// counter = json.getInt("counter");
counterOnGetRooms = json.getInt("count");
Log.d("counterOnGetRooms", "" + counterOnGetRooms);
// Log.v("counter", "" + counter);
for (int i = 0; i < rooms.length(); i++) {
tryme2++;
JSONObject c = rooms.getJSONObject(i);
// get room titles
roomTitle = c.getString("room_title");
retrievedRoomId = c.getString("room_id");
created_at = c.getString("created_at");
username = c.getString("username");
numOfComments = c.getString("counters");
filePath = c.getString("filePath");
Log.i("filePath", filePath);
details = new RoomList(retrievedRoomId, roomTitle,
created_at, username, numOfComments, filePath);
mRoomList.add(details);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//MostRecentRooms Room;
//deliverResult(mRoomList);
return mRoomList;
}
#Override
public void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
loadInBackground();
//deliverResult(mRoomList);
}
#Override
public void onCanceled(List<RoomList> data) {
// TODO Auto-generated method stub
super.onCanceled(data);
}
#Override
public void deliverResult(List<RoomList> data) {
// TODO Auto-generated method stub
Log.d("Deliver Result",""+data.size());
super.deliverResult(data);
}
#Override
protected void onReset() {
// TODO Auto-generated method stub
super.onReset();
onStopLoading();
}
#Override
protected void onStartLoading() {
// TODO Auto-generated method stub
if (mRoomList != null) {
//deliverResult(mRoomList);
}
super.onStartLoading();
}
#Override
protected void onStopLoading() {
// TODO Auto-generated method stub
cancelLoad();
}
}
Activity
public class MostRecentRooms extends ListActivity implements LoaderManager.LoaderCallbacks<List<RoomList>> {
// progress dialog
ProgressDialog pDialog;
// json parser object
JSONParser jsonParser = new JSONParser();
int decrement = 0;
int success;
int s = 0;
Activity mActivity;
// url to view most recent rooms
private static String url = "************8";
// url to load more rooms
private static String url3 = "***************";
// url to check status of user
private static String url2 = "*****************";
// url to get profile images
private static String url4 = "****************88";
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
int Loader_ID =0x3;
int counter = 0;
HashMap<String, String> map;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
RoomList details;
ListAdapter adapter;
public static RoomListAdapter mAdapter;
public static LoaderManager mLoadManager;
// json arrays
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
// Array list to hold room titles
ArrayList<HashMap<String, String>> allRooms;
// ArrayList<String> allRooms;
// List view to show room titles of an arraylist
public ListView lv;
// json Object
JSONObject json;
int limit = 20;
// strings
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
// buttons
Button back, loadMore, refresh;
Bitmap img_bitmap;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_most_recent_rooms);
mLoadManager = getLoaderManager();
mAdapter = new RoomListAdapter(this, getApplicationContext());
lv= getListView();
lv.setAdapter(mAdapter);
// back button
back = (Button) findViewById(R.id.backToMainMenu);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
// end back button
// get user id from View rooms class
if (getIntent().getExtras().getString("user_id_value") != null)
user_id = getIntent().getExtras().getString("user_id_value");
else
Log.e("Error", "Missing user_id");
mLoadManager.initLoader(Loader_ID,null,MostRecentRooms.this);
//allRooms = new ArrayList<HashMap<String, String>>();
// allRooms = new ArrayList<String>();
// call class GetAllRooms
//new GetAllRooms().execute();
// get room_id
if (getIntent().getExtras().getString("room_id_to_send") != null)
room_id = getIntent().getExtras().getString("room_id_to_send");
else
Log.e("Error", "Missing room id");
loadMore = (Button) findViewById(R.id.loadMore);
loadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//new LoadMoreRooms().execute();
// counter -= 5;
}
});
refresh = (Button) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mRoomList.clear();
allRooms.clear();
limit = 20;
tryme = 0;
img_bitmap.recycle();
//new GetAllRooms().execute();
}
});
}
/**
* This class get users status whether deleted or not
*/
class GetUserStatus extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
backGroundProcess(user_id);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("i is", "" + i);
if (i == 2) {
// decativatedPage();
Toast.makeText(getApplicationContext(), "noooo",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(getApplicationContext(), RoomPage.class);
i.putExtra("room_id_to_send", clickedOnRoomId);
i.putExtra("user_id_value", user_id);
startActivity(i);
}
}
}// end class
private void backGroundProcess(String string) {
// build parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", string));
json = jsonParser.makeHttpRequest(url2, "POST", params);
int success;
try {
success = json.getInt("success");
if (success == 1) {
i = 1;
Log.i("status", json.getString("message").toString());
} else if (success == 2) {
i = 2;
} else {
Log.d("Error", "Something went wrong");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Loader<List<RoomList>> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
Log.d("Tsg", "here");
RoomListLoader mRoomloader = new RoomListLoader(getApplicationContext(), user_id);
mRoomloader.forceLoad();
return mRoomloader ;
}
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
// TODO Auto-generated method stub
Log.i("tag","list loaded");
if(data != null){
mAdapter.SetData(data);
mAdapter.notifyDataSetChanged();
}
//mAdapter.SetData(data);
Log.i("Tag",""+data.size());
//lv.setAdapter(mAdapter);
}
#Override
public void onLoaderReset(Loader<List<RoomList>> arg0) {
// TODO Auto-generated method stub
Log.d("Loader", "Loader Reset");
mAdapter.SetData(null);
}
}
Adapter
public class RoomListAdapter extends ArrayAdapter<RoomList> {
ImageLoader imageLoader = null;
private Activity activity;
String TAG = "RoomListAdapter";
private final LayoutInflater mInflator;
List<RoomList> nRoomList;
public RoomListAdapter(Activity a, Context context) {
// TODO Auto-generated constructor stub
super(context, R.layout.viewroom_layout);
activity = a;
mInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(a.getApplicationContext());
//nRoomList = mRoomList;
//SetData(nRoomList);
}
public void SetData(List<RoomList> data) {
clear();
if (data != null) {
addAll(data);
}
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
#Override
public void setNotifyOnChange(boolean notifyOnChange) {
// TODO Auto-generated method stub
super.setNotifyOnChange(notifyOnChange);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi;
if (convertView == null) {
vi = mInflator.inflate(R.layout.viewroom_layout, null);
} else {
vi = convertView;
}
TextView room_id = (TextView) vi.findViewById(R.id.roomsIDHidden);
TextView room_title = (TextView) vi.findViewById(R.id.roomsName);
TextView created_at = (TextView) vi.findViewById(R.id.createdTime);
TextView username = (TextView) vi.findViewById(R.id.creatorName);
TextView numOfComments = (TextView) vi.findViewById(R.id.numComments);
ImageView image = (ImageView) vi.findViewById(R.id.userPic);
//Log.d(TAG, "Within the room list adapter");
RoomList info = getItem(position);
room_id.setText(info.getmRoom_id());
room_title.setText(info.getmRoomTitle());
created_at.setText(info.getmCreated_at());
username.setText(info.getmUsername());
numOfComments.setText(info.getmNumberOfComments());
imageLoader.DisplayImage(info.getmFilePath(), image);
return vi;
}
}
with the help of venkat and monica i solved it didn't need the Syncadpter all i needed was a broadcast receiver this i did by
1) creating a broad cast intent when GCM receives the message
Intent intent1 = new Intent();
intent1.setAction("com.gcm.updatecame");
this.sendBroadcast(intent1);
2) in my Activity i register the receiver and create the class
filter1= new IntentFilter("com.gcm.updatecame");
registerReceiver(myReceiver, filter1);
Broadcast Receiver
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// write your code here to update the listview.
if(mLoadManager != null){
Reload.setVisibility(View.VISIBLE);
Reload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mLoadManager.destroyLoader(Loader_ID);
mAdapter.notifyDataSetChanged();
mAdapter.SetData(null);
mRoomList.clear();
mLoadManager.initLoader(Loader_ID, null, MostRecentRooms.this);
Reload.setVisibility(View.INVISIBLE);
}
});
}
}
};
Replace you onLoadFinished method with this one:
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
if(data != null){
mAdapter = new RoomListAdapter(this, getApplicationContext());
mAdapter.SetData(data);
lv.setAdapter(mAdapter);
}
}
I have a problem with updating my table-layout from my async class.
MY async class is fetching XML data so I don't block the main thread. My logs show the XML data is coming through but I don't know how to update my view with the data.
So I am attempting to put the data in tablerows and add the rows to the TableLayout but the logs show errors suggesting the Async class is not allowed to update my TableLayout view.
My code is as follows:
public class RemotePrimary extends Activity {
private static String SERVER_PATH = "http://test2.icerge.com/";
private static String XML_FILE1 = "samplexml";
//private static String SERVER_PATH = "http://tqs.mamlambo.com/";
//private static String XML_FILE1 = "scores.jsp";
private String[] data = new String[10];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TableLayout datatable = (TableLayout)findViewById(R.id.TableLayout_data);
Downloader downloader = new Downloader();
downloader.execute(SERVER_PATH + XML_FILE1, datatable);
}
private class Downloader extends AsyncTask<Object, String, Boolean>{
TableLayout table;
#Override
protected Boolean doInBackground(Object... params) {
// TODO Auto-generated method stub
String path = (String)params[0];
table = (TableLayout)params[1];
XmlPullParser xmldata = null;
try {
URL serverPath = new URL(path);
xmldata = XmlPullParserFactory.newInstance().newPullParser();
xmldata.setInput(serverPath.openStream(), null);
addRecord(xmldata, table);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
//super.onProgressUpdate(values);
}
private boolean addRecord(XmlPullParser data, TableLayout table){
int eventType = -1;
boolean bFoundScores = false;
//find some records from xml
while(eventType != XmlResourceParser.END_DOCUMENT){
if( eventType == XmlResourceParser.START_TAG ){
//get the name of the tag(eg scores or score)
String strName = data.getName();
if( strName.equals("node") ){
bFoundScores = true;
String scoreValue = data.getAttributeValue(null, "Title");
String scoreRank = data.getAttributeValue(null, "Type");
String scoreUserName = data.getAttributeValue(null, "Nid");
Log.e("ADDING: ", scoreValue);
//Log.e("RETRIEVED", "collected : "+scoreValue+", "+scoreRank+", "+scoreUserName);
//publishProgress(scoreValue, scoreRank, scoreUserName);
TableRow newRow = new TableRow(RemotePrimary.this);
TextView rowText = new TextView(RemotePrimary.this);
rowText.setText(scoreValue);
newRow.addView(rowText);
table.addView(newRow);
}
}
try {
eventType = data.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}//close Downloader class
}//close RemotePrimary class
It's a bit much I know but I'll appreciate any help.
Thanks a great deal :-)
You can only make changes from the UI on the UI thread. The AsyncTask gives you an easy place to do this via onPostExecute. As it says in the docs, onPostExecute is always performed on the UI thread.
In doInBackground, do all of the hard work of building up the structured data that wish to display. Return that data so that it will be passed into onPostExecute, then in there add the appropriate table rows.