How to get live updates via JSON to listview - android

I couldn't find a way to get live updates via JSON to a listview.
My activity is requesting JSON data from a webpage and the code is:
public class Second extends Activity {
static final String Li_nk = "LinkName:";
static final String Image_name = "ImageName:";
ListView list;
public final static String AUTH = "authentication";
static final String KEY_THUMB_URL = "thumb_image"; // Uri.decode("http://zeesms.info/android_app_images/Koala.jpg");
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i2 = getIntent();
String wrd = i2.getStringExtra("entrd");
Log.v("keyis", wrd);
// if(wrd.equalsIgnoreCase("test")){
JSONObject j2 = JSONfunctions.getJSONfromURL("/webservice_search.php?keyword=" + wrd + "&format=json");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray jray = j2.getJSONArray("listings");
for (int i = 0; i < jray.length(); i++) {
Log.v("state", "json data being read");
JSONObject j3 = jray.getJSONObject(i);
String first = j3.getString("listing");
Log.v("sublist", first);
JSONObject j4 = j3.getJSONObject("listing");
String sec = j4.getString("links");
int maxLength = (sec.length() < 30) ? sec.length() : 27;
sec.substring(0, maxLength);
String cutsec = sec.substring(0, maxLength);
Log.v("links are", cutsec);
String img = j4.getString("image_name");
Log.v("image name is ", img);
// Uri
// dimg=Uri.parse("http://zeesms.info/android_app_images/Koala.jpg");
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", String.valueOf(i));
map.put(Li_nk, cutsec);
map.put(Image_name, j4.getString("image_name"));
map.put(KEY_THUMB_URL, "http://zeesms.info/android_app_images/" + img);
mylist.add(map);
}
}
catch (JSONException e) {
alertbox();
Log.e("loG_tag", "Error parsing" + e.toString());
}
list = (ListView) findViewById(R.id.lv1);
this.list.setEmptyView(findViewById(R.id.empty));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getApplicationContext(),"Click ListItem Number "
// + position, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.riffre.com/"));
startActivity(myIntent);
}
});
LazyAdapter adapter = new LazyAdapter(this, mylist);
list.setAdapter(adapter);
list.setItemsCanFocus(false);
// }
/*
* else{ alertbox(); }
*/
}
/*
* public void register(View view) { Log.w("C2DM",
* "start registration process"); Intent intent = new
* Intent("com.google.android.c2dm.intent.REGISTER");
* intent.putExtra("app", PendingIntent.getBroadcast(this, 0, new
* Intent(), 0)); // Sender currently not used intent.putExtra("sender",
* "nonsenses#gmail.com"); startService(intent); }
*
* public void showRegistrationId(View view) { SharedPreferences prefs =
* PreferenceManager .getDefaultSharedPreferences(this); String string =
* prefs.getString(AUTH, "n/a"); Toast.makeText(this, string,
* Toast.LENGTH_LONG).show(); Log.d("C2DM RegId", string);
*
* }
*/
public void alertbox() {
new AlertDialog.Builder(this).setMessage("Invalid Keyword,No Results found").setTitle("Alert").setCancelable(true).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
}).show();
}
}
and I'm using a custom adapter with the code as follows:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.custom_row_view1, null);
TextView title = (TextView)vi.findViewById(R.id.linkname); // merchnts name
TextView artist = (TextView)vi.findViewById(R.id.imagename); // address
//TextView duration = (TextView)vi.findViewById(R.id); // distance
ImageView thumb_image=(ImageView)vi.findViewById(R.id.mClogo); // logo
HashMap<String, String> jsn = new HashMap<String, String>();
jsn = data.get(position);
// Setting all values in listview
title.setText(jsn.get(Second.Li_nk));
artist.setText(jsn.get(Second.Image_name));
//duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(jsn.get(Second.KEY_THUMB_URL), thumb_image);
return vi;
}
}
What I want is that the application updates the listview with data every minute or so. Also the latest entry in the list should stay on top.
What would be the best way to do this?

Put your JSON parsing code, that's probably your try..catch block in a separate function and not in onCreate().
So can easily call that part every minute. let's say that function name LoadData() also add one more line adapter.notifyDataSetChanged() to update adapter/list every time.
now in your onCreate(), write this code to call that function every one minute,
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runable, 1000);
Now for second problem, to add new data at top..
I am just getting one thing in mind right now to write a loop , ADD THIS TO IN YOUR FUNCTION BEFORE CALLING ADAPTER NOTIFY CHANGE,like
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
ArrayList<HashMap<String,String>> mylistTemp = new ArrayList<HashMap<String,String>>();
for(int i = mylist.size()-1 ; i >=0;i--)
{
mylistTemp.add(mylist.get(i));
}
mylist = mylistTemp;

Well if your code above is working, you should be able to achieve your goal with the following steps:
Extract your JSON-Loading code into an AsyncTask, which you can trigger every minute. (AsyncTask)
Update your ListAdapter using the AsyncTask.

Here is a possible implementation of the onCreate() method, which will run an update-task every minute:
public class JSON_AndroidActivity extends Activity {
/** Called when the activity is first created. */
private JSONLoaderTask mJSONLoaderTask;
private Handler mHandler;
private ArrayAdapter<String> mArrayAdapter;
private Runnable mRefresher = new Runnable() {
#Override
public void run() {
mJSONLoaderTask = new JSONLoaderTask(JSON_AndroidActivity.this, mArrayAdapter);
mJSONLoaderTask.execute("");
mHandler.postDelayed(this, 1000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler.postDelayed(mRefresher, 1000);
}
}
And here is a hull implementation of a possible task, where you can do your heavy loading and update your adapter for the list:
public class JSONLoaderTask extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog progressDialog;
private final ArrayAdapter<String> mArrayAdapter;
public JSONLoaderTask(Context pContext, ArrayAdapter<String> pArrayAdapter) {
this.context = pContext;
this.mArrayAdapter = pArrayAdapter;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String result = getJSONStream();
return result;
}
private String getJSONStream() {
//load your string here
return "";
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
// Update your ArrayAdapter
}
}

Related

Android how to display arraylist index numbers in my dynamic listview

Sorry for my English,How i can show arraylist index numbers in my dynamic listview?
for example in my app when listview display,in a listview every cell have a index number display like first cell 1,second cell 2,third cell 3 and so on..how i can implement this?Thanks in advance.
This is the screen shot:
in my screen shot see the left int number 1.and now want to in 2nd cell display 2 and so on..
This is my 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 = "My URL";
// 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;
}
}
just want to display my arraylist cells serialwise like first cell is 1,2nd cell 2 and so on
in your listview adapter, on getView() method, you can use the position for that purpose. If you don't have any textView to show the number, first add it to your listview item, then use it in getView() method
Add a new textview to show your position number;
static class ViewHolder {
TextView mNameTxt = null;
TextView mSeqNo; //new
}
Then use it in getView() method,
#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) {
// rest of your code
mHolder.mSeqNo = (TextView)row.findViewById(R.id.your_text_view);
row.setTag(mHolder);
} else {
// recycling of cells
mHolder = (ViewHolder) row.getTag();
}
//rest of your code
mHolder.mSeqNo.setText("" + position);
return row;
}
Using the position param in getView method is sufficient. It starts from 0 (the first index), then 1, 2,3 ...
mHolder.mSeqNo.setText("" + (position+1));
This would start the seq numbers from 1, like 1, 2, 3,..... and so on to the end of the list. But giving mHolder.mSeqNo.setText("" + (position) starts your number from 0, since list starts with 0 (the first value of index). All the best!

Android app shows listview only after running for the second time

My app is supposed to get some info from a website (JSON format), parse it, store it in a SQLite database, then show a list of items (obtained from the database) in a list view. It does everything (checked with Log.v messages) except populate the listview. But if I run it for the second time the listview is displayed.
In MainActivity I use an AsyncTask to get the data after it is parsed. Then I start another activity to read data from a table (all rows) and display them in the ListView.
public class MainActivity extends Activity {
private MySQLiteHelper dbHelper;
private SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://strong-earth-32.heroku.com/stores.aspx";
dbHelper = new MySQLiteHelper(this);
db = dbHelper.getWritableDatabase();
ConnectAsyncTask connect = new ConnectAsyncTask(url);
connect.execute();
try {
connect.wait(2000);
} catch (Exception e) {
Log.v("Waiting. ",e.getStackTrace().toString());
}
Intent intent=new Intent(MainActivity.this,DisplayActivity.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void cacheData(String result) {
ContentValues cv = new ContentValues();
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("stores");
for(int i = 0; i < jArray.length(); i++) {
try{
JSONObject oneObject = jArray.getJSONObject(i);
String logoURL = oneObject.getString("storeLogoURL");
String address = oneObject.getString("address");
cv.put(MySQLiteHelper.COLUMN_ADDRESS, address);
String phoneNr = oneObject.getString("phone");
cv.put(MySQLiteHelper.COLUMN_PHONE, phoneNr);
long row = db.insert(MySQLiteHelper.TABLE_STORES, MySQLiteHelper.COLUMN_ID, cv);
//Log.v("row= ", row + "");
cv.clear();
} catch (JSONException e) {
Log.v("Oops! ",e.getStackTrace().toString());
}
}
} catch (JSONException e) {
Log.v("ERR",e.getStackTrace().toString());
}
}
private class ConnectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
ConnectAsyncTask(String urlPass){
url = urlPass;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching data, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
JSONparser jParser = new JSONparser();
String json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
progressDialog.dismiss();
if (result!=null) {
Log.v("READY","READY");
cacheData(result);
}
}
}
}
Here's the other activity:
public class DisplayActivity extends Activity {
private MySQLiteHelper dbHelper;
private SQLiteDatabase db;
private ListView lv_custom;
ArrayList<Content> contents = new ArrayList<Content>();
Content content0 = new Content();
Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
lv_custom = (ListView) findViewById(android.R.id.list);
dbHelper = new MySQLiteHelper(this);
db = dbHelper.getWritableDatabase();
readData(db);
lv_custom.setAdapter(new CustomListviewAdapter(this, R.layout.one_row, contents));
}
private class Content {
private String logoURL;
private String phoneNr;
private String address;
}
private class ViewHolder{
WebView webView;
TextView textViewPhone;
TextView textViewAddress;
}
private class CustomListviewAdapter extends BaseAdapter{
private int layoutResource;
private ArrayList<Content> mArrayList;
private LayoutInflater inflater;
public CustomListviewAdapter(Context mContext, int layoutResource, ArrayList<Content> mArrayList) {
this.layoutResource = layoutResource;
this.mArrayList = mArrayList;
inflater = LayoutInflater.from(mContext);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mArrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
convertView = inflater.inflate(layoutResource, null);
viewHolder = new ViewHolder();
//WebView web = (WebView) findViewById(R.id.webView1);
//web.loadUrl("Your Url");
//viewHolder.webView = (WebView) findViewById(R.id.webView1);
viewHolder.textViewPhone = (TextView) convertView.findViewById(R.id.phoneNr);
viewHolder.textViewAddress = (TextView) convertView.findViewById(R.id.address);
//viewHolder.webView.loadUrl(mArrayList.get(position).logoURL);
viewHolder.textViewPhone.setText(mArrayList.get(position).phoneNr);
viewHolder.textViewAddress.setText(mArrayList.get(position).address);
//int itemHeight = height/4 - 10;
//viewHolder.webView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, itemHeight));
return convertView;
}
}
public void readData(SQLiteDatabase db) {
String[] selectionArguments = {};
c = db.rawQuery("SELECT * FROM storesList", selectionArguments);
if (c.getCount() != 0) {
try {
while (c.moveToNext()) {
//add a new store information to the ArrayList
content0 = new Content();
//content0.logoURL = logoURL;
content0.phoneNr = c.getString(2);
content0.address = c.getString(1);
contents.add(content0);
Log.v("address:", content0.address);
}
} catch (Exception e) {
Log.v("Exception e ",e.fillInStackTrace().toString());
}}
else Log.v("Cursor ", 0+"");
}
}
Why don't I see the list from the first execution of the app? I guess it has something to do with the second activity starting before the AsyncTask is done. However, I don't have a solution to fix the problem. Besides, I don't see the ProgressDialog. Any idea?
Try to call start second activity within onPostExecute of your MainActivity.java.
Remove below code from onCreate() of MainActivity.java
Intent intent=new Intent(MainActivity.this,DisplayActivity.class);
startActivity(intent);
and replace onPostExecute like below
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
progressDialog.dismiss();
if (result!=null) {
Log.v("READY","READY");
cacheData(result);
Intent intent=new Intent(MainActivity.this,DisplayActivity.class);
startActivity(intent);
}
}
Why don't I see the list from the first execution of the app?
because you are starting another Activity just after calling execute method of AsyncTask. to display data in second activity you will need to start second Activity after inserting data in db inside cacheData method :
public void cacheData(String result) {
//your code for inserting data in db
....
//start second Activity here
Intent intent=new Intent(MainActivity.this,DisplayActivity.class);
startActivity(intent);
}

adding data to existing listview

I have created listview using the following code
public class homeScreen extends Activity{
ArrayList<SingleRow> list;
boolean flag = false;
String space = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
final Context c = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
//putting actual values in array
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i = 0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
final ListView list1 = (ListView)findViewById(R.id.spacelist);
final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
list1.setAdapter(adapter);
space = getIntent().getStringExtra("spaceName");
if(null! = space){
adapter.addView(space);
}
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
if((titles[position]).equalsIgnoreCase("My Ideas")){
Intent i = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(i);
} else if((titles[position]).equalsIgnoreCase("Create New Space")){
Intent i = new Intent(homeScreen.this, createNewSpace.class);
startActivity(i);
}
}
});
}
}
Row class:
class SingleRow{
String title;
int image;
public SingleRow(String title,int image) {
this.title = title;
this.image = image;
}
}
Adapter:
class MySimpleAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
private Context context;
public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
this.context = c;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void addView(String space) {
int rows = this.getCount();
list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewgroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,viewgroup,false);
TextView title = (TextView)row.findViewById(R.id.label);
ImageView image = (ImageView)row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
image.setImageResource(temp.image);
return row;
}
}
code for create new space
public class createNewSpace extends Activity{
Button add;
TextView sname,pname;
ListView plist;
int success;
Jparser jsonParser = new Jparser();
JSONObject json;
private ProgressDialog pDialog;
ArrayList<String> usersList;
ArrayList<String> spaceUsers;
private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UNAME = "firstName";
// products JSONArray
JSONArray users = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createnewspace);
sname=(TextView)findViewById(R.id.spaceName);
pname=(TextView)findViewById(R.id.participents);
plist=(ListView)findViewById(R.id.participantlist);
add=(Button)findViewById(R.id.button1);
// Hashmap for ListView
usersList= new ArrayList<String>();
spaceUsers=new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new getAllUsers().execute();
}
});
plist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String users[]=usersList.toArray(new String[usersList.size()]);
Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();
spaceUsers.add(users[arg2]);
}
});
// Loading users in Background Thread
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menuspace, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return MenuChoice(item);
}
private boolean MenuChoice(MenuItem item)
{
switch(item.getItemId())
{
case R.id.create:
new createSpace().execute();
return true;
}
return false;
}
class createSpace extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i=0;i<spaceUsers.size();i++)
{
String sname1 = sname.getText().toString();
String uname = spaceUsers.get(i);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sname", sname1));
params.add(new BasicNameValuePair("uname", uname));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_space,
"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully inserted user details
Intent is = new Intent(getApplicationContext(), homeScreen.class);
is.putExtra("spaceName", sname1);
startActivity(is);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
class getAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON Object
json = jsonParser.makeHttpRequest(url_users,"GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// getting value of success tag
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
// Getting Array of users
try{
JSONArray users=json.getJSONArray(TAG_USERS);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
Log.d("check", "success");
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_UNAME);
Log.d("name....",name);
// adding HashList to ArrayList
usersList.add(name);
}
} catch(JSONException e)
{
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList));
}
});
}
}
}
Now I want to add Item to this existing list.
I am taking data from another activity using intent.
Now one item get added.but next time that get replaced.
Please Help.
Thank you in advance.
You should move the creation of the data outside of the adapter:
list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i=0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
Pass the list variable to the adapter and store a reference to it there. Then you can just update the data in the list variable, and call notifyDataSetChanged() on your adapter.
Edit: It seems you want to store the space values, and then retrieve them in the HomeScreen activity later. If I understand the flow of your app correctly, then the createNewSpace class should store the space in SharedPreferences. Then in the HomeScreen activity you should retrieve those from the SharedPreferences, and show them.
You can add data to the adapter and call notifyDataSetChanged().Alternatively, You can create a new adapter and listView.setAdapter(adapter) that adapter.

Android search in Listview using baseadapter

I try to add search list form City list using my base adapter but it doesn't work. I want to search City in cities list. Here's My code.
My CitySerach :
private ProgressDialog pDialog;
EditText inputSearch;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// Hashmap for ListView
ArrayList<HashMap<String, String>> CitiesLI = new ArrayList<HashMap<String, String>>();
// url to make request
private static String url_cityli = "http://10.0.2.2/Myweb/ecities.php";
// JSON Keys
public static final String TAG_CITEMS_LI = "cities_li";
public static final String TAG_CID_LI = "city_id";
public static final String TAG_CNAME_LI = "city_name";
public static final String TAG_CIMG_LI = "image";
JSONArray cities_li = null;
ListView list;
CitySearchAdapter adapter;
private CitySearch activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tt);
CitiesLI = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.city_list);
//list click to details view of the place
list.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String cid_li = ((TextView) view.findViewById(R.id.cid_li)).getText().toString();
Intent i = new Intent(getApplicationContext(),
//Tab.class);
CityInfoActivity.class);
// Starting new intent
i.putExtra(TAG_CID_LI, cid_li);
startActivity(i);
//startActivityForResult(i, 100);
}
});
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new CitySearchAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CitySearch.this);
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray json = jParser.makeHttpRequest(url_cityli, "GET",
params);
Log.d("All Products: ", json.toString());
// looping through All data
try {
cities_li = json;
for (int i = 0; i < cities_li.length(); i++) {
JSONObject c = cities_li.getJSONObject(i);
// Storing each json item in variable
String city_id = c.getString(TAG_CID_LI);
String city_name =c.getString(TAG_CNAME_LI);
String image = c.getString(TAG_CIMG_LI);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//JSON Object
map.put(TAG_CID_LI, city_id);
map.put(TAG_CNAME_LI,city_name);
map.put(TAG_CIMG_LI, image);
// adding HashList to ArrayList
CitiesLI.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
SetListViewAdapter(CitiesLI);
//
// Enabling Search Filter
CitySearchAdapter adapter;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Listview name of the class
CitySearch.this.adapter.getFilter().filter(s);
}
#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
}
});
}
});
}
}
}
Here my CitylistAdapter :
public class CitySearchAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public CitySearchAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.te, null);
TextView city_id = (TextView) vi.findViewById(R.id.cid_li);
TextView image = (TextView) vi.findViewById(R.id.cimg_li);
TextView city_name = (TextView) vi.findViewById(R.id.cname);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.cimage);
HashMap<String, String> city_li = new HashMap<String, String>();
city_li = data.get(position);
city_id.setText(city_li.get(CityActivity.TAG_CID_LI));
image.setText(city_li.get(CityActivity.TAG_CIMG_LI));
city_name.setText(city_li.get(CityActivity.TAG_CNAME_LI));
imageLoader.DisplayImage(city_li.get(CityActivity.TAG_CIMG_LI),thumb_image);
return vi;
}
public Object getFilter() {
// TODO Auto-generated method stub
return null;
}
}
Pleace Help me.
Thanks all

Activity reloads the whole data from server again when coming back from an other activity in Android

Basically, I'm working on a app which has a tab-activity including 4 tabs and also I'm using the actvityGroup to manage the activities and backKey pressed() method.
When my app first starts it sends a request to server and shows the progress bar (using AsyncTask) as shown in below image.
After this, my complete UI appears as
it loads new actvity on click event of button "GO" (code is given below)
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
bookSearchResultActivityIntent.setClass(getParent(),
BookSearchResultActivity.class);
bookSearchResultActivityIntent.putExtra("LANG", language);
bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS",
edTxt_SearchField.getText().toString());
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BooksSearchActivity",
bookSearchResultActivityIntent);
also here is my ActivtyGroup.java code
public class MyActivityGroup extends ActivityGroup {
private Stack<String> stack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null) {
stack = new Stack<String>();
}
push("1stStackActivity", new Intent(this, Home.class));
}
#Override
public void finishFromChild(Activity child) {
pop();
}
#Override
public void onBackPressed() {
pop();
}
public void push(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
stack.push(id);
setContentView(window.getDecorView());
}
}
public void pop() {
if (stack.size() == 1) {
finish();
}
LocalActivityManager manager = getLocalActivityManager();
manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window newWindow = manager.startActivity(stack.peek(), lastIntent);
setContentView(newWindow.getDecorView());
}
}
}
ok now my question is that when i press the backKey(); it should come to the previous actvity.
Yes it comes to the previous activity but it send request to the server again and shows the progress bar again and loads until the server sends response. it wastes my time.
I only want to load the HomeTab just once (when i play the app). not again and again
I am also adding the
setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
while starting the activity
also added following code in menifest.xml file
android:configChanges="keyboard|keyboardHidden|orientation"
but not working yet.
and here is the code of my Home tab(which sends the request to server in onCreate method)
public class Home extends Activity {
/** Called when the activity is first created. */
static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx";
static final String KEY_ITEM = "Book"; // parent node
static final String KEY_BOOKAUTHOR = "BookAuthor";
static final String KEY_BOOKDATEPUBLISHED = "DatePublished";
static final String KEY_BOOKTITLE = "BookTitle";
static final String KEY_BOOKCODE = "BookCode";
static final String KEY_BOOKIMAGE = "BookImage";
String searchLang;
String searchKeywords;
LayoutInflater inflater = null;
ArrayList<String> BookTitle = new ArrayList<String>();
ArrayList<String> BookCoverPhotos = new ArrayList<String>();
ArrayList<String> BookAuther = new ArrayList<String>();
ArrayList<String> BookPublishDate = new ArrayList<String>();
ArrayList<String> ImageByte = new ArrayList<String>();
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
Context ctx = this;
Activity act = this;
Context context = Home.this;
URL bookImageURL = null;
Bitmap bitMapImage = null;
Button btnGo;
Spinner spnrLanguage;
Spinner spnrBrowseBy;
String language;
EditText edTxt_SearchField;
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.home_activity);
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(
R.layout.home_activity, null);
this.setContentView(viewToLoad);
gridView = (GridView) findViewById(R.id.gridview);
spnrLanguage = (Spinner) findViewById(R.id.spnrLanguage);
spnrBrowseBy = (Spinner) findViewById(R.id.spnrBrowseBy);
edTxt_SearchField = (EditText) findViewById(R.id.EditTxt_Search);
btnGo = (Button) findViewById(R.id.btn_GO);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// checking for availbe internet Connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new UIThread().execute(URL, "Imam Ali");
}
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(context, BookTitle.get(pos), Toast.LENGTH_SHORT)
.show();
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent.setClass(getParent(),
BookOverView.class);
bookSearchResultActivityIntent.putExtra("BITMAP",
bitmapArray.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_TITLE",
BookTitle.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_AUTHOR",
BookAuther.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_PUBLISH_DATE",
BookPublishDate.get(pos));
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BookOverViewActivity",
bookSearchResultActivityIntent);
}
});
// //////////////////// Spinners handler/////////////////////////
ArrayAdapter<String> adapterLanguage = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.spnr_language_array));
ArrayAdapter<String> adapterBrowseBy = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.spnr_browse_array));
spnrLanguage.setAdapter(adapterLanguage);
spnrBrowseBy.setAdapter(adapterBrowseBy);
spnrLanguage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(getParent(),
spnrLanguage.getItemAtPosition(pos) + "",
Toast.LENGTH_SHORT).show();
language = spnrLanguage.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spnrBrowseBy.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(context,
spnrBrowseBy.getItemAtPosition(pos) + "",
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// ////////////////////Search Button Handler/////////////////
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!edTxt_SearchField.getText().toString().equals("")) {
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
bookSearchResultActivityIntent.setClass(getParent(),
BookSearchResultActivity.class);
bookSearchResultActivityIntent.putExtra("LANG", language);
bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS",
edTxt_SearchField.getText().toString());
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BooksSearchActivity",
bookSearchResultActivityIntent);
} else {
Toast.makeText(context, "Search Field Empty",
Toast.LENGTH_SHORT).show();
}
}
});
}
private class UIThread extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(getParent(),
"Acumlating Books from server...",
"This may Take a few seconds.\nPlease Wait...");
}
#Override
protected String doInBackground(String... params) {
String URL = params[0];
String searchKeywords = params[1];
XMLParser parser = new XMLParser();
String XMLString = parser.getXmlFromUrl(URL, searchKeywords,
searchLang);
// Log.i("XML Response", XMLString);
Document doc = parser.getDomElement(XMLString);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
BookTitle.add(parser.getValue(e, KEY_BOOKTITLE));
BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/"
+ parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg");
BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR));
BookPublishDate.add(parser.getValue(e, KEY_BOOKDATEPUBLISHED));
Log.i("URLs", BookCoverPhotos.toString());
}
for (int i = 0; i < BookAuther.size(); i++) {
try {
bookImageURL = new URL(BookCoverPhotos.get(i));
} catch (MalformedURLException e) {
e.printStackTrace();
Log.i("URL", "ERROR at image position" + i + "");
}
try {
bitMapImage = BitmapFactory.decodeStream(bookImageURL
.openConnection().getInputStream());
bitmapArray.add(bitMapImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("BITMAP", "ERROR" + i);
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
ImageAdapter adapter = new ImageAdapter(getBaseContext(), act);
gridView.setAdapter(adapter);
}
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
context = c;
}
// ---returns the number of images---
public int getCount() {
// return imageIDs.length;
return bitmapArray.size();
// return 6;
}
public ImageAdapter(Context ctx, Activity act) {
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
// ImageView bmImage;
final ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.grid_style, parent, false);
holder = new ViewHolder();
holder.txt_BooksTitle = (TextView) vi
.findViewById(R.id.txt_BookTitle);
holder.img_BookCoverPhoto = (ImageView) vi
.findViewById(R.id.imgBookCover);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txt_BooksTitle.setText(BookTitle.get(position) + "");
holder.img_BookCoverPhoto.setImageBitmap(bitmapArray.get(position));
return vi;
}
}
class ViewHolder {
TextView txt_BooksTitle;
ImageView img_BookCoverPhoto;
}
}
please have a look on my activity group class and tell what should i do.
thanks in advance
When loading your data in the Home Tab activity, put it inside some static arrays.
ArrayList<String> BookTitle = new ArrayList<String>();
ArrayList<String> BookCoverPhotos = new ArrayList<String>();
ArrayList<String> BookAuther = new ArrayList<String>();
ArrayList<String> BookPublishDate = new ArrayList<String>();
ArrayList<String> ImageByte = new ArrayList<String>();
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
From a quick glimpse on the code, make them static ArrayList<...> ... = null; and check inside the onCreate() method:
if(BookTitle == null)
{
//needs init
BookTitle = new ArrayList<String>();
//perform connect to server and parse response.
}
When the application activity home tab is stopped then restarted, the data will be in memory already and it will skip the if clause keeping the old data for re-use.
Make sure you will clear the static variables when you really want to kill the app - on a quit button click, call a static method to init them to null again, or if you want them to be valid for let's say 12 hours, memorize the timestamp in a static variable and each time you kill/pause the main activity perform a check on it (wheather is null or has a date, if it has a date, check if 12 hours have passed, if yes, clear the static variable contents)
This is the quick and easy way. Another way is to store them in the application database if you don't want to deal with static variables.
There are a lot of options, the point is you kinda have to mark them as "global persistent" data with static, or store them in a databse / file etc.

Categories

Resources