public class EpisodeScreen extends Activity implements OnClickListener,OnItemClickListener,IServerResponse {
private String image;
private String episodediscription;
private String video;
private ListView episodelist=null;
private ArrayList<Object> _EpisodeList=new ArrayList<Object>();
private EpisodeAdapter mAdapter=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.episode_list);
episodelist=(ListView)findViewById(R.id.listview1);
episodelist.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.play:
Log.i("click","sucess");
break;
default:
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
getEpisode();
}
public void getEpisode() {
if (NetworkAvailablity.checkNetworkStatus(EpisodeScreen.this)) {
ArrayList<NameValuePair> requestParaList = new ArrayList<NameValuePair>();
requestParaList.add(new BasicNameValuePair("issue_id","1"));
WebServiceCommunicator.getInstance().registerForServerResponse(
(IServerResponse) EpisodeScreen.this);
WebServiceCommunicator.getInstance().callGetAppWebService(
Constant.showDialog, this, WebServiceConstants.getMethodUrl(WebServiceConstants.METHOD_NAME_GET_EPISODE_DETAILS),
EpisodeScreen.this, Constant.PID_EPISODE, false,
requestParaList);
} else {
Constant.showAlertDialog(Constant.errorTitle,
Constant.MSG_CHECK_INTERNET_SETTING,
EpisodeScreen.this, false);
}
}
#Override
public void serverResponse(String response, int processid) {
// TODO Auto-generated method stub
Message msg = new Message();
msg.obj = response;
msg.arg1 = processid;
_handler.sendMessage(msg);
}
private Handler _handler = new Handler() {
public void handleMessage(Message msg) {
String respons=msg.obj.toString();
switch (msg.arg1) {
case Constant.PID_EPISODE:
if(respons!=null ){
try{
JSONObject jsonObj=new JSONObject(respons);
JSONArray jArray=jsonObj.optJSONArray("Episode Detail");
if(jArray!=null){
for(int i =0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
episodebean bean=new episodebean();
bean.setEpisode_image(jsonObject.getString("Episode-image"));
bean.setEpisode_discription(jsonObject.getString("Episode-description"));
bean.setEpisode_video(jsonObject.getString("Episode-video"));
_EpisodeList.add(bean);
}
mAdapter=new EpisodeAdapter(EpisodeScreen.this, _EpisodeList);
episodelist.setAdapter(mAdapter);
/**/
/*if(_EpisodeList.size()!=0){
mAdapter=new EpisodeAdapter(EpisodeScreen.this, _EpisodeList);
episodelist.setAdapter(mAdapter);
}*/
}
}
catch (JSONException e) {
}
}
break;
default:
break;
}
}
};
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "ok........", Toast.LENGTH_LONG).show();
}
}
here is adapter
public class EpisodeAdapter extends BaseAdapter {
private LayoutInflater _mInflater = null;
private ArrayList<Object> _EpisodeList=null;
private Context ctx = null;
private UserImageLoaderWithCache imageLoader=null;
public EpisodeAdapter(Context context,
ArrayList<Object> _episodeList) {
// TODO Auto-generated constructor stub
this.ctx = context;
this._EpisodeList = _episodeList;
imageLoader=new UserImageLoaderWithCache(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return _EpisodeList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return _EpisodeList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
static class ViewHolder {
public TextView txtViewTitle;
public ImageView pic;
public TextView tvurl;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater linf = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = linf.inflate(R.layout.episode_screen, null);
// view.imgViewFlag.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_episode);
holder.tvurl=(TextView)convertView.findViewById(R.id.tv_url);
holder.pic = (ImageView) convertView.findViewById(R.id.iv_episode);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final episodebean bean=(episodebean)_EpisodeList.get(position);
holder.txtViewTitle.setText(bean.getEpisode_discription());
holder.tvurl.setText(bean.getEpisode_video());
imageLoader.display(bean.getEpisode_image(), holder.pic, R.drawable.ic_launcher);
return convertView;
}}
I am using ListView in which I have to show data, which is coming from server. My ListView is not showing anything while response is coming (although it is showing in logcat) What do I do? Please help.
Thank you.
try to change some code on your adapter at method: getItemId
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
let us know if this work.
It may be help u..replace your handler
private Handler _handler = new Handler() {
public void handleMessage(Message msg) {
switch (id) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Related
I have a listview with a custom adapter, and Im trying to use SearchView with a CustomFilter. But the search is not "fully" working.
When I search for something that is on the viewable area of the listview, it is able to search, and all nonviewable area is not being included in the search.
Here is a video on whats going on:
https://youtu.be/2Z9FZMlNmGw
main
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_board_game_list, container, false);
this.listView = (ListView) view.findViewById(R.id.listView);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this.getContext());
databaseAccess.open();
List<String> boardgamesNames = databaseAccess.getNames();
List<String> urls = databaseAccess.getUrls();
adapter = new bgAdapter(getContext(), R.layout.row_layout);
adapterOriginal = new bgAdapter(getContext(), R.layout.row_layout);
databaseAccess.close();
listView.setAdapter(adapter);
int i = 0;
for(String name: boardgamesNames) {
boardgameListRow data = new boardgameListRow(urls.get(i), boardgamesNames.get(i));
i++;
adapter.add(data);
adapterOriginal.add(data);
}
listView.setDivider(null);
listView.setDividerHeight(0);
searchView = (SearchView)view.findViewById(R.id.searchId);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
adapter.getFilter().filter(newText);
}
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
BoardGameListFragment fragment= new BoardGameListFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
//adapter = adapterOriginal;
return true;
}
});
// Inflate the layout for this fragment
return view;
}
}
Here is the Adapter:
https://github.com/Shank09/AndroidTemp/blob/master/bgAdapter.java
I think you need to call notifyDataSetChanged() in onQueryTextChange
I fixed it, I was using the wrong variable in bgAdapter. Please remove this question if possible.
public class Listbyoperator extends Activity {
ListView lstdetail;
Activity act;
EditText search;
ArrayList<DetailModel> detail=new ArrayList<DetailModel>();
DetailaAdapter dadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listbyoperator);
act=this;
lstdetail=(ListView) findViewById(R.id.Listbyoperator_detaillist);
search=(EditText) findViewById(R.id.editsearch);
search.setPadding(10, 0, 0, 0);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
DetailModel d=new DetailModel("1","HARDIP","saahi");
detail.add(d);
DetailModel d1=new DetailModel("2","jalpa","sadfsadf");
detail.add(d1);
dadapter=new DetailaAdapter(act, detail);
lstdetail.setAdapter(dadapter);
dadapter.notifyDataSetChanged();
lstdetail.setEnabled(true);
}
}
/*Detail Model*/
public class DetailModel
{
public String d_id,d_name,d_decription;
public String getD_id() {
return d_id;
}
public void setD_id(String d_id) {
this.d_id = d_id;
}
public String getD_name() {
return d_name;
}
public void setD_name(String d_name) {
this.d_name = d_name;
}
public String getD_decription() {
return d_decription;
}
public void setD_decription(String d_decription) {
this.d_decription = d_decription;
}
public DetailModel(String s1,String s2,String s3)
{
this.d_id=s1;
this.d_name=s2;
this.d_decription=s3;
}
}
/*detail adapter */
public class DetailaAdapter extends BaseAdapter{
Context mContext;
private List<DetailModel> data=null;
private ArrayList<DetailModel> arraylist;
private static LayoutInflater inflater=null;
private static String String=null,valid;
public boolean flag=true;
public DetailaAdapter(Context context,List<DetailModel> data)
{
mContext = context;
this.data = data;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<DetailModel>();
this.arraylist.addAll(data);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.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) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_detail, null);
final TextView t1,t2,t3,t4,t5;
t1=(TextView)vi.findViewById(R.id.list_detail_text1);
t2=(TextView)vi.findViewById(R.id.list_detail_textview2);
t3=(TextView)vi.findViewById(R.id.list_detail_text2);
DetailModel da =new DetailModel(String, String,String);
da=data.get(position);
final String a1,a2,a3;
a1=da.d_id;
a2=da.d_name;
a3=da.d_decription;
t2.setText(a3);//description
t3.setText(a2);//name
return vi;
}
public void filter(String charText)
{
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.addAll(arraylist);
}
else
{
for (DetailModel wp : arraylist)
{
if (wp.getD_decription().toLowerCase(Locale.getDefault()).contains(charText) || wp.getD_name().toLowerCase(Locale.getDefault()).contains(charText))
{
data.add(wp);
}
}
}
notifyDataSetChanged();
}
}
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.
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.
I have a BaseAdapter in that, I have a Button. When a user clicks on that button, I need to call a Service and I need to set the data to that button in onpostExecute()
public class MenuTagsAdapter extends BaseAdapter {
View v;
#Override
public int getCount() {
// TODO Auto-generated method stub
return BaseApp.getTagsAroundMeList().size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.menutaglistitem, null);
TextView textViewName = (TextView) v
.findViewById(R.id.textViewName);
final Button buttonAction = (Button) v
.findViewById(R.id.buttonAction);
textViewName.setText("#"
+ BaseApp.getTagsAroundMeList().get(position).name);
buttonAction
.setText(BaseApp.getTagsAroundMeList().get(position).action);
buttonAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (buttonAction.getText().toString()
.equalsIgnoreCase("follow")) {
buttonAction.setBackgroundResource(R.drawable.followbutton);
if (appUtils.getNetworkInfo(AmgonnaHome.this)) {
new FollowInterestAsyTask().execute();
} else {
NetworkDialogClass.createDAlertDialog(
AmgonnaHome.this,
getString(R.string.network_error));
}
} else {
buttonAction.setBackgroundResource(R.drawable.unfollowbutton);
if (appUtils.getNetworkInfo(AmgonnaHome.this)) {
new UnfollowInterestAsyTask().execute();
} else {
NetworkDialogClass.createDAlertDialog(
AmgonnaHome.this,
getString(R.string.network_error));
}
}
}
});
return v;
}
}
public class FollowInterestAsyTask extends AsyncTask<Void, Void, Void> {
boolean progressDialogStatus = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(AmgonnaHome.this,
"Please Wait", "Connecting to Server");
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
progressDialogStatus = false;
}
});
}
#Override
protected Void doInBackground(Void... params) {
TaskUrl = BaseApp.baseUrl + BaseApp.followInterest;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("user_id=" + amgonnaUserId);
// stringBuilder.append("&interestName="+);
stringBuilder.append("&interestName=");
ConnectionManager connectionManager = new ConnectionManager();
String response = connectionManager.setUpHttpPost(TaskUrl,
stringBuilder.toString());
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
errStatus = jsonObject.getInt("errStatus");
status = jsonObject.getString("status");
} catch (Exception e) {
// TODO: handle exception
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialogStatus) {
progressDialog.dismiss();
if (errStatus == 0) {
// here i need to set the status message to button on adapter list item
}
}
}
}
Just save the string you want to show in button in a variable.
eg :
String temp=btnText;
Then call your list adapter again.
And make a change in your getView() as
buttonAction.setText(temp);
ive implented a searchbar into my ListView and so far it works correctly except
that the adapter is acting weird. Everytime i call its clear function my listview still shows the "old" content.
public abstract class MYLISTITEM extends BaseAdapter {
private Context activity;
private List<String> data;
private static LayoutInflater inflater=null;
private int ItemIcon;
private boolean moreVis;
public MYISTITEM(Context a, int IconID,boolean vis) {
activity = a;
data = new ArrayList<String>();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ItemIcon = IconID;
moreVis = vis;
}
public void add(String object)
{
data.add(object);
notifyDataSetChanged();
}
public void replace(int index,String object)
{
data.set(index, object);
notifyDataSetChanged();
}
public void clear()
{
data.clear();
notifyDataSetChanged();
}
public void remove(Object object)
{
data.remove(object);
notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public void insert(String object,int c)
{
data.set(c, object);
notifyDataSetChanged();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
if(position >= 0 && position < data.size())
{
return data.get(position);
}
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public static class ViewHolder{
public TextView text;
public ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.item,parent, false);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(data.get(position));
holder.image.setImageDrawable(activity.getResources().getDrawable(ItemIcon));
ImageButton btn_more = (ImageButton) vi.findViewById(R.id.more);
if(moreVis)
{
btn_more.setOnClickListener(new OnMoreClickListener(btn_more,position));
}
else
{
btn_more.setVisibility(View.GONE);
}
vi.setOnClickListener(new OnRowClickListener(vi,position));
return vi;
}
public abstract void OnRowClick(View mView, int position);
public abstract void OnMoreClick(View mView, int position);
private class OnRowClickListener implements OnClickListener{
private int mPosition;
private View mView;
OnRowClickListener(View view,int position){
mPosition = position;
mView = view;
}
#Override
public void onClick(View arg0) {
OnRowClick(mView,mPosition);
}
}
private class OnMoreClickListener implements OnClickListener{
private int mPosition;
private View mView;
OnMoreClickListener(View view,int position){
mPosition = position;
mView = view;
}
#Override
public void onClick(View arg0) {
OnMoreClick(mView,mPosition);
}
}
}
the debugger shows that only the size of data has been changed but none of its content. Do i miss something here???
some additional code:
public abstract class MYSCREEN extends ListView{
public abstract void Init();
public abstract void OnLoadFinished();
public abstract void OnRowClicked(int position);
public abstract void onCreateQuickAction(MYQUICKACTION action,int position);
public abstract void CreateOptionMenu(Menu menu);
public abstract boolean OptionsItemSelected(MenuItem item);
public MYLISTITEM adapter = null;
public static void StartupScreen(Activity current,Class<?> next)
{
Intent myIntent = new Intent(current,next);
current.startActivity(myIntent);
}
public MYSCREEN(Activity context,int Icon) {
super(context);
boolean moreisvis = true;
MYQUICKACTION canarybirdybirdy = new MYQUICKACTION(new View(context));
onCreateQuickAction(canarybirdybirdy,0);
if(canarybirdybirdy.anchor.getVisibility() != View.VISIBLE)
{
moreisvis = false;
}
adapter = new MYLISTITEM(context,Icon,moreisvis){
#Override
public void OnRowClick(View mView, int position) {
// TODO Auto-generated method stub
OnRowClicked(position);
}
#Override
public void OnMoreClick(View mView, int position) {
// TODO Auto-generated method stub
final MYQUICKACTION mQuickAction = new MYQUICKACTION(mView);
final ImageButton mMoreImage = (ImageButton) mView.findViewById(MY.views.R.id.more);
mMoreImage.setImageResource(MY.views.R.drawable.ic_list_more_selected);
onCreateQuickAction(mQuickAction,position);
mQuickAction.setAnimStyle(MYQUICKACTION.ANIM_AUTO);
mQuickAction.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss() {
mMoreImage.setImageResource(MY.views.R.drawable.ic_list_more);
}
});
mQuickAction.show();
}
};
final ProgressDialog dialog = new ProgressDialog(context);
dialog.setMessage("loading...");
dialog.show();
new LOADER(){
#Override
public void RunThread() {
Init();
}
#Override
public void FinishLoad() {
dialog.dismiss();
OnLoadFinished();
}
}.Start();
}
public abstract class MYTHREAD extends AsyncTask<Void, Void, Void> {
public abstract void InitThread();
public abstract void RunThread();
public abstract void FinishThread();
#Override
protected Void doInBackground(Void... params) {
RunThread();
// TODO Auto-generated method stub
return null;
}
//ui stuff allowed
#Override
protected void onPreExecute() {
InitThread();
}
//ui stuff allowed
#Override
protected void onProgressUpdate(Void... value) {
super.onProgressUpdate(value);
}
//ui stuff allowed
#Override
protected void onPostExecute(final Void unused) {
FinishThread();
}
public void Start()
{
this.execute();
}
}
public abstract class LOADER extends MYTHREAD{
public abstract void FinishLoad();
#Override
public void InitThread() {
// TODO Auto-generated method stub
}
#Override
public void FinishThread() {
// TODO Auto-generated method stub
FinishLoad();
}
}}
and here is the function that gives me the headache.Its from one of MYSCREEN derived classes , oh and its also called from the search-buttons clickevent.
#Override
public void OnLoadFinished() {
// TODO Auto-generated method stub
SelectedTable = TabController.Instance.Clients[TabController.Instance.selectedtab ? 1 : 0].DbTablename;
adapter.clear();
TabController.Instance.Clients[TabController.Instance.selectedtab ? 1 : 0].MetaEntities(SelectedTable, true, new ClientCallBackHandler(){
#Override
public void StartCallBack() {
// TODO Auto-generated method stub
prgdialog.setMessage("connecting service...");
prgdialog.show();
}
#Override
public void EndCallBack(boolean success) {
// TODO Auto-generated method stub
if(success)
{
try{
ExceptionResponse except = (ExceptionResponse) this.response;
ab.setMessage(Html.fromHtml("<b><font color=#ff0000>" + except.Message));
ab.setPositiveButton("ok", null);
ab.show();
success = false;
}catch(Exception e)
{
MetadataEntitiesResponse resp = (MetadataEntitiesResponse) response;
if(resp.Entities[0] != null)
{
Ent = resp.Entities[0];
int i = 0;
//search for the first string in our database ...
for(AttributeMetaData Att : Ent.Attributes)
{
if(Att.Type.contentEquals("string"))
{
SelectedAttribute = i;
break;
}
i++;
}
StartQuery(0); //here the adapter gets filled with info
}
}
}
}
});
}
private void StartQuery(int page)
{
if(currentpage != -1)
{
nextpage = page;
return;
}
Query query = new Query();
query.EntityName = Ent.Name;
if(SearchFilter != null)
{
query.Filter = new Filter();
query.Filter.Filters = SearchFilter;
query.Filter.FilterOperator = Filter.E_FilterOperator.And;
}
query.Columns = new AllColumns();
query.Limit = new Limit();
query.Limit.Count = 15;
Order order = new Order();
order.OrderType = Order.OrderTypeE.Ascending;
order.AttributeName = Ent.Attributes[SelectedAttribute].Name;
query.Orders = new Order[] {order};
currentpage = query.Limit.Page = page;
TabController.Instance.Clients[TabController.Instance.selectedtab ? 1 : 0].RetrieveMultiple(query, new ClientCallBackHandler(){
#Override
public void StartCallBack() {
// TODO Auto-generated method stub
}
#Override
public void EndCallBack(boolean success) {
// TODO Auto-generated method stub
try{
ExceptionResponse except = (ExceptionResponse) this.response;
ab.setMessage(Html.fromHtml("<b><font color=#ff0000>" + except.Message));
ab.setPositiveButton("ok", null);
ab.show();
success = false;
}catch(Exception e)
{
RetrieveMultipleResponse rmResp = (RetrieveMultipleResponse) this.response;
if(adapter.getCount() == 0)
{
for(int i = 0; i< rmResp.TotalRecords;i++)
{
prgdialog.setMessage( ((int) (i/rmResp.TotalRecords * 100)) + "%");
adapter.add("connecting...");
}
prgdialog.dismiss();
}
int i = 0;
for(Entity ent : rmResp.Entities)
{
adapter.replace(currentpage*15+i, ent.Properties[SelectedAttribute].ToString());
i++;
}
if(currentpage == nextpage)
{
nextpage = -1;
}
else
{
StartQuery(nextpage);
}
currentpage = -1;
}
}
});
}
i tried this code..
in oncreate() of where we are creating the CustomListView Adapter, call a function.
adapter.clear();
on the CustomListViewAdapter class create a function as clear
public void clear() {
// TODO Auto-generated method stub
movieItems.clear();
}
where movieItems is the name of the ListView
Call notifyDataSetChanged() instead.
In general you use notifyDataSetInvalidated() if item properties change, and notifyDataSetChanged() if items themselves change (i.e. items are removed or added).