How to set Icons into ListItems dynamically? - android

I have a ListView whose list item comes from a 'String' from Shared Preference. Now I have to set two icons "success" and "failed" identifying those keywords "successful" and "failed" from string. But while setting it is either setting "success" icons to all listitems or "failed" icons to all reason because string contains both. Any idea how can i identify each list items and set icons to them ? Below is my code :
Class where I am retrieving "oldlistitems" and "newlistitems" strings from Shared Preference and trying to set icons to listitems
public class EntryAdapterLog extends ArrayAdapter<Item> {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
public EntryAdapterLog(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());
}else{
String oldlistitems = LogListView.first;
String newlistitems = LogListView.title;
Log.d("LOG", "ABCD : " + oldlistitems);
Log.d("LOG", "DEFG : " + newlistitems);
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry_log, null);
final TextView title = (TextView)v.findViewById(R.id.list_item_entry_title);
final TextView subtitle = (TextView)v.findViewById(R.id.list_item_entry_summary);
final ImageView imageicon = (ImageView)v.findViewById(R.id.list_item_entry_drawable);
if(title != null) {
title.setText(ei.title);
}
if(subtitle != null){
subtitle.setText(ei.subtitle);
}
//HERE IS PROCESS OF SETTING ICONS
if ((oldlistitems !=null && oldlistitems.contentEquals("Sync Successful")) || (newlistitems != null && newlistitems.contentEquals("Sync Successful"))){
imageicon.setImageResource(R.drawable.ok);
}
else {
imageicon.setImageResource(R.drawable.wrong);
}
}
}
return v;
}
}
Class where i am setting shared preference
public class LogListView extends ListActivity {
/** Called when the activity is first created. */
static String newString;
private static EntryAdapterLog adapter;
int clickCounter = 0;
static ArrayList<Item> items = new ArrayList<Item>();
static SharedPreferences preferences = null;
private static Context context = null;
static StringTokenizer tokens;
static String first;
private static String second;
private JSONArray jsonarry = null;
static String saveitems;
private JSONObject jsonobject = null;
private String subtitle;
static String title;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
adapter = new EntryAdapterLog(this, items);
// items.add(new SectionItem("Log Report"));
setListAdapter(adapter);
if (adapter.getCount() != 0) {
// Do nothing Adapter has value
} else {
retreiveItems();
}
}
// Method which will handle dynamic insertion
public static void addItems() {
preferences = context.getSharedPreferences("LOG",android.content.Context.MODE_PRIVATE);
newString = preferences.getString("log", "");
tokens = new StringTokenizer(newString, ",");
first = tokens.nextToken();
second = tokens.nextToken();
items.add(new EntryItem(first, second));
adapter.notifyDataSetChanged();
}
// Method which will handle dynamic insertion ends
#Override
protected void onDestroy() {
super.onDestroy();
saveItems();
}
// Save ListItems if restarted
protected static void saveItems() {
SharedPreferences prefs = context.getSharedPreferences("prefName",Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("myList", new Gson().toJson(items).toString());
editor.apply();
Log.d("LOG", "Saved Items : " + items);
}
// Save ListItems if restarted ends
// Retrieve ListItems if restarted
protected void retreiveItems() {
preferences = context.getSharedPreferences("prefName",android.content.Context.MODE_PRIVATE);
saveitems = preferences.getString("myList", "");
Log.d("LOG", "Retreived Items : " + saveitems);
try {
jsonarry = new JSONArray(saveitems);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonarry == null || jsonarry.length() == 0) {
return; //This checks before setting adapter onCreate if adapter is null
}
for (int i = 0; i < jsonarry.length(); i++) {
try {
jsonobject = jsonarry.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
// get all values here from JSONObject
title = jsonobject.optString("title");
subtitle = jsonobject.optString("subtitle");
items.add(new EntryItem(title, subtitle));
adapter.notifyDataSetChanged();
}
}
// Retrieve ListItems if restarted ends
// Counter for amount of period of time before flusing adapter
protected void flushList(){
}
// Counter for amount of period of time before flusing adapter ends
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if (!items.get(position).isSection()) {
items.get(position);
Toast.makeText(this, "You clicked " + position, Toast.LENGTH_SHORT).show();
}
if (position == 9) {
}
super.onListItemClick(l, v, position, id);
}
}
Regards

If I understand correctly, you want to update the icon for each item, based on if sync successful or sync failed for that item.
You should do something like this (update your code accordingly):
//HERE IS PROCESS OF SETTING ICONS
if ((ei.title.contains("Sync Successful")) {
imageicon.setImageResource(R.drawable.ok);
}
else {
imageicon.setImageResource(R.drawable.wrong);
}

First of all your adapter will laggy when you will have big number of list items, you should use ViewHolder pattern as is described HERE
Second, it will be better to get all the data from sharedPreferences and store them in an ArrayList and give that list to adapter, Reading and Writing to SharedPreferences is an expansive operation.
Also to handle if the sync is success or fail use a boolean in your Item object, and in the adapter just chec that boolean and like this change the drawable of the list item.

Related

Android Getting Bound Object from OnClick

I'm totally stuck with something. I'm trying to do simple de-reference of a clicked object in Android environment but for the life of me can't find a way.
I have a MainView where I load json objects and I pass these objects to my adapter where I find these to a list. I have onClick on a TextView items in a list to capture click events.
Issue: the OnClick fires but I can't get back the original bound object from there, or I'm not sure how? I was trying to use a position variable that increments when getView function gets called for each row, but my position when OnClick happens always points to the last record in my list. I also tried implementing onItemClick in MainView but that never seems to fire.
How can I get back the object I bound to my TextView? Thank you in advance for any assistance with this.
public class MainActivity extends AppCompatActivity {
private static final String LOCATION_KEY = "location";
SharedPreferences pref;
SharedPreferences.Editor editor;
public JSONObject jsonObj = null;
ListView mainList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.digitour.www.R.layout.activity_main);
// Load state from shared preferences
pref= getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor=pref.edit();`enter code here`
mainList = (ListView) findViewById(com.digitour.www.R.id.checkableList);
try {
jsonObj=new JSONObject(pref.getString("json",null));
// Bind Data and pass the json object read from a file to the adapter
MainViewAdapter customListViewAdapter = new MainViewAdapter(this, jsonObj);
mainList.setAdapter(customListViewAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the adapters code:
public class MainViewAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private Context context;
private JSONArray listItems;
private int positionPrivate;
private JSONObject jsonObj;
public MainViewAdapter(Context context, JSONObject jsonObj) {
layoutInflater = LayoutInflater.from(context);
this.context = context;
this.jsonObj = jsonObj;
JSONObject jObjectResult = null;
try {
jObjectResult = jsonObj.getJSONObject("Items");
this.listItems = jObjectResult.getJSONArray("Item");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final SharedPreferences pref= context.getApplicationContext ().getSharedPreferences("MyPref", context.MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
try {
positionPrivate = position;
if(convertView == null){
convertView = layoutInflater.inflate (com.digitour.www.R.layout.activity_row,parent,false);
}
TextView textView = (TextView) convertView.findViewById (com.digitour.www.R.id.rowText);
textView.setText(listItems.getJSONObject(position).getString ("description"));
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
//Trying to get here the bound object
TextView tv = (TextView)v;
int id = tv.getId();
if (listItems != null){
JSONObject clickedItem = listItems.getJSONObject(positionPrivate); // positionPrivate always indexed to last item in a list
Intent intent = new Intent(context, DetailActivity.class);
context.startActivity(intent);
}
} catch (Exception e){
e.printStackTrace();
}
}
});
return convertView;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
You have a single member variable private int positionPrivate that you store the index in. It can only hold one index, so ends up with the last index that was written to it.
Try removing this variable and just use the position parameter in your getView function.
JSONObject clickedItem = listItems.getJSONObject(position);
I think what you are looking for is a setTag(Object tag) method.
textView.setTag(position)
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) textView.getTag()
if (listItems != null) {
JSONObject clickedItem = listItems.getJSONObject(position);
...
}
}
}

How to fetch the image using JSON in ListFragment?

I am new to android development,I am parsing my data using JSON Parsing method,I extend my class with List Fragment and I want my data in list view but the problem is i am getting all the data perfectly except the images,i don't know how to solve it,my response looks like this
{"matching":[{"name":"Monic Dano","profile_id":"GM335695","image":"http://mywebsitename.com/images/Girlnoimage.jpg","cast":"","age":"24","location":"Ivory Coast"}]}
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://mywebsitename.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// Storing each json item values in variable
String user_name = c.getString(TAG_NAME);
String user_profile=c.getString(TAG_PROFILE);
String user_image=c.getString(TAG_IMAGE);
String user_cast=c.getString(TAG_CAST);
String user_age=c.getString(TAG_AGE);
String user_location=c.getString(TAG_LOCATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME,user_name);
map.put(TAG_PROFILE, user_profile);
map.put(TAG_IMAGE, user_image);
map.put(TAG_CAST, user_cast);
map.put(TAG_AGE, user_age+" years");
map.put(TAG_LOCATION, user_location);
// adding HashList to ArrayList
aList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
// updating listview
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
}
Try to AndroidQuery with custom adapter :
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propic);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtproname);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproid);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecast);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileage);
holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplace);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}
How to set adapter to ListView :
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
You can use universal image loader for viewing images from your server.Z
Just pass the image url and your view and you are good to go.
For your reference here is the link to Universal Image loader with all its documentation.
https://github.com/nostra13/Android-Universal-Image-Loader
Hop it helps you.
I am hardly suggest you to use Android Query for this. Its mind blowing api given by Android itself. You can download image, download bitmap or whatever you wanna do you can.
You can download the jar file from here :here Download the jar file and set jar to your Build Path.
AQuery androidAQuery=new AQuery(this);
As an example to load image directly from url:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
As an example to get Bitmap from url:
androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
//You will get Bitmap from object.
}
});
It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.
//Declare adapter globally.
private EfficientAdapter adapter;
//Initialize it in onCreate() method
adapter = new EfficientAdapter(this);
//Set your adapter like
listview.setAdapter(adapter);
//Adapter class code
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return aList.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.YOUR ITEM LAYOUT, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
holder.txtProfile = (TextView) convertView.findViewById(R.id.txtProfile);
holder.txtCast = (TextView) convertView.findViewById(R.id.txtCast);
holder.txtAge = (ImageView) convertView.findViewById(R.id.txtAge);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(aList.get(position).get(TAG_NAME));
holder.txtProfile.setText(aList.get(position).get(TAG_PROFILE));
holder.txtCast.setText(aList.get(position).get(TAG_CAST));
holder.txtAge.setText(aList.get(position).get(TAG_AGE));
aQuery.id(holder.imgUser).image(data.get(position).get(TAG_IMAGE), true, true);
return convertView;
}
class ViewHolder {
TextView txtName;
TextView txtProfile;
TextView txtCast;
TextView txtAge;
ImageView imgUser;
}
}
In source code of SimpleAdapter:
private void bindView(int position, View view) {
final Map dataSet = mData.get(position);
if (dataSet == null) {
return;
}
final ViewBinder binder = mViewBinder;
final String[] from = mFrom;
final int[] to = mTo;
final int count = to.length;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
final Object data = dataSet.get(from[i]);
String text = data == null ? "" : data.toString();
if (text == null) {
text = "";
}
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, data, text);
}
if (!bound) {
if (v instanceof Checkable) {
if (data instanceof Boolean) {
((Checkable) v).setChecked((Boolean) data);
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else {
throw new IllegalStateException(v.getClass().getName() +
" should be bound to a Boolean, not a " +
(data == null ? "<unknown type>" : data.getClass()));
}
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
if (data instanceof Integer) {
setViewImage((ImageView) v, (Integer) data);
} else {
setViewImage((ImageView) v, text);
}
} else {
throw new IllegalStateException(v.getClass().getName() + " is not a " +
" view that can be bounds by this SimpleAdapter");
}
}
}
}
}
You can see if your view is ImageView , the code will use the url String be the resId in
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* By default, the value will be treated as an image resource. If the
* value cannot be used as an image resource, the value is used as an
* image Uri.
*
* This method is called instead of {#link #setViewImage(ImageView, int)}
* if the supplied data is not an int or Integer.
*
* #param v ImageView to receive an image
* #param value the value retrieved from the data set
*
* #see #setViewImage(ImageView, int)
*/
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
And your error is here , so you need Override the getView function of SimpleAdapter.Here is code:
Uri uri = Uri.parse("http://gujjumatch.com/images/Girlnoimage.jpg");
image.setImageURI(uri);
You need to create adapter and extend it to BaseAdapter and add all your items and call it in your AsyncTask's method and it will return your output as said by Haresh Chellana.

ListView disappears after reloading it again

I have 3 arraylist that i have combined to show in listview. Wehen i click on to generate listview, it works fine the first time but when i hit back and then click the button again, the listview shows nothing. Not sure what is cause it. I checked other post but couldnt find an answer. I am not too good with Arraylist so any details would be greatly appreciated.
I have also noticed this message in Log cat. not sure what it means.
onVisibilityChanged() is called, visibility : 0
public class Edit extends Activity implements OnItemClickListener {
private int pic;
public String filename ="User Info";
//Declaring SHareddPreference as userprofile
static SharedPreferences userprofile;
ListView listView;
List<RowItem> rowItems;
// String[] titles, descriptions;
File imgpath=null;
Context context=this;
CustomListAdapter adapter;
private List<String> Titles = new ArrayList<String>();
private List<String> Actions = new ArrayList<String>();
private List<Bitmap> Images = new ArrayList<Bitmap>();
int x;
int y=1;
int z=1;
static int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aname);
listView = (ListView)findViewById(R.id.listing);
userprofile = getSharedPreferences(filename,0);
Intent pdf=getIntent();
pic= userprofile.getInt("lastpic",pic);
x=pic;
Log.d("editpic",new Integer(pic).toString());
while(y!=x){
String comment = commentresult();
Titles.add(comment);
y++;
Log.d("y",new Integer(y).toString());
}
while(z!=x){
String act = actionresult();
Actions.add(act);
z++;
Log.d("z",new Integer(z).toString());}
while(a!=x){
Bitmap photo = getbitmap();
Images.add(photo);
a++;
Log.d("a",new Integer(a).toString());}
Titles.toArray();
Actions.toArray();
Images.toArray();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < Images.size(); i++) {
RowItem item = new RowItem(Images.get(i), Titles.get(i),Actions.get(i));
rowItems.add(item);
}
Log.d("TAG", "listview null? " + (listView == null));
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.aname_list_item, rowItems);
Log.d("TAG", "adapter=null? " + (adapter == null));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(this);
}
public static Bitmap getbitmap() {
String photo1 =userprofile.getString("picpath"+a, "");
File imgpath=new File(photo1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp=DecodeImage.decodeFile(imgpath, 800, 1000, true);
bmp.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Bitmap photo2=bmp;
return photo2;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
public String commentresult()
{
// String com2 = null;
// while(y!=x){
String comment=userprofile.getString("comment"+y, "");
String com1=comment;
String com2=com1;
// }
return com2;
}
public String actionresult()
{
// String act2 = null;
// while(y!=x){
String action=userprofile.getString("action"+z, "");
String act1=action;
String act2=act1;
// }
return act2;
}
private static final long delay = 2000L;
private boolean mRecentlyBackPressed = false;
private Handler mExitHandler = new Handler();
private Runnable mExitRunnable = new Runnable() {
#Override
public void run() {
mRecentlyBackPressed=false;
}
};
#Override
public void onBackPressed() {
//You may also add condition if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) // in case of Fragment-based add
if (mRecentlyBackPressed) {
mExitHandler.removeCallbacks(mExitRunnable);
mExitHandler = null;
super.onBackPressed();
}
else
{
mRecentlyBackPressed = true;
Toast.makeText(this, "press again to exit", Toast.LENGTH_SHORT).show();
mExitHandler.postDelayed(mExitRunnable, delay);
}
}
#Override
public void onDestroy() {
// Destroy the AdView.
super.onDestroy();
}
Custom List Adapter:
public class CustomListAdapter extends ArrayAdapter<RowItem> {
Context context;
List<RowItem> items;
public CustomListAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public RowItem getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.aname_list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.rab);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// String name=items.get(position).getDesc();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageBitmap(rowItem.getImageId());
// holder.imageView.setImageResource(Images.get(position) .getPlaceholderleft());
return convertView;
}
}
It looks like this is because you've made your variables x, y, z and a all static, which means there is a single instance of the variables shared by all instances of the class. Therefore, when you call onCreate the second time, all your while loop termination conditions are already met, so the while loops never execute. It's unclear to me why you've made these static, so unless you need them to be, you should remove the static keyword for these variables.
Why are you creating another object of ListView in onCreate() and onResume()
Remove code from onResume()
Also replace this line in onCreate()
old line ListView listView = (ListView)findViewById(R.id.listing);
New line listView = (ListView)findViewById(R.id.listing);

Custom ExpandableListview which contain another expand button in child

I want to implement this type of list-view. Problem is when i scroll the list, view got refreshed. The task is to show groups expanded up to 3 child's by default and when click on '+'(plus) button, child-items of that group will be expanded and new button will be shown below that group for collapsing that group to default layout means 3 child-items to show with plus('+') button. Plus button is shown when any group have child-items more than 3, if child-items are less than 3 or equal to 3 then all child-items will be shown with no plus button, but if child-items are more than 3 then plus button will be shown. Here 'DIAPERS' and 'LAUNDRY DETERGENT' are the group names.
Present scenario:- If child-position > 3, then set text-view visibility to 'GONE' and button visibility to 'VISIBLE'. But problem is that if childitems are more than 4 and i click to plus button to expand group , then only 4 child-items are shown 5 or next childitems are not shown.
If you want the code of this, please ask in the comments, I will provide you the code.
First of all you have need to set a minimum limit to the child view of expandable list view. Like 2 or 3 child for the very first time will get downloaded or fetched from your database or webservices.
Then on that limit variable you can restrict expandable list view to display only first 2 and 3 child item.
Then with the child limit variable you have also needed a flag variable which contain information like "value 1 if list have more than 3 child's and 0 if list have 3 or less than three child's."
On the value of flag variable you can set plus button hidden and visible value in android.
For plus button click i think the below given code will help. on click just make a another call to the database and fetch all the child items and display them and refresh the expandable list view.
public class ProductListingExpandableAdapter extends BaseExpandableListAdapter {
public String TAG = ProductListingExpandableAdapter.class.getSimpleName();
private Context _context;int clickedPosition;
private List<String> _listDataHeader; // header titles child data in format of header title, child title
private HashMap<String, ArrayList<String>> _listDataChild;
ArrayList<String> CategoryId;
String stateId,countryID;
ArrayList<ProductDataBean> ProductList; ArrayList<ProductListingDisplayCheck> checkArrayList;
int _ListSize;String user_id;
ProductDataBean bean;
/* Variable to do lazy loading of images */
Handler handler;
Runnable runnable;
/* array list to hold data */
ArrayList<String> BrandList;
ImageLoader imageLoader;
private DisplayImageOptions options;
Activity a; String RetailerImageUrl,BrandImageUrl;
public ProductListingExpandableAdapter(Context context, List<String> listDataHeader, HashMap<String, ArrayList<String>> listChildData,
int size,ArrayList<ProductDataBean> ProductList,ArrayList<ProductListingDisplayCheck> checkArrayList,ArrayList<String> CategoryId, String user_id,String stateId,String countryID)
{
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
this.CategoryId = CategoryId;
this.checkArrayList = checkArrayList;
this._ListSize = size;
this.ProductList = ProductList;
this.checkArrayList = checkArrayList;
this.user_id = user_id;
this.countryID = countryID;
this.stateId = stateId;
options = new DisplayImageOptions.Builder()
.showImageForEmptyUrl(R.drawable.thumb_demo).cacheInMemory()
.cacheOnDisc().build();
imageLoader = ImageLoader.getInstance();
Log.d("....return the the event image loader class...==", ""+imageLoader.getClass());
}
#Override
public Object getChild(int groupPosition, int childPosititon)
{
//Log.i("Object getChild",String.valueOf(this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon)));
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,boolean isLastChild, View convertView, ViewGroup parent)
{
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.custom_brand_retailer_layout_new, null);
}
RelativeLayout ParentLayout= (RelativeLayout) convertView.findViewById(R.id.parentLayout);
/* Retailer Image*/
ImageView retailerImage = (ImageView) convertView.findViewById(R.id.retailerImage);
/* Brand Image */
ImageView brandImage = (ImageView) convertView.findViewById(R.id.brandImage);
/* Product PricePerUnit */
TextView pricePerUnit = (TextView) convertView.findViewById(R.id.pricePerItem);
/* Product PricePerUnit */
TextView packetPrice = (TextView) convertView.findViewById(R.id.pricePerPacket);
/* Product Name */
TextView productName = (TextView) convertView.findViewById(R.id.ProductName);
/* Group close Images */
RelativeLayout addMore = (RelativeLayout) convertView.findViewById(R.id.addMore);
/* Minus Button Image */
ImageView minusItems = (ImageView) convertView.findViewById(R.id.minusItems);
/* Minus Button Image */
ImageView plusItems = (ImageView) convertView.findViewById(R.id.plusItems);
try {
JSONObject jObject = new JSONObject(childText); // Log.i("jObject",String.valueOf(jObject));
pricePerUnit.setText ("$"+jObject.getString("pricePerItem"));
packetPrice .setText ("$"+jObject.getString("product_price"));
String itemNameString = "";
String title = jObject.getString("product_name");
if (title.length() > 44)
{
itemNameString = title.substring(0, 45)+"...";
}
else
{ itemNameString = title;
}
productName.setText(itemNameString);
RetailerImageUrl = jObject.getString("retailer_image_url_small");
BrandImageUrl = jObject.getString("brand_image_url");
// String RetailerImageUrl = jObject.getString("pricePerItem");
} catch (JSONException e)
{
e.printStackTrace();
}
//=========================================================================================
// Log.e("Pagination ArrayList size", String.valueOf(Constants.PaginationPosition.size()));
String PaginationPos = Constants.PaginationPosition.get(groupPosition);
Log.e ("PaginationPos", String.valueOf(PaginationPos));
// Log.e("is last child", String.valueOf(isLastChild));
/* Hide or Show Group Close option */
Log.e("Pagination ArrayList size", String.valueOf(Constants.PaginationPosition.size()));
if(PaginationPos.equals("1") && childPosition == 2 && isLastChild == true )
{
addMore.setVisibility(View.VISIBLE); minusItems.setVisibility(View.GONE ); plusItems.setVisibility(View.VISIBLE);
}
else if(PaginationPos.equals("0") && childPosition > 2 && isLastChild == true )
{
addMore.setVisibility(View.GONE);
}
else if(PaginationPos.equals("2") && childPosition > 2 && isLastChild == true )
{
plusItems.setVisibility(View.GONE);
addMore.setVisibility (View.VISIBLE);
minusItems.setVisibility(View.VISIBLE);
minusItems.setVisibility(View.VISIBLE);
minusItems.setImageResource(R.drawable.minus);
}
else
{
addMore.setVisibility(View.GONE);
}
//==================================================================================
minusItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Constants.listDataHeader.get(groupPosition)", Constants.listDataHeader.get(groupPosition));
String keyword = Constants.listDataHeader.get(groupPosition);
String alternate = ProductListingExpandableListViewActivity.demoJsonObjectTesting;
// check whether the list for keyword is present
ArrayList<String> alternateList = _listDataChild.get(keyword);
if(alternateList == null)
{
Log.i(TAG, "list is null");
/* alternateList = new ArrayList<String>();
_listDataChild.put(keyword, alternateList); */
}
else
{
Constants.PaginationPosition.set(groupPosition, "1");
ArrayList<String> newList = new ArrayList<String>();
int size = alternateList.size();
Log.e("alternateList size", String.valueOf( alternateList.size()));
for(int i=0;i<3;i++)
{
newList.add(alternateList.get(i));
}
alternateList.clear();
for(int i=0;i<3;i++)
{
alternateList.add(newList.get(i));
}
Log.i("alternate list size",String.valueOf( alternateList.size()));
ProductListingExpandableAdapter.this.notifyDataSetChanged();
//ProductListingExpandableAdapter.this.notifyDataSetInvalidated();
/*Intent showSearchResult = new Intent(_context,ProductListingExpandableListViewActivity.class);
showSearchResult.putExtra("ShowSeachResult", "2");
_context.startActivity(showSearchResult);
((Activity)_context).finish();
Apply our splash exit (fade out) and main entry (fade in) animation transitions.
((Activity)_context). overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout);*/
}
}
});
addMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("addMore images list clicked", "addMore image clicked");
//Clicked postion of group
clickedPosition = groupPosition;
String keyword = Constants.listDataHeader.get(groupPosition);
Log.i("keyword", keyword);
for( int ii = 0;ii<Constants.listDataHeader.size();ii ++)
{
String currentKeyword = Constants.listDataHeader.get(ii);
if(currentKeyword.equals(keyword)==false)
{
// check whether the list for keyword is present
ArrayList<String> alternateList = _listDataChild.get(currentKeyword);
if(alternateList == null)
{
Log.i(TAG,Constants.listDataHeader.get(groupPosition)+ " List is null");
/*alternateList = new ArrayList<String>();
_listDataChild.put(keyword, alternateList); */
}
else
{
if(alternateList.size()>2)
{
Constants.PaginationPosition.set(ii, "1");
Log.i(TAG,Constants.listDataHeader.get(groupPosition)+ "inside else");
ArrayList<String> newList = new ArrayList<String>();
int size = alternateList.size();
Log.e("alternateList size", String.valueOf( alternateList.size()));
for (int i=0; i<3;i++)
{
newList.add(alternateList.get(i));
}
alternateList.clear();
for (int j=0; j<3; j++)
{
alternateList.add(newList.get(j));
}
Log.i("alternate list size",String.valueOf( alternateList.size()));
}}
}
}
/* Calling json webservices */
new LoadProductData(_context,groupPosition).execute();
}
});
/* Lazy loading class method for loading Retailer images */
imageLoader.init(ImageLoaderConfiguration.createDefault(_context));
if(RetailerImageUrl.equals("no image"))
{
retailerImage.setBackgroundResource(R.drawable.no_img);
}
else
{
imageLoader.displayImage(RetailerImageUrl,retailerImage,
options, new ImageLoadingListener() {
#Override
public void onLoadingComplete() {}
#Override
public void onLoadingFailed() {}
#Override
public void onLoadingStarted() {}
});
}
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT>=16)
{
if(BrandImageUrl.equals("no image")==false)
{
Drawable Branddrawable= Loadimage(BrandImageUrl);
brandImage.setBackground(Branddrawable);
}
}
else
{
if(BrandImageUrl.equals("no image")==false)
{
Drawable Branddrawable= Loadimage(BrandImageUrl);
brandImage.setBackgroundDrawable(Branddrawable);
}
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition)
{
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition)
{
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount()
{
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
{
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate (R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface (null, Typeface.BOLD);
lblListHeader.setText (headerTitle);
ExpandableListView mExpandableListView = (ExpandableListView) parent;
mExpandableListView.expandGroup(groupPosition);
return convertView;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
// Background async task
/* State/Province list background thread */
class LoadProductData extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;String response;
Context context;int GroupPos;
private JSONArray jsonarray, stateJsonArray;
public LoadProductData(Context context,int GroupPos) {
super();
this.GroupPos = GroupPos;
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "","Please wait...", true, true);dialog.show();
Log.e("Adapter pre execute ", "in the pre-execute loop");
}
#Override
protected Void doInBackground(Void... params) {
try {
//Constants.listDataChild.clear();Constants.listDataHeader.clear();Constants.productListing.clear();
Log.e(TAG , "in the background-execute loop");
UserFunctions userFunctions = new UserFunctions();
String CategoryID = String.valueOf(Constants.CategoryId.get(GroupPos)); Log.e("CategoryId" , Constants.CategoryId.get(GroupPos));
JSONObject CategoryJson = userFunctions.SingleCategoryListRequest(CategoryID,user_id,stateId,countryID); // Log.i("Product Lisiting Json Array",String.valueOf(CategoryJson));
String result = CategoryJson.getString("result");
Log.i("result",result);
if(result.equals("no records found"))
{
response = "no records found";
}
else
{
response = "record found";
// SearchResult refers to the current element in the array
// "search_result"
JSONObject questionMark = CategoryJson.getJSONObject("result");
Iterator keys = questionMark.keys();
ProductListingDisplayCheck addCheck;
int i = 0;
while (keys.hasNext()) {
// Loop to get the dynamic key
String currentDynamicKey = (String) keys.next(); // Log.i("current Dynamic key",
// String.valueOf(currentDynamicKey));
ArrayList<String> BrandList = new ArrayList<String>();
// Get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); // Log.i("current Dynamic Value"+String.valueOf(i),
String product_list = currentDynamicValue.getString("product_listing"); // Log.i("product_listing",String.valueOf(product_list));
addCheck = new ProductListingDisplayCheck();
addCheck.setCheckStatus(0);
checkArrayList . add(addCheck);
Log.i("checkArrayList size",String.valueOf(checkArrayList.size()));
JSONArray product_listing = currentDynamicValue.getJSONArray ("product_listing");
BrandList = Constants.listDataChild.get(currentDynamicKey); Log.i("BrandList size", String.valueOf(BrandList.size()));
BrandList.clear();
for (int ii = 0; ii < product_listing.length(); ii++)
{
JSONObject jsonobject = product_listing.getJSONObject(ii);
String JsonObjectString = String.valueOf(jsonobject);
if ( BrandList == null )
{
BrandList = new ArrayList<String>();
Constants.listDataChild.put(currentDynamicKey, BrandList);
}
BrandList.add(JsonObjectString);
}
//HashMap<String, ArrayList<String>> _listDataChild = null;
/* String keyword = "Wipes";
String alternate = ProductListingExpandableListViewActivity.demoJsonObjectTesting;
// check whether the list for keyword is present
ArrayList<String> alternateList = _listDataChild.get(keyword);
if(alternateList == null) {
alternateList = new ArrayList<String>();
_listDataChild.put(keyword, alternateList);
}
alternateList.add(ProductListingExpandableListViewActivity.demoJsonObjectTesting);
*/
Constants.PaginationPosition.set(GroupPos, "2");
Constants.listDataChild.put(Constants.listDataHeader.get(clickedPosition), BrandList);
Log.i("hash map size", String.valueOf(Constants.listDataChild.size()));
/* Update the value of position */
i++;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
if(response.equals("no records found"))
{
Toast.makeText(_context, "No Record Found.", 500).show();
}
else
{
ProductListingExpandableAdapter.this.notifyDataSetChanged();
/*Intent showSearchResult = new Intent(_context,ProductListingExpandableListViewActivity.class);
showSearchResult.putExtra("ShowSeachResult", "2");
_context.startActivity(showSearchResult);
((Activity)context).finish();
Apply our splash exit (fade out) and main entry (fade in) animation transitions.
((Activity)context). overridePendingTransition(R.anim.mainfadein, R.anim.splashfadeout);*/
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
private Drawable Loadimage(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e) {
// tv.setText("Exc="+e);
return null;
}
}
}
You can use the Expand List custom Class, the following might be helpful:
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
if (listItem instanceof ViewGroup)
listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
try this out.it worked for me.
i solved this problem by using this link https://github.com/PaoloRotolo/ExpandableHeightListView .
package com.rtt.reeferwatch.utilities;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
public class ExpandableHeightListView extends ExpandableListView {
boolean expanded = false;
public ExpandableHeightListView(Context context) {
super(context);
}
public ExpandableHeightListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExpandableHeightListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean isExpanded() {
return expanded;
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isExpanded()) {
int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}

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