Am trying search from listview using custom adapter. i have search widget in toolbar menu and i can display widget. when i click on search icon, it expands, but when i start typing, search does not happen and list gets cleared. can someone plz trace this issue .
Here's my code from Main Activity:
public class VideoActivity extends BaseActivity {
ListView listView;
ArrayList<Video> videoArrayList;
public VideoListAdapter videoListAdapter;
String vid_id, vid_title, vid_type, vid_path, vid_img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
initializeToolbar();
listView = (ListView) findViewById(R.id.listview_video);
videoArrayList = new ArrayList<Video>();
videoListAdapter = new VideoListAdapter(VideoActivity.this, videoArrayList);
jsonParser = new JSONParser();
new VideoTask().execute();
public class VideoTask extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
jsonObject = jsonParser.makeHttpRequest2(Network_constants.video_list_page, "POST");
Log.e("json data", "" + jsonObject);
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
progressDialog.dismiss();
if (jsonObject != null) {
try {
jsonArray = jsonObject.getJSONArray("videos");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Log.d("jsonObject1", "" + jsonObject1);
Video video = new Video();
vid_id = jsonObject1.getString("video_id");
vid_title = jsonObject1.getString("video_channel_name");
vid_type = jsonObject1.getString("video_channel_link");
vid_path = jsonObject1.getString("video_channel_description");
vid_img = jsonObject1.getString("video_img_path");
video.set_vTitle(vid_title);
TextView t1 = (TextView) findViewById(R.id.video_title);
TextView t2 = (TextView) findViewById(R.id.video_type);
video.set_vArtist(vid_title);
video.set_vType(vid_type);
videoArrayList.add(video);
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(videoListAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView cnt = (TextView) view.findViewById(R.id.video_type);
String cn = cnt.getText().toString();
Intent i = new Intent(VideoActivity.this, Youtube.class);
i.putExtra("url", cn);
startActivity(i);
}
});
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.clear();
getMenuInflater().inflate(R.menu.main,menu);
MenuItem menuItem = menu.findItem(R.id.menu_search);
final SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(TextUtils.isEmpty(newText)){
LogHelper.e("Query Result","Filter is Empty");
}else{
videoListAdapter.filter(newText);
}
return true;
}
});
return true;
}
}
And this is my CustomAdapter class :
public class VideoListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
ImageView imageView;
private String mCurrentArtUrl;
private ArrayList<Video> video;
private ArrayList<Video> searchListView = null;
public VideoListAdapter(Activity a, ArrayList<Video> b){
this.activity = a;
this.video = b;
this.searchListView = new ArrayList<Video>();
this.searchListView.addAll(video);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return video.size();
}
#Override
public Object getItem(int position) {
return video.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.video_list_item, null);
final TextView v_title = (TextView)vi.findViewById(R.id.video_title);
final TextView v_type = (TextView)vi.findViewById(R.id.video_type);
final TextView v_artist = (TextView)vi.findViewById(R.id.video_artist);
imageView = (ImageView) vi.findViewById(R.id.video_image);
Video video1 = video.get(position);
v_title.setText(video1.get_vTitle());
v_type.setText(video1.get_vType());
v_artist.setText(video1.get_vArtist());
String img = video1.get_vImage();
String profile = Network_constants.image_url + img;
fetchImageAsync(profile);
return vi;
}
// Filter method
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
video.clear();
if(charText.length() == 0){
video.addAll(searchListView);
}else{
for(Video v : searchListView){
LogHelper.e("Query","Entered For Loop");
if(v.get_vTitle().contains(charText)){
video.add(v);
}else{
LogHelper.e("Query","Could not create list");
}
}
}
notifyDataSetChanged();
}
}
I think my code is not working with the for loop in the filter function i guess.
You should implements Filterable in your Adapter
Related
Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});
I have listview and after filtering items of listview when I click on item its always returning wrong position of listview item.
Following is Adapter Class:
public class AdmitPatientAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> TempArrList = new ArrayList<>();
private static LayoutInflater inflater = null;
public static final String TAG_MRDNO = "mrd_no";
public AdmitPatientAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
TempArrList.addAll(d);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return TempArrList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
TempArrList.clear();
if (charText.length() == 0) {
TempArrList.addAll(data);
} else {
HashMap<String, String> tMap;
for (int i = 0; i < data.size(); i++) {
tMap = data.get(i);
if (charText.length() != 0 && tMap.get("mrd_no").toLowerCase(Locale.getDefault()).contains(charText)) {//mrd_no
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("pname").toLowerCase(Locale.getDefault()).contains(charText)) {//pname
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("bed_no").toLowerCase(Locale.getDefault()).contains(charText)) {
TempArrList.add(tMap);
} else if (charText.length() != 0 && tMap.get("nursingstation").toLowerCase(Locale.getDefault()).contains(charText)) {
TempArrList.add(tMap);
}
}
notifyDataSetChanged();
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View viw = convertView;
if (convertView == null)
viw = inflater.inflate(R.layout.ip_ptn_items, null);
TextView txt_Mr_dno = (TextView) viw.findViewById(R.id.txtMrdno);
TextView txt_pitnt_Name = (TextView) viw.findViewById(R.id.txtpitntName);
TextView txt_Bed_no = (TextView) viw.findViewById(R.id.txtBedno);
TextView txt_Dob = (TextView) viw.findViewById(R.id.txtDob);
TextView txt_drNme = (TextView) viw.findViewById(R.id.txtDr);
TextView txt_Sex = (TextView) viw.findViewById(R.id.txtSex);
TextView txt_Wrdnm = (TextView) viw.findViewById(R.id.txtWrdnm);
HashMap<String, String> item = new HashMap<String, String>();
item = TempArrList.get(position);
String mrd_no = item.get(TAG_MRDNO);
item.put(TAG_MRDNO, mrd_no);
mrd_no = item.get(TAG_MRDNO);
if (mrd_no.endsWith("*")) {
txt_Mr_dno.setTextColor(Color.RED);
txt_pitnt_Name.setTextColor(Color.RED);
txt_Dob.setTextColor(Color.RED);
txt_Sex.setTextColor(Color.RED);
txt_Wrdnm.setTextColor(Color.RED);
txt_Bed_no.setTextColor(Color.RED);
} else {
txt_Mr_dno.setTextColor(Color.BLACK);
txt_pitnt_Name.setTextColor(Color.BLACK);
txt_Dob.setTextColor(Color.BLACK);
txt_Sex.setTextColor(Color.BLACK);
txt_Wrdnm.setTextColor(Color.BLUE);
txt_Bed_no.setTextColor(Color.BLUE);
}
//Setting all values in listview
txt_Mr_dno.setText(item.get("mrd_no"));
txt_pitnt_Name.setText(item.get("pname"));
txt_Bed_no.setText(item.get("bed_no"));
txt_Dob.setText(item.get("dob"));
//txt_admit_Date.setText(item.get("admission_date"));
txt_Sex.setText(item.get("sex"));
txt_Wrdnm.setText(item.get("nursingstation"));
txt_drNme.setText(item.get("doctor"));
// item = data.get(position);
/// String userType = item.get(TAG_UTYPE);
// item.put(TAG_UTYPE, mrd_no);
// userType = item.get(TAG_UTYPE);
try {
if (item.get("userType").equals("doctor")) {
txt_drNme.setVisibility(View.INVISIBLE);
} else {
txt_drNme.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
return viw;
}
}
and another one is on click event class:
public class AdmitPatientFragment extends Fragment implements FragmentCycle {
ListView lstViw;
AdmitPatientAdapter adapter;
String DcId = "";
String userType = "";
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
// generic array list
ArrayList<HashMap<String, String>> dlst = new ArrayList<HashMap<String, String>>();
// json url
private static String url = "http://scanweb.dmhospital.org:81/amrita_login/AdmList.php?auth=Yes";
#Override
public void onResumeFragment() {
}
#Override
public void onPauseFragment() {
}
// json node names
private static final String TAG_ADMITLIST = "AdmissionList";
private static final String TAG_MRD = "mrd_no";
private static final String TAG_PNAME = "pname";
private static final String TAG_BNO = "bed_no";
private static final String TAG_DOB = "dob";
private static final String TAG_ADMIT_DATE = "admission_date";
private static final String TAG_DOCTOR = "doctor";
private static String TAG_SEX = "sex";
private static String TAG_PATN_ID = "patient_id";
private static String TAG_VISIT_ID = "visit_id";
private static final String TAG_WARD_NAME = "nursingstation";
public static final String TAG_UTYPE = "userType";
JSONArray AdmissionList = null;
public AdmitPatientFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setReturnTransition(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
LinearLayout rootView = (LinearLayout) inflater.inflate(
R.layout.ip_ptn_lstviw, container, false);
dlst = new ArrayList<HashMap<String, String>>();
Intent intent = getActivity().getIntent();
DcId = intent.getStringExtra("drid");
if (CheckNetwork.isInternetAvailable(getActivity())) //returns true if internet available
{
} else {
Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
// to read doctor id from shared preferences
sharedPreferences = getActivity().getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
DcId = sharedPreferences.getString("drid", DcId);
userType = sharedPreferences.getString("usertype", userType);
url = url + "&docID=" + DcId;
new paAsyncTask().execute();
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.three_dots_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
final MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
//*** setOnQueryTextFocusChangeListener ***
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String searchQuery) {
adapter.filter(searchQuery.toString().trim());
lstViw.invalidate();
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
private class paAsyncTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait admit patient list is loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
AdmissionList = json.getJSONArray(TAG_ADMITLIST);
dlst = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < AdmissionList.length(); i++) {
JSONObject c = AdmissionList.getJSONObject(i);
String admission_date = c.getString(TAG_ADMIT_DATE);
HashMap<String, String> map = new HashMap<String, String>();
String ageSex = "(" + c.getString(TAG_DOB) + " | " + c.getString(TAG_SEX) + ")";
String[] admDte = admission_date.split(":");
String[] admDte1 = admission_date.split(":");
String resultDte = admDte[0] + ":" + admDte1[1];
map.put(TAG_MRD, c.getString(TAG_MRD).toString());
map.put(TAG_PNAME, c.getString(TAG_PNAME));
map.put(TAG_BNO, c.getString(TAG_BNO));
map.put(TAG_DOB, ageSex);
map.put(TAG_ADMIT_DATE, resultDte);
map.put(TAG_UTYPE, userType);
map.put(TAG_DOCTOR, c.getString(TAG_DOCTOR).toString());
// map.put(TAG_SEX, str);
map.put(TAG_WARD_NAME, c.getString(TAG_WARD_NAME));
map.put(TAG_PATN_ID, c.getString(TAG_PATN_ID));
map.put(TAG_VISIT_ID, c.getString(TAG_VISIT_ID));
dlst.add(map);
}
lstViw = (ListView) getView().findViewById(R.id.lstAdmsion);
adapter = new AdmitPatientAdapter(getActivity(), dlst);
adapter.notifyDataSetChanged();
lstViw.setAdapter(adapter);
lstViw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
HashMap<String, String> map = dlst.get(position);
Intent imp = new Intent(getActivity(),
NavigationDrawerActivity.class);
imp.putExtra("drid", DcId);
// imp.putExtra(TAG_ADMIT_DATE, map.get(""));
imp.putExtra("docNme", map.get(TAG_DOCTOR));
imp.putExtra("ptnId", map.get(TAG_PATN_ID));
imp.putExtra("vst_id", map.get(TAG_VISIT_ID));
startActivity(imp);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try changing
HashMap<String, String> map = dlst.get(position);
to
HashMap<String, String> map = adapter.getItem(position);
Basically, the OnItemClickListener is grabbing objects from your ListView rather than your Adapter that has updated references...
EDIT 1: You also need to implement getItem in your Adapter so it returns an object from your filtered list. I'm assuming that's dlst...
So, you would need to put this in your adapter class:
public HashMap<String, String> getItem(int position){
return dlst.get(position);
}
android ListActivity how to make Custom Adapter getter setter using ,call json Volley library populate data ListActivity ? could not populate data with Json how to implement ,Please Help me
my code
ItemFragment Class
public class ItemFragment extends ListActivity {
RequestParse requestParse;
MySharedPreferences prefs;
String UsrId;
Context context;
ArrayList<BizForumArticleInfo> list = new ArrayList<>();
private List<BizForumArticleInfo> CountryCodeNumber = new ArrayList<>();
MobileArrayAdapter adapter;
LinearLayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
requestParse = new RequestParse();
prefs = MySharedPreferences.getInstance(this, SESSION);
UsrId = prefs.getString("UsrID", "");
context = getApplicationContext();
setListAdapter(new MobileArrayAdapter(this,0, list));
getJson(60);
}
public void getJson(final int limit){
requestParse.postJson(ConfigApi.postArticleBiz(), new RequestParse.VolleyCallBackPost() {
#Override
public void onSuccess(String result) {
list = parseResponse(result);
}
#Override
public void onRequestError(String errorMessage) {
}
#Override
public Map OnParam(Map<String, String> params) {
params.put("sessionid", UsrId);
params.put("offset", "0");
params.put("limit", String.valueOf(limit));
params.put("viewtype", "all");
params.put("access_token","e3774d357aa7d4bd14e9763b5459ee9cf7ebe36161c142551836ee510d98814a:b349b76b334a94b2");
return params;
}
});
}
public static ArrayList<BizForumArticleInfo> parseResponse(String response) {
ArrayList<BizForumArticleInfo> bizList = new ArrayList<>();
try {
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray(DATA);
for (int i = 0; i < data.length(); i++) {
BizForumArticleInfo ls = new BizForumArticleInfo();
JSONObject item = data.getJSONObject(i);
String ArticleTitle = item.getString("ArticleTitle");
String Article = item.getString("Article");
M.i("===================",ArticleTitle);//working
ls.setArticleTitle(ArticleTitle);
ls.setArticleArticle(Article);
bizList.add(ls);
}
} catch (JSONException e) {
e.printStackTrace();
}
return bizList;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("selectedValue", selectedValue);
setResult(RESULT_OK, intent);
finish();
//startActivity(new Intent(v.getContext(), MainActivity.class));
}
}
Adapter Class
public class MobileArrayAdapter extends ArrayAdapter<BizForumArticleInfo> {
private Activity activity;
private ArrayList<BizForumArticleInfo> lPerson;
private static LayoutInflater inflater = null;
public MobileArrayAdapter (Activity activity, int textViewResourceId,ArrayList<BizForumArticleInfo> _lPerson) {
super(activity, textViewResourceId, _lPerson);
try {
this.activity = activity;
this.lPerson = _lPerson;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
}
}
public int getCount() {
return lPerson.size();
}
public BizForumArticleInfo getItem(BizForumArticleInfo position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView display_name;
public TextView display_number;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.list_mobile, null);
holder = new ViewHolder();
holder.display_name = (TextView) vi.findViewById(R.id.label);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.display_name.setText(lPerson.get(position).getArticleTitle());
} catch (Exception e) {
}
return vi;
}
}
Explanation:
I have a listview in my fragment. When I click one of the row of the listview it goes to another activity.In listview,I got the data from the adapter.
Inside the adapter view,I set the setOnClick().
Problem is when I click one of the row multiple time it is opening multiple activity.I want to restrict only one time click on the particular row over the listview item.
Here is my fragment where I get the listview and set the adapter-
public class HomeFragment extends Fragment{
public HomeFragment() {
}
public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
private static String url = "";
List<String> lst_key = null;
List<JSONObject> arr_completed = null;
List<String> lst_key2 = null;
List<JSONObject> lst_obj = null;
List<String> list_status = null;
ListView completed_listview;
int PagerLength = 0,exeption_flag=0;
View rootView;
private ViewPager pagerRecentMatches;
private ImageView imgOneSliderRecent;
private ImageView imgTwoSliderRecent;
private ImageView imgThreeSliderRecent;
private ImageView imgFourSliderRecent;
private ImageView imgFiveSliderRecent;
private ImageView imgSixSliderRecent;
private ImageView imgSevenSliderRecent;
private ImageView imgEightSliderRecent;
LinearLayout selector_dynamic;
LinearLayout Recent_header_layout;
FrameLayout adbar;
String access_token = "";
SharedPreferences sharedPreferences;
int current_pos=0,status_flag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
findViews();
selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
new AddLoader(getContext()).LoadAds(adbar);
MainActivity activity = (MainActivity) getActivity();
access_token = activity.getMyData();
sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (access_token == null || access_token=="") {
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";
} else {
editor.putString("access_token", access_token);
editor.commit();
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
}
completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);
Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);
Recent_header_layout.setVisibility(View.GONE);
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
new TabJson().execute();
}
pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
return rootView;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void dialog_popup() {
final Dialog dialog = new Dialog(getContext());
DisplayMetrics metrics = getResources()
.getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.internet_alert_box);
dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
getActivity().finish();
}
});
dialog.show();
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
dialog.dismiss();
new TabJson().execute();
}
}
});
dialog.show();
}
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
exeption_flag=0;
status_flag = 0;
if (jsonStr != null) {
try {
if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
exeption_flag = 1;
} else {
JSONObject obj = new JSONObject(jsonStr);
if (obj.has("status") && !obj.isNull("status")) {
if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
status_flag = 1;
} else {
JSONObject data = obj.getJSONObject("data");
JSONArray card = data.getJSONArray("cards");
PagerLength = 0;
lst_obj = new ArrayList<>();
list_status = new ArrayList<>();
lst_key = new ArrayList<>();
lst_key2 = new ArrayList<>();
arr_completed = new ArrayList<>();
for (int i = 0; i < card.length(); i++) {
JSONObject card_obj = card.getJSONObject(i);
if (card_obj.getString("status").equals("started")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("notstarted")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("completed")) {
arr_completed.add(card_obj);
lst_key2.add(card_obj.getString("key"));
}
}
}
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Utils.Pdialog_dismiss();
if (status_flag == 1 || exeption_flag==1) {
dialog_popup();
} else {
Recent_header_layout.setVisibility(View.VISIBLE);
LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
adapterTabRecent.notifyDataSetChanged();
pagerRecentMatches.setAdapter(adapterTabRecent);
pagerRecentMatches.setCurrentItem(current_pos);
ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
CmAdapter.notifyDataSetChanged();
completed_listview.setAdapter(CmAdapter);
}
}
}
private void findViews() {
pagerRecentMatches = (ViewPager) rootView
.findViewById(R.id.pager_recent_matches);
imgOneSliderRecent = (ImageView) rootView
.findViewById(R.id.img_one_slider_recent);
imgTwoSliderRecent = (ImageView) rootView
.findViewById(R.id.img_two_slider_recent);
imgThreeSliderRecent = (ImageView) rootView
.findViewById(R.id.img_three_slider_recent);
imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
After load the data from the server it passed to the onPost() i called an adapter which extends BaseAdpter
Here is my BaseAdapter
package adapter;
public class ScheduleAdapter extends BaseAdapter{
private Context context;
private List<JSONObject> arr_schedule;
private List<String> arr_matchKey;
private static LayoutInflater inflater;
int flag = 0;
String time="";
String status="";
String match_title = "";
String match_key="";
public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
this.context=context;
this.arr_schedule=arr_schedule;
this.arr_matchKey=arr_matchKey;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.arr_schedule.size();
}
#Override
public Object getItem(int position) {
return this.arr_schedule.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder{
TextView txt_one_country_name;
TextView txt_two_country_name;
TextView txt_venue;
TextView txtTimeGMT;
TextView txtDate;
TextView txtTimeIST;
ImageView team_one_flag_icon;
ImageView team_two_flag_icon;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
String[] parts;
String[] state_parts;
String[] match_parts;
Typeface tf=null;
String winner_team = "";
String final_Score="";
String now_bat_team="",team_name="";
String related_status="";
if(convertView==null) {
convertView = inflater.inflate(R.layout.recent_home_layout, null);
holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
holder.txt_one_country_name.setTypeface(tf);
holder.txt_two_country_name.setTypeface(tf);
holder.txt_venue.setTypeface(tf);
holder.txtTimeIST.setTypeface(tf);
holder.txtTimeGMT.setTypeface(tf);
holder.txtDate.setTypeface(tf);
convertView.setTag(holder);
}
else{
holder=(Holder)convertView.getTag();
}
try {
String overs="";
String wickets_now="";
String now_runs="";
String[] over_parts;
time = "";
JSONObject mainObj = this.arr_schedule.get(position);
status = mainObj.getString("status");
String name = mainObj.getString("short_name");
String state = mainObj.getString("venue");
String title = mainObj.getString("title");
related_status=mainObj.getString("related_name");
JSONObject start_date = mainObj.getJSONObject("start_date");
JSONObject teams=null;
JSONObject team_a=null;
JSONObject team_b=null;
String team_a_key="";
String team_b_key="";
time = start_date.getString("iso");
parts = name.split("vs");
match_parts = title.split("-");
state_parts = state.split(",");
int length = state_parts.length;
flag=0;
match_title="";
winner_team="";
if (!mainObj.isNull("msgs")) {
JSONObject msgs = mainObj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
flag = 1;
}
}
match_title=name+" - "+match_parts[1];
JSONObject now=null;
if(mainObj.has("now") && !mainObj.isNull("now")) {
now = mainObj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if(now.getString("runs_str").equals("null")){
overs="0";
}
else{
over_parts=now.getString("runs_str").split(" ");
overs=over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
try {
if (!mainObj.isNull("teams") && mainObj.has("teams")) {
teams = mainObj.getJSONObject("teams");
team_a = teams.getJSONObject("a");
team_b = teams.getJSONObject("b");
team_a_key = team_a.getString("key");
team_b_key = team_b.getString("key");
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
}
}
catch (NullPointerException e){
e.printStackTrace();
}
if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
final_Score="";
}
else{
final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
}
}
holder.txt_one_country_name.setText(parts[0]);
holder.txt_two_country_name.setText(parts[1]);
if(length==1){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
holder.txtTimeGMT.setText(state_parts[0]);
}
if(length==2){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);
}
if(length==3){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
}
if(length==4){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
}
holder.txtDate.setText(final_Score);
holder.txtDate.setTypeface(tf, Typeface.BOLD);
holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
holder.txtTimeIST.setText(winner_team);
holder.txt_venue.setText(related_status);
} catch (JSONException e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
}
});
return convertView;
}
#Override
public boolean isEnabled(int position) {
return super.isEnabled(position);
}
}
This adapter set the listrow item into listview.
In ScheduleAdapter.java i set the onclick() on the convertView in which i called a GetValue class which is only implement a Asynctask to get the data and called and intent then it goes to an activity.
Means HomeFragment->ScheduleAdapter->GetValue->Scorecard
Here,
HomeFragment is fragment which have listview
ScheduleAdpter is an adapter which set data to listview which reside in homefragment
GetValue is class which implement some important task and it passed an intent and goes to an activity(It's work as a background)
ScoreCard is my activity which called after click on the row of the listview which reside in HomeFragment.
Please, help me to solve out this problem.
You can use a flag in Listview click - isListClicked, and set flag value as false in onPostexecute method of Aysnc task class -GetValue
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isListClicked){
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
isListClicked = true;
}
}
});
If you want to prevent multiple activities being opened when the user spams with touches, add into your onClick event the removal of that onClickListener so that the listener won't exist after the first press.
Easy way is you can create a model class of your json object with those field you taken in holder class. And add one more boolean field isClickable with by default with true value.Now when user press a row for the first time you can set your model class field isClickable to false. Now second time when user press a row,you will get a position of row and you can check for isClickable. it will return false this time.
Model Class :
public class CountryInfoModel {
//other fields to parse json object
private boolean isClickable; //<- add one more extra field
public boolean isClickable() {
return isClickable;
}
public void setIsClickable(boolean isClickable) {
this.isClickable = isClickable;
}
}
listview click perform :
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//country_list is your list of model class List<CountryInfo>
if(country_list.get(position).isClickable())
{
//Perform your logic
country_list.get(position).setIsClickable(false);
}else{
//Do nothing : 2nd time click
}
}
});
Try creating your custom click listener for your listview and use it. In this way
public abstract class OnListItemClickListener implements OnItemClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public abstract void onListItemSingleClick(View parent, View view, int position, long id);
public OnListItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
onListItemSingleClick(parent, view, position, id);
}
}
I'm using onScroll onclicklistner to update listview in my listFragment.
public class WishboardFragment extends ListFragment implements OnScrollListener{
private ProgressBar progressBar2;
private TextView finished;
private Context context = null;
private ListAdapter wishAdapter = null;
private final String TAG = "wishboard";
private final String cachedName = "wishboard";
JSONObject jsonObject = null;
JSONArray jsonArray = null;
private Menu optionsMenu;
private Integer pageStart = 1;
private Integer pageEnd = 15;
private Boolean isDownloading = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.context = getActivity();
return inflater.inflate(R.layout.activity_dashboard,container,false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
String url = getWishboardUrl();
sendRequest(url);
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
wishAdapter = new WishRowAdaptor(getActivity(),this.getWishboardCached());
setListAdapter(wishAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
this.optionsMenu = menu;
inflater.inflate(R.menu.dashboard, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
getListView().setOnScrollListener(this);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.btn_refresh:
Common.setRefreshActionButtonState(true,optionsMenu);
String url = getWishboardUrl();
sendRequest(url);
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendRequest(String url) {
new SendRequest().execute(url);
}
private class SendRequest extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... requestURL) {
String data = "";
HttpURLConnection httpUrlConnection = null;
try {
URL url = new URL(requestURL[0]);
URLConnection connection = url.openConnection();
connection.setUseCaches(true);
Object response = connection.getContent();
Log.i(TAG, "Requesting http "+requestURL[0]);
if (response instanceof Bitmap) {
}
InputStream in = new BufferedInputStream(
connection.getInputStream());
data = Common.readStream(in);
} catch (MalformedURLException exception) {
Log.e(TAG, "MalformedURLException");
} catch (IOException exception) {
Log.e(TAG, "IOException");
} finally {
if (null != httpUrlConnection)
httpUrlConnection.disconnect();
}
return data;
}
protected void onPostExecute(String jsonString) {
jsonObject = Common.getObjectFromJsonString(jsonString,3);
ArrayList<HashMap<String, String>> wishList = Common.parseJson(jsonObject);
if (pageEnd > Constants.limit) {
wishAdapter = new WishRowAdaptor(getActivity(),wishList);
}else{
Common.cacheResponse(context,cachedName,jsonString);
wishAdapter = new WishRowAdaptor(getActivity(),wishList);
setListAdapter(wishAdapter);
Common.setRefreshActionButtonState(false, optionsMenu);
}
isDownloading = false;
}
}
private ArrayList<HashMap<String, String>> getWishboardCached() {
String jsonString = Common.getCachedResponse(context,cachedName);
try {
jsonObject = Common.getObjectFromJsonString(jsonString,3);
ArrayList<HashMap<String, String>> wishList = Common.parseJson(jsonObject);
return wishList;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (view.getAdapter() != null
&& ((firstVisibleItem + visibleItemCount) >= totalItemCount)
&& isDownloading == false) {
pageStart = pageEnd + 1;
pageEnd = pageStart + (Constants.limit -1);
String url = getUrl();
sendRequest(url);
isDownloading = true;
}
}
}
In the above code If use setListAdapter(wishAdapter); in onPostExecute() after user has reached end of list. Listview gets updated but all the preveious entries goes away.
Here is my custom adapter
public class WishRowAdaptor extends BaseAdapter {
public WishRowAdaptor(Context context,
ArrayList<HashMap<String, String>> arrayList) {
// TODO Auto-generated constructor stub
this.mData = arrayList;
this.context = context;
this.listAq = new AQuery(context);
// mKeys = mData.keySet().toArray(new String[arrayList.size()]);
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtWishName;
ImageButton btn_touchwood;
ImageButton btn_addwish;
TextView tvGesture;
TextView tvNotes;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final HashMap<String, String> rowItem = (HashMap<String, String>) getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_wish, null);
holder = new ViewHolder();
holder.txtWishName = (TextView) convertView
.findViewById(R.id.tvwishname);
holder.imageView = (ImageView) convertView
.findViewById(R.id.ivWishImage);
holder.btn_touchwood = (ImageButton) convertView
.findViewById(R.id.btn_touchwood);
holder.btn_addwish = (ImageButton) convertView
.findViewById(R.id.btn_addwish);
holder.tvGesture = (TextView) convertView
.findViewById(R.id.tvGestures);
holder.tvNotes = (TextView) convertView
.findViewById(R.id.tvNotesText);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
return convertView;
}
}
How do update listview so that it should push new changes to list instead replacing all the content.
you are changing the adapter of the list adapter after each websevice call. just call notifyDataSetChanged after changing the items of your array list. Also dont replace the items of the array list. add the new to your arraylist.