swipe update pager view contents but tab select not update content - android

I use PagerSlidingTabStrip library but I have a problem with this library. I have a GridView that gets updated from the web by an AsyncTask when the page is changed. if swipe from page 1 to page 2, page 2 get update from web but My problem is, when such as tab 1 is selected click on tab 2, page 2 not update and show page 1 content(grid adapter updated but pager not show new content). swipe update contents but tab select not update content. what is wrong in my code?
How to avoid cache next and prev page in pager? I want receive data from server when select any page.
public class SubCategoryActivity extends SherlockFragmentActivity {
boolean firstPagerAdapterConfirmed = false;
LayoutInflater inflator;
PagerSlidingTabStrip tabs;
ViewPager pager;
MyPagerAdapter pagerAdapter;
TextView tvCustomTitle;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray jsonArray;
String[][] SubCat;
GridviewAdapter gridAdapter;
GridView gridViewSubCategory;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
Intent intent;
int recordNum = 0;
int totalItems = 0;
int pageNum = 1;
int itemsPerPage = 20;
boolean loadingMore = false;
int itemId[];
ProgressBar progressBar;
RelativeLayout relativeLayoutLoadingMore;
private class getSubCategoryObjects extends AsyncTask<String, Void, String> {
int i = 0;
#Override
protected String doInBackground(String... url) {
// TODO Auto-generated method stub
return BaseActivity.jsonParser.makeHttpRequest(url[0], "POST",
nameValuePairs);
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
// progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
try {
jsonArray = new JSONArray(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (pageNum == 1 ) {
i = 3;
try {
recordNum = jsonArray.getJSONObject(0).getInt("recordNum");
totalItems = jsonArray.getJSONObject(1)
.getInt("totalItems");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
itemId = new int[totalItems];
for (int i = 0; i < totalItems; i++) {
try {
itemId[i] = jsonArray.getJSONObject(2).getInt(
String.valueOf(i));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for (; i < jsonArray.length(); i++) {
JSONObject jsonObjet;
map = new HashMap<String, String>();
try {
jsonObjet = jsonArray.getJSONObject(i);
map.put("id", String.valueOf(jsonObjet.getInt("id")));
map.put("title", jsonObjet.getString("title_fa"));
map.put("image", jsonObjet.getString("image"));
map.put("price", jsonObjet.getString("price"));
map.put("date", jsonObjet.getString("date"));
list.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
if (pageNum == 1 && firstPagerAdapterConfirmed == false) {
// progressBar.setVisibility(View.GONE);
gridAdapter = new GridviewAdapter(SubCategoryActivity.this,
list);
pagerAdapter = new MyPagerAdapter(gridAdapter);
pager.setAdapter(pagerAdapter);
firstPagerAdapterConfirmed = true;
//pager.setOffscreenPageLimit(1);
}else if(pageNum == 1 && firstPagerAdapterConfirmed) {
//progressBar.setVisibility(View.GONE);
gridAdapter = new GridviewAdapter(SubCategoryActivity.this,
list);
gridViewSubCategory.setAdapter(gridAdapter);
}else {
gridAdapter.GridviewAdapterAdd(SubCategoryActivity.this,
list);
runOnUiThread(returnRes);
}
}
}
private class getSubCategory extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
// TODO Auto-generated method stub
return BaseActivity.jsonParser.makeHttpRequest(url[0], "POST",
nameValuePairs);
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
try {
jsonArray = new JSONArray(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SubCat = new String[jsonArray.length()][2];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjet;
try {
jsonObjet = jsonArray.getJSONObject(i);
SubCat[i][0] = String.valueOf(jsonObjet.getInt("id"));
SubCat[i][1] = jsonObjet.getString("title_fa");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.toString();
}
}
pagerAdapter = new MyPagerAdapter();
pager.setAdapter(pagerAdapter);
// pager.setCurrentItem(SubCat.length-1);
// final int pageMargin = (int) TypedValue.applyDimension(
// TypedValue.COMPLEX_UNIT_DIP, 30, getResources()
// .getDisplayMetrics());
// pager.setPageMargin(pageMargin);
// pager.setCurrentItem(0);
// pager.setOffscreenPageLimit(0);
tabs.setViewPager(pager);
tabs.setTextSize(20);
tabs.setTypeface(BaseActivity.font, Typeface.NORMAL);
list = new ArrayList<HashMap<String, String>>();
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("getAdvertise", "true"));
nameValuePairs
.add(new BasicNameValuePair("subCatId", SubCat[0][0]));
new getSubCategoryObjects().execute(url2);
}
}
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
intent = getIntent();
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
tabs.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
recordNum = 0;
totalItems = 0;
pageNum = 1;
//loadingMore = false;
jsonArray = new JSONArray();
list = new ArrayList<HashMap<String, String>>();
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("getAdvertise",
"true"));
nameValuePairs.add(new BasicNameValuePair("subCatId",
SubCat[arg0][0]));
// Activity myActivity = getActivity();
// if (myActivity instanceof SubCategoryActivity) {
new getSubCategoryObjects().execute(url2);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
inflator = SubCategoryActivity.this.getLayoutInflater();
jsonArray = new JSONArray();
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("getSubCategory", "true"));
nameValuePairs.add(new BasicNameValuePair("catId", intent
.getStringExtra("id")));
new getSubCategory().execute(url);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
tvCustomTitle = new TextView(this);
tvCustomTitle.setText(intent.getStringExtra("title"));
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
para.setMargins(0, 0, 0, 0); // left,top,right, bottom
para.gravity = Gravity.CENTER_VERTICAL;
tvCustomTitle.setTypeface(BaseActivity.font);
Configuration config = getResources().getConfiguration();
if (Build.VERSION.SDK_INT >= 13) {
if (config.smallestScreenWidthDp >= 600) {
tvCustomTitle.setTextSize(22);
} else {
tvCustomTitle.setTextSize(14);
}
} else {
tvCustomTitle.setTextSize(14);
}
tvCustomTitle.setTextColor(Color.WHITE);
ll.addView(tvCustomTitle, para);
getSupportActionBar().setCustomView(ll);
changeColor(intent.getIntExtra("color", Color.parseColor("#FF666666")));
}
private void changeColor(int newColor) {
tabs.setIndicatorColor(newColor);
// change ActionBar color just if an ActionBar is available
Drawable colorDrawable = new ColorDrawable(newColor);
Drawable bottomDrawable = getResources().getDrawable(
R.drawable.actionbar_bottom);
LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable,
bottomDrawable });
getSupportActionBar().setBackgroundDrawable(ld);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
public class MyPagerAdapter extends PagerAdapter {
GridviewAdapter gridAdapter;
public MyPagerAdapter(GridviewAdapter gridAdapter) {
// TODO Auto-generated constructor stub
this.gridAdapter = gridAdapter;
}
public MyPagerAdapter() {
// TODO Auto-generated constructor stub
}
public Object instantiateItem(View collection, int position) {
View rootView = inflator.inflate(
R.layout.fragment_sub_category_objects, null);
gridViewSubCategory = (GridView) rootView
.findViewById(R.id.gridViewSubCategory);
//progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
relativeLayoutLoadingMore = (RelativeLayout) rootView.findViewById(R.id.relativeLayoutLoadingMore);
gridViewSubCategory.setAdapter(gridAdapter);
gridViewSubCategory
.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
BaseActivity.cd = new ConnectionDetector(
SubCategoryActivity.this);
BaseActivity.isInternetPresent = BaseActivity.cd
.isConnectingToInternet();
if (BaseActivity.isInternetPresent) {
Intent i = new Intent(SubCategoryActivity.this,
SubCategoryActivity.class);
i.putExtra("id", ((TextView) view
.findViewById(R.id.textViewId))
.getText().toString());
i.putExtra(
"color",
i.getIntExtra("color",
Color.parseColor("#FF666666")));
startActivity(i);
} else {
Toast.makeText(
SubCategoryActivity.this,
"به اینترنت متصل نیستید، به اینترنت متصل شده و دوباره امتحان کنید.",
Toast.LENGTH_SHORT).show();
}
}
});
gridViewSubCategory.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
// save index and top position
// what is the bottom iten that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
// is the bottom item visible & not loading more already ?
// Load
// more !
if ((lastInScreen == totalItemCount) && !(loadingMore)
&& recordNum > 1) {
recordNum--;
pageNum++;
relativeLayoutLoadingMore.setVisibility(View.VISIBLE);
Thread thread = new Thread(null, loadMoreGridItems);
thread.start();
}
}
});
((ViewPager) collection).addView(rootView, 0);
return rootView;
}
#Override
public CharSequence getPageTitle(int position) {
return SubCat[position][1];
}
#Override
public int getCount() {
return SubCat.length;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager)collection).removeView((RelativeLayout) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
}
// Runnable to load the items
private Runnable loadMoreGridItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
list = new ArrayList<HashMap<String, String>>();
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("getAdvertise", "true"));
nameValuePairs
.add(new BasicNameValuePair("subCatId", SubCat[pager.getCurrentItem()][0]));
nameValuePairs.add(new BasicNameValuePair("pageNum", String
.valueOf(pageNum)));
new getSubCategoryObjects().execute(url3);
}
};
// Since we cant update our UI from a thread this Runnable takes care of
// that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
//pager.requestLayout();
relativeLayoutLoadingMore.setVisibility(View.GONE);
gridViewSubCategory.setAdapter(gridAdapter);
//gridAdapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
public class GridviewAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> list;
HashMap<String, String> tempMap;
public GridviewAdapter(Activity activity,
ArrayList<HashMap<String, String>> list) {
this.activity = activity;
this.list = list;
}
public void GridviewAdapterAdd(Activity activity,
ArrayList<HashMap<String, String>> list) {
this.activity = activity;
for (int i = 0; i < list.size(); i++)
this.list.add(list.get(i));
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflator = activity.getLayoutInflater();
View vi = convertView;
if (convertView == null)
vi = inflator.inflate(R.layout.gridview_sub_category_row, null);
TextView id = (TextView) vi.findViewById(R.id.textViewId);
TextView title = (TextView) vi.findViewById(R.id.textViewTitle);
ImageView imageViewSubCat = (ImageView) vi
.findViewById(R.id.imageViewSubCat);
TextView price = (TextView) vi.findViewById(R.id.textViewPrice);
TextView date = (TextView) vi.findViewById(R.id.textViewDate);
RelativeLayout textBackground = (RelativeLayout) vi
.findViewById(R.id.relativeLayoutText);
tempMap = new HashMap<String, String>();
tempMap = list.get(position);
id.setText(tempMap.get("id"));
textBackground.setBackgroundColor(intent.getIntExtra("color",
Color.parseColor("#FF666666")));
title.setText(tempMap.get("title"));
price.setText(tempMap.get("price"));
date.setText(tempMap.get("date"));
title.setTypeface(BaseActivity.font);
price.setTypeface(BaseActivity.font);
date.setTypeface(BaseActivity.font);
// File cachedImg = ImageLoader.getInstance().getDiscCache()
// .get(picUrl + tempMap.get("logo") + ".jpg");
// if (cachedImg.exists())
// cachedImg.delete();
ImageLoader.getInstance().displayImage(
BaseActivity.picUrl + tempMap.get("image") + ".jpg",
imageViewSubCat);
return vi;
}
}

Related

Sort in listview using BaseAdapter

I want to sort listview on the basis of counter but i am unable to do that please any body help me on that.
Here i am sharing my code and screen shot.
This is the adapter which is linked to the listview
Custom_adapter_group.java
public class CustomAdapter_groups extends BaseAdapter {
String phone = "";
Button bttn_request;
ArrayList<DiscoverModel> discoverModel;
SharedPreference_Main sharedPreference;
String[] result;
String[] details;
private Context context;
private int[] prgmImages;
private LayoutInflater inflater = null;
public Database4 db4;
private ArrayList<DiscoverModel> listupdate;
protected int position;
public CustomAdapter_groups(Context context,
ArrayList<DiscoverModel> discoverModel) {
// TODO Auto-generated constructor stub
this.context = context;
this.discoverModel = discoverModel;
this.listupdate = listupdate;
this.inflater = (LayoutInflater) ((context))
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
db4 = new Database4(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return discoverModel.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return discoverModel.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
TextView tv_pushcounter;
private Holder() {
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
sharedPreference = new SharedPreference_Main(context);
final Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = this.inflater.inflate(
R.layout.fragment_others_list_view_elements, null);
holder.tv = (TextView) convertView.findViewById(R.id.tv_foodibdhe);
holder.img = (ImageView) convertView.findViewById(R.id.iv_foodie);
holder.tv_pushcounter = (TextView) convertView
.findViewById(R.id.tv_pushcounter);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
if (discoverModel.get(position) != null) {
holder.tv.setText(discoverModel.get(position).getGroupname());
// //Condition for counter
if (db4.getCounter(discoverModel.get(position).getGroupchatid()) == "0") {
holder.tv_pushcounter.setVisibility(View.GONE);
} else if (db4.getCounter(discoverModel.get(position)
.getGroupchatid()) == "101") {
holder.tv_pushcounter.setText("100+");
}
holder.tv_pushcounter.setText(db4.getCounter(discoverModel.get(
position).getGroupchatid()));
Picasso.with(context)
.load(discoverModel.get(position).getGroupimage())
.resize(200, 200).centerCrop()
.transform(new CircleTransform())
.into(holder.img, new Callback() {
#Override
public void onError() {
holder.img
.setBackgroundResource(R.drawable.group_friend_list_icon);
}
#Override
public void onSuccess() {
}
});
}
String update1 = sharedPreference.getlistupdate1();
// if (!update1.equalsIgnoreCase("")) {
// discoverModel.add(0, discoverModel.get(position));
// discoverModel.
// notifyDataSetChanged();
// }
notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context,
Private_group_chat_activity.class);
sharedPreference = new SharedPreference_Main(context);
sharedPreference.is_slient(""
+ discoverModel.get(position).getIs_slient());
i.putExtra("public_group", "1");
i.putExtra("isMember", ""
+ discoverModel.get(position).getIsMember());
i.putExtra("groupidentify", ""
+ discoverModel.get(position).getGroup_identify());
i.putExtra("public_priavte_Identify",
"" + discoverModel.get(position).getPublic_private());
i.putExtra("groupchatid", ""
+ discoverModel.get(position).getGroupchatid());
i.putExtra("groupname", ""
+ discoverModel.get(position).getGroupname());
i.putExtra("groupId", ""
+ discoverModel.get(position).getGroupid());
i.putExtra("isAdmin", ""
+ discoverModel.get(position).getIsAdmin());
context.startActivity(i);
// discoverModel.add(0, discoverModel.get(position));
// notifyDataSetChanged();
}
});
return convertView;
Collections.sort(discoverModel, myComparator);
}
public Comparator<Database4> myComparator = new Comparator<Database4>() {
public int compare(Database4 obj1, Database4 obj2) {
return obj1
.getCounter(discoverModel.get(position).getGroupchatid())
.compareTo(
obj2.getCounter(discoverModel.get(position)
.getGroupchatid()));
}
};
}
Here is the code where ListView is used
Fragment_groups.java
public class Fragment_groups extends Fragment implements ApiConstants,UpdateListener
{
private static int FLAG = 0;
private ListView lv_list_view;
private RelativeLayout rl_foodie;
private EditText et_type_groups;
private Database2 db2;
private Database4 db4;
private String newResponse;
private String counter;
private Button bttn_create_private_group;
private ArrayList<DiscoverModel> discoverModel;
private ArrayList<DiscoverModel> listupdate;
private CustomAdapter_groups CustomAdapter_groups;
SharedPreference_Main sharedPreference;
public ArrayList<DiscoverModel> discoverModelSearch;
public ArrayList<DiscoverModel> discoverModelStore;
Activity activity;
// Fragment_groups context;
public static int\[\] prgmImages = { R.drawable.group_chat_icon,
R.drawable.group_chat_icon, R.drawable.group_chat_icon };
public static String\[\] prgmNameList = { "Foodie", "Football" };
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
sharedPreference = new SharedPreference_Main(getActivity());
View v = inflater.inflate(R.layout.fragment_others, container, false);
// Inflate the layout for this fragment
// this.setUpdatedCounter();
activity = this.getActivity();
lv_list_view = (ListView) v.findViewById(R.id.lv_list_view);
et_type_groups = (EditText) v.findViewById(R.id.et_type_groups);
discoverModel = new ArrayList<DiscoverModel>();
listupdate = new ArrayList<DiscoverModel>();
discoverModelSearch = new ArrayList<DiscoverModel>();
discoverModelStore = new ArrayList<DiscoverModel>();
db2 = new Database2(getActivity());
db4 = new Database4(getActivity());
bttn_create_private_group = (Button) v
.findViewById(R.id.bttn_create_private_group);
bttn_create_private_group.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), Private_group.class);
startActivity(intent);
}
});
et_type_groups.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
searchText(s.toString());
}
#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
}
});
get_groups_api();
isOnline();
return v;
}
private void isOnline() {
// TODO Auto-generated method stub
ConnectivityManager conMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
Toast.makeText(getActivity(), "No Internet connection!",
Toast.LENGTH_LONG).show();
newResponse = db2.getResponse(getActivity(), newResponse, 3);
jsonparsing(newResponse);
}
return;
}
public void get_groups_api() {
FLAG = 0;
// TODO Auto-generated method stub
final ProgressDialog pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
StringRequest sr = new StringRequest(Request.Method.POST,
"http://unichatapi.approutes.com:80/groups",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
discoverModel.clear();
// parsing method passing the response
Log.e("groups response", "" + response);
jsonparsing(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.hide();
VolleyLog.e("TAG", "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("deviceId", sharedPreference.getRegisteration_id());
params.put("sessionId", "" + sharedPreference.getSession());
params.put("option", "getGroups");
params.put("userId", "" + sharedPreference.getUserId());
params.put("unixTime", "" + 0);
return params;
}
};
AppController.getInstance().addToRequestQueue(sr);
}
protected void jsonparsing(String response) {
// TODO Auto-generated method stub
db2.update(response, 2, "1");
try {
JSONObject jsonO = new JSONObject(response);
Log.e("message", "" + jsonO.getString("message"));
Log.e("serverTime", "" + jsonO.getString("serverTime"));
sharedPreference.server_time(jsonO.getString("serverTime"));
// code for public group
JSONArray publicgroupsA = jsonO.getJSONArray("publicGroups");
for (int i = 0; i < publicgroupsA.length(); i++) {
DiscoverModel cm = new DiscoverModel();
JSONObject public_groupO = publicgroupsA.getJSONObject(i);
// if(sharedPreference.getlistupdate1().equalsIgnoreCase(public_groupO.getString("groupChatId")))
// {
// listupdate.add(cm);
// }
DiscoverModel dm = new DiscoverModel();
dm.setGroup_identify("1");
dm.setPublic_private("0");
dm.setIs_slient(public_groupO.getString("is_silent"));
dm.setGroupid(public_groupO.getString("groupId"));
Log.e("groupId", "" + public_groupO.getString("groupId"));
dm.setGroupname(public_groupO.getString("groupName"));
Log.e("groupName", "" + public_groupO.getString("groupName"));
dm.setGroupimage("http://unichatapi.approutes.com/vchatfiles/"
+ public_groupO.getString("groupImage"));
dm.setGroupchatid(public_groupO.getString("groupChatId"));
// counter = db4.getCounter(dm.getGroupchatid());
Log.e("value from counter",""+counter);
// dm.setPushcounter(counter);
dm.setGroup_modified_on(public_groupO.getString("modifiedOn"));
dm.setGroup_created_on(public_groupO.getString("createdOn"));
discoverModel.add(dm);
db4.insertIncidentDetails(getActivity(), dm);
}
// code for private group
JSONArray fullDataA = jsonO.getJSONArray("fullData");
for (int j = 0; j < fullDataA.length(); j++) {
DiscoverModel fm = new DiscoverModel();
JSONObject jsongroup = fullDataA.getJSONObject(j);
fm.setGroup_identify("2");
fm.setPublic_private("1");
fm.setGroupid(jsongroup.getString("groupId"));
fm.setIsMember(jsongroup.getString("isMember"));
fm.setIsAdmin(jsongroup.getString("isAdmin"));
fm.setGroupname(jsongroup.getString("groupName"));
fm.setGroupimage("http://unichatapi.approutes.com/vchatfiles/"
+ jsongroup.getString("groupImage"));
fm.setGroupchatid(jsongroup.getString("groupChatId"));
fm.setGroup_modified_on(jsongroup.getString("modifiedOn"));
fm.setGroup_created_on(jsongroup.getString("createdOn"));
Log.e("groupid", "" + jsongroup.getString("groupId"));
Log.e("groupName", "" + jsongroup.getString("groupName"));
Log.e("groupImage", "" + jsongroup.getString("groupImage"));
Log.e("groupChatId", "" + jsongroup.getString("groupChatId"));
Log.e("modifiedOn", "" + jsongroup.getString("modifiedOn"));
Log.e("createdOn", "" + jsongroup.getString("createdOn"));
discoverModel.add(fm);
db4.insertIncidentDetails(getActivity(), fm);
// CustomAdapter_groups.notifyDataSetChanged();
}
CustomAdapter_groups = new CustomAdapter_groups(getActivity(),
discoverModel);
lv_list_view.setAdapter(CustomAdapter_groups);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "" + e, Toast.LENGTH_SHORT).show();
}
}
public LayoutInflater getSystemService(String layoutInflaterService) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, new IntentFilter("com.example.vchat"));
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
}
public void searchText(String chartext) {
// TODO Auto-generated method stub
chartext = chartext.toLowerCase(Locale.getDefault());
if (FLAG == 0) {
discoverModelStore.clear();
discoverModelStore.addAll(discoverModel);
FLAG = 1;
}
discoverModelSearch.clear();
discoverModelSearch.addAll(discoverModelStore);
discoverModel.clear();
if (chartext.length() == 0) {
// discoverModel.clear();
discoverModel.addAll(discoverModelStore);
CustomAdapter_groups.notifyDataSetChanged();
} else if (chartext.length() >= 0) {
// discoverModel.clear();
for (DiscoverModel dm : discoverModelSearch) {
if (dm.getGroupname().toLowerCase(Locale.getDefault())
.contains(chartext)) {
discoverModel.add(dm);
}
}
}
CustomAdapter_groups.notifyDataSetChanged();
}
#Override
public void setUpdatedCounter() {
// TODO Auto-generated method stub
}
BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
CustomAdapter_groups.notifyDataSetChanged();
}
};
}
here is the screen shot of screen
Try sort list in desc order, use this
Collections.sort(myIntegerList, new Comparator<Integer>() {
public int compare(Integer one, Integer other) {
if (one >= other) {
return -1;
} else {
return 1;
}
}
});
Check this for more detail.

How to populate partial Data into ListView

Still i am populating all JSON data into ListView, but now i want to populate (records into ListView) based on visibility, when user scrolls I want to show progess bar for 5 seconds and then want to populate more records (those will be visible to user) and so on...
I don't want to populate all data into ListView for the first time !
MainActivity.java:
public class MainActivity extends Activity {
ArrayList<Main> arrayList;
MainAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<Main>();
new JSONAsyncTask().execute("....");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new MainAdapter(getApplicationContext(), R.layout.row, arrayList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), arrayList.get(position).getTitle(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Main main = new Main();
main.setTitle(object.getString("title"));
Log.v("title:", object.getString("title"));
arrayList.add(main);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
MainAdapter.java:
public class MainAdapter extends BaseAdapter {
ArrayList<Main> arrayList;
LayoutInflater layoutInflater;
int resource;
ViewHolder viewHolder;
public MainAdapter(Context context, int resource, ArrayList<Main> arrayList) {
this.layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resource = resource;
this.arrayList = arrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.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) {
// convert view = design
View view = convertView;
if (view == null) {
viewHolder = new ViewHolder();
view = layoutInflater.inflate(resource, null);
viewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tvName.setText(arrayList.get(position).getTitle());
return view;
}
static class ViewHolder {
public TextView tvName;
}
}
You can try using this library (Android-Infinite-Scroll-Listview)
I've used it before and it's easy to work with.

Blank listview getting in android

public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
DataModel datamodel = new DataModel();
ArrayList<DataModel> list = new ArrayList<DataModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
if (Id != null) {
datamodel.setId(_obj.getString("Id"));
}
if (Designation != null) {
datamodel.setDesignation(_obj.getString("Designation"));
}
if (EmployeeName != null) {
datamodel.setEmployeeName(_obj
.getString("EmployeeName"));
}
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
}
public class DataModel implements Parcelable {
private String Id = "";
private String Designation = "";
private String EmployeeName = "";
public String getId() {
return Id;
}
public void setId(String id) {
this.Id = id;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
this.Designation = designation;
}
public String getEmployeeName() {
return EmployeeName;
}
public void setEmployeeName(String employeeName) {
this.EmployeeName = employeeName;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public DataModel() {
// TODO Auto-generated constructor stub
}
public DataModel(Parcel in) {
Id = in.readString();
EmployeeName = in.readString();
Designation = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(Id);
dest.writeString(EmployeeName);
dest.writeString(Designation);
}
}
public class CustomList extends BaseAdapter {
Context context;
private ArrayList<DataModel> arrModel;
public CustomList(Context context, ArrayList<DataModel> arrModel) {
this.context = context;
this.arrModel = arrModel;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView locationimage;
ImageView roleimageview;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.settingrowitem, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView
.findViewById(R.id.rowcontact_txtName);
holder.txtTitle = (TextView) convertView
.findViewById(R.id.rowcontact_txtrole);
holder.locationimage = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.roleimageview = (ImageView) convertView
.findViewById(R.id.imageView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtDesc.setText(arrModel.get(position).getEmployeeName());
holder.txtTitle.setText(arrModel.get(position).getDesignation());
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
}
else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
return convertView;
}
#Override
public int getCount() {
return arrModel.size();
}
#Override
public Object getItem(int position) {
return arrModel.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
There are three class which I have use to parse data from from web service and and trying to print in Listview .I am able to do Json parsing and getting data from server insetting.javaclass:
list.add(datamodel);
and bind this in list in onpostexcute method:
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
Using this i am trying to print data in listview item but I am getting blank value in each item while Number Json is 49 and i am getting that 49 but getDesignation and getEmploye I am getting blank value please check and tell me where I am doing mistake I have tried much unable to get Print that value please check suggest me
Where are you inistailizind the Id,Designation and EmployeeName, it will be null itself. so doInBackground wont add any datamodel. remove the check
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
DataModel datamodel = new DataModel();
JSONObject _obj = _jarray.getJSONObject(i);
datamodel.setId(_obj.getString("Id"));
datamodel.setDesignation(_obj.getString("Designation"));
datamodel.setEmployeeName(_obj.getString("EmployeeName"));
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
Initialise the model inside the for loop and try once.
To identify changes in your list item you should call
adapter.notifyDataSetChanged();
call it before setting adapter to list view.

How to Implement on scroll load ListView in Android?

I have implemented listview in fragment. In that listview i have used custom adapter to display images with their description. Data is coming from web server. There are many list items with image so I'd like to implement on scroll load ListView for the same.
Which approach should i follow to do the same? I have tried to google it and found some sample but it does not fit into my requirement.
Here is the code of my Fragment containing listview. Thanks in advance.
FragmentTab1.class
public class FragmentTab1 extends Fragment implements
AdapterView.OnItemClickListener {
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
JSONArray AdsArray = null;
String TAG_IMAGE = "image";
String TAG_DISCRIPTION = "description";
ListView lv;
final Context context = getActivity();
static ArrayList<HashMap<String, String>> adList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,false);
options = new DisplayImageOptions.Builder().showStubImage(R.drawable.no_image).cacheInMemory().cacheOnDisc()
.bitmapConfig(Bitmap.Config.RGB_565).build();
lv = (ListView) rootView.findViewById(R.id.listView1);
lv.setOnItemClickListener(this);
adList = new ArrayList<HashMap<String, String>>();
new LoadMyAds().execute();
return rootView;
}
class LoadMyAds extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
String type = "all";
JSONObject json = userFunction.myAds(userid, type);
try {
if (json.getString("status") != null) {
String res = json.getString("status");
if (Integer.parseInt(res) == 1) {
adList.clear();
AdsArray = json.getJSONArray("myadslistsArray");
for (int i = 0; i < AdsArray.length(); i++) {
JSONObject c = AdsArray.getJSONObject(i);
String description = c.getString(TAG_DISCRIPTION);
String image = c.getString(TAG_IMAGE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_IMAGE, image);
map.put(TAG_DISCRIPTION, description); adList.add(0, map);
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
"parsing error", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// image parameter need to be added
lv.setAdapter(new CustomAdapter(adList));
}
}
class CustomAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> locallist;
public CustomAdapter(ArrayList<HashMap<String, String>> list) {
// TODO Auto-generated constructor stub
locallist = list;
imageLoader.init(ImageLoaderConfiguration
.createDefault(getActivity()));
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return locallist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
// return null;
return getItem(getCount() - position - 1);
}
#Override
public long getItemId(int arg0) {
// 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;
if (row == null) {
row = getActivity().getLayoutInflater().inflate(
R.layout.ad_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.desc= (TextView) row.findViewById(R.id.title);
viewHolder.img = (ImageView) row.findViewById(R.id.thumbImage);
row.setTag(viewHolder);
}
final ViewHolder holder = (ViewHolder) row.getTag();
holder.desc.setText(""+locallist.get(position).get(TAG_DISCRIPTION));
imageLoader.displayImage(locallist.get(position).get(TAG_IMAGE),
holder.img, options);
return row;
}
}
class ViewHolder {
protected TextView desc;
protected ImageView img;
}
}
Attach scroll listener to the listView
lv.setOnScrollListener(new EndlessScrollListener());
Here is the class implementation:
class EndlessScrollListener implements OnScrollListener {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
new LoadMyAds().execute();
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}

Android List with check box

I have list with a check box in it and when i tick the check box by scrolling the list i get the values into an array.
But now the problem is i have a search box to search and tick.but when i search i get the element which is last ticked into array.
here is my code.
public class Person extends ListActivity {
private TreeMap<String, String> map = new TreeMap<String, String>();
String SEARCH_STRING = "";
private String METHOD_NAME;
private String SERVICENAME;
ArrayList<String[]> DISPLAY = new ArrayList<String[]>();
ArrayList<String[]> SEARCH = new ArrayList<String[]>();
ArrayList<Boolean> ok = new ArrayList<Boolean>();
SoapIntractions intractions;
public static ArrayList<String[]> dataList=new ArrayList<String[]>();
boolean FLAG;
EditText search;
Button search_btn, back_btn;
LinearLayout tab1, tab2;
public Context c;
static class Viewholder {
TextView name, number;
CheckBox check;
}
public class EfficientAdapter extends BaseAdapter {
LayoutInflater inflater;
Context c;
public EfficientAdapter(Context addNote, int itemadd, Object object,
int[] to) {
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(addNote);
c = addNote;
}
public int getCount() {
// TODO Auto-generated method stub
return SEARCH.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Viewholder holder;
final int var = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.person, null);
holder = new Viewholder();
holder.name = (TextView) convertView
.findViewById(R.id.tv_name_prsnLI);
holder.number = (TextView) convertView
.findViewById(R.id.tv_nmbr_prsnLI);
holder.check = (CheckBox) convertView.findViewById(R.id.check);
convertView.setTag(holder);
} else {
holder = (Viewholder) convertView.getTag();
}
CheckBox box=new CheckBox(c);
String[] argg = SEARCH.get(var);
holder.name.setText(argg[0]);
holder.number.setText(argg[1]);
if (ok.get(position)){
holder.check.setChecked(true);
}
else{
holder.check.setChecked(false);
}
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (ok.get(var)) {
ok.set(var, false);
} else {
ok.set(var, true);
}
}
});
return convertView;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.person_list);
StateListDrawable bkBtn = new StateListDrawable(), srchBtn = new StateListDrawable();
bkBtn.addState(new int[] { android.R.attr.state_pressed },
getResources().getDrawable(R.drawable.back_click));
bkBtn.addState(new int[] {}, getResources()
.getDrawable(R.drawable.back));
srchBtn.addState(new int[] { android.R.attr.state_pressed },
getResources().getDrawable(R.drawable.srch_click));
srchBtn.addState(new int[] {},
getResources().getDrawable(R.drawable.srch));
search = (EditText) findViewById(R.id.et_search_prsnL);
search_btn = (Button) findViewById(R.id.btn_search_prsnL);
search_btn.setBackgroundDrawable(srchBtn);
back_btn = (Button) findViewById(R.id.btn_back_prsnL);
back_btn.setBackgroundDrawable(bkBtn);
tab1 = (LinearLayout) findViewById(R.id.lyt_tab1_prsnL);
tab2 = (LinearLayout) findViewById(R.id.lyt_tab2_prsnL);
tab1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FLAG = false;
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
}
});
tab2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FLAG = true;
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
}
});
search_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SEARCH_STRING = search.getText().toString();
SEARCH.clear();
SearchPageTask srch_task = new SearchPageTask();
srch_task.execute(new String[] { null });
Log.d("SEARCH", "Searchable");
}
});
back_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int len=ok.size();
for(int i=0;i<len;i++){
if(ok.get(i)){
dataList.add(new String[]{SEARCH.get(i)[0],SEARCH.get(i)[1],SEARCH.get(i)[2],SEARCH.get(i)[3] });
}
}
Intent in=new Intent(getApplicationContext(),Multiple_view.class);
in.putExtra("ARRAY", dataList);
setResult(RESULT_OK,in);
finish();
for (int i = 0; i < dataList.size(); i++) {
Log.d("ARRAY1", ""+dataList.get(i)[0]);
Log.d("ARRAY1", ""+dataList.get(i)[1]);
Log.d("ARRAY1", ""+dataList.get(i)[2]);
Log.d("ARRAY1", ""+dataList.get(i)[3]);
}
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
FLAG = false;
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
METHOD_NAME = "ZaplxTmrDisplayPernr";
SERVICENAME = "ZAPLX_WEB_TMR_DISPLAY_PERNR/ZaplxTmrDisplayPernrRequest";
map = new TreeMap<String, String>();
map.put("IDate", "2012-12-04");
intractions = new SoapIntractions(METHOD_NAME, SERVICENAME, map,
Person.this);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { null });
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Log.d("POSITION", "" + position);
// CheckBox cb = (CheckBox)
// l.getChildAt(position).findViewById(R.id.check);
// if (cb.isChecked()) {
// cb.setChecked(false);
//
// }
// else
// {
// cb.setChecked(true);
// }
// Intent in1=new Intent();
// String[] argg1 = SEARCH.get(position);
//
// in1.putExtra("number", SEARCH.get(position)[0]);
// in1.putExtra("name", SEARCH.get(position)[1]);
// in1.putExtra("area", SEARCH.get(position)[2]);
// in1.putExtra("group", SEARCH.get(position)[3]);
// setResult(RESULT_OK,in1);
// finish();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
String[][] data;
int value = 0;
ProgressBar pb;
public DownloadWebPageTask() {
// TODO Auto-generated constructor stub
// flag = string;
value = 0;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
data = intractions.GetSoapData1();
String[][] subtypeData = data;
int n = subtypeData[0].length;
value = n;
for (int i = 0; i < value; i++) {
String Pernr = subtypeData[0][i];
String Ename = subtypeData[1][i];
String Earea = subtypeData[3][i];
String Egroup = subtypeData[5][i];
ok.add(false);
DISPLAY.add(new String[] { Pernr, Ename, Earea, Egroup });
}
for (int i = 0; i < DISPLAY.size(); i++)
SEARCH.add(DISPLAY.get(i));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// pb = (ProgressBar) findViewById(R.id.pb);
// pb.setVisibility(View.VISIBLE);
search_btn.setClickable(false);
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// pb = (ProgressBar) findViewById(R.id.pb);
// pb.setVisibility(View.INVISIBLE);
setListAdapter(new EfficientAdapter(Person.this, R.layout.person,
null, null));
search_btn.setClickable(true);
Log.d("POST_TIME", "Inside post");
super.onPostExecute(result);
}
}
private class SearchPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("SEARCH", "List Size" + DISPLAY.size());
Log.d("SEARCH", "List Size" + SEARCH.size());
int n = DISPLAY.size();
if (!FLAG) {
for (int i = 0; i < n; i++) {
if (DISPLAY.get(i)[1].toLowerCase().startsWith(
SEARCH_STRING.toLowerCase())) {
SEARCH.add(DISPLAY.get(i));
Log.d("SEARCH_ATSK", "result size " + SEARCH.size());
}
Log.d("SEARCH_ATSK", "" + i + " " + n);
}
} else {
for (int i = 0; i < n; i++) {
if (DISPLAY.get(i)[0].toLowerCase().endsWith(
SEARCH_STRING.toLowerCase())) {
SEARCH.add(DISPLAY.get(i));
Log.d("SEARCH_ATSK", "result size " + SEARCH.size());
}
Log.d("SEARCH_ATSK", "" + i + " " + n);
}
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
setListAdapter(new EfficientAdapter(Person.this, R.layout.person,
null, null));
super.onPostExecute(result);
}
}
}

Categories

Resources