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.
Related
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
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);
}
May be this question many times.
i am getting some data from server and showing in listview . every thing working fine but i am getting problem to show image in list view.
Here is my example code
public class MainActivity extends ListActivity {
private static String url = null;
private static final String book_name = "b_name";
private static final String book_detail = "b_publisher";
private static final String book_image = "b_image";
ProgressDialog progressDialog;
ListView lv;
String cus_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
url = getResources().getString(R.string.url);
/*----Receiving data from Splash Activity-----*/
Bundle b = getIntent().getExtras();
cus_id = b.getString("custom_id");
new ProgressTask(MainActivity.this).execute();
}
class ProgressTask extends AsyncTask<String, Integer, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(final Boolean success) {
progressDialog.dismiss();
}
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
setBookImageUrl(b_image);
setBookName(b_name);
setBookDetail(b_detail);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
public String getBookImageUrl() {
return book_image;
}
public CharSequence getBookName() {
return book_name;
}
public CharSequence getBookDetail() {
return book_detail;
}
public void setBookImageUrl(String imgeUrl) {
book_image = imgeUrl;
}
public void setBookName(String b_name) {
book_name = b_name;
}
public void setBookDetail(String b_detail) {
book_detail = b_detail;
}
}
BookListAdapter class:
public class BookListAdapter extends ArrayAdapter<MainActivity> {
private ArrayList<MainActivity> bookModels;
private Context context;
public BookListAdapter(Context context, int resource,
ArrayList<MainActivity> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row_list_item, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView.findViewById(R.id.icon);
viewHolder.bookName = (TextView) rowView.findViewById(R.id.b_name);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.b_detail);
rowView.setTag(viewHolder);
}
final MainActivity bookModel = bookModels.get(position);
ViewHolder holder = (ViewHolder) rowView.getTag();
Picasso.with(context).load(bookModel.getBookImageUrl())
.into(holder.bookIcon);
holder.bookName.setText(bookModel.getBookName());
holder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
i can show book name and book detail in listview finely but image is not showing ..
i am getting value for book_image is http:\/\/X.X.X.X\/admin\/book_images\/232513pic9.png how to show in listview from that path..
I think you will need to implement your own adapter and use some library to display the image from URL.
My recommendation is Picasso
This is an example to implement your own adapter
BookListAdapter.java
public class BookListAdapter extends ArrayAdapter<BookModel> {
private ArrayList<BookModel> bookModels;
private Context context;
public BookListAdapter(Context context, int resource, ArrayList<BookModel> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.book_child_list, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView
.findViewById(R.id.bookIcon);
viewHolder.bookName = (TextView) rowView
.findViewById(R.id.bookName);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.bookDetail);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
final BookModel bookModel = bookModels.get(position);
Picasso.with(context).load(bookModel.getBookImageUrl()).into(viewHolder.bookIcon);
viewHolder.bookName.setText(bookModel.getBookName());
viewHolder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
BookModel.java
public class BookModel {
private String bookName;
private String bookDetail;
private String bookImageUrl;
public BookModel() {
bookName = "";
bookDetail = "";
bookImageUrl = "";
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookDetail() {
return bookDetail;
}
public void setBookDetail(String bookDetail) {
this.bookDetail = bookDetail;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public void setBookImageUrl(String bookImageUrl) {
this.icons = bookImageUrl;
}
}
Where BookModel class is a class where you can wrap your data (book name, book detail, book image) and pass it as a list to the adapter.
for example :
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
ArrayList<BookModel> bookModelList = new ArrayList<BookModel>();
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
BookModel bookModel = new BookModel();
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
bookModel.setBookName(b_name);
bookModel.setBookDetail(b_detail);
bookModel.setBookImageUrl(b_image);
bookModelList.add(bookModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if(bookModelList.size()>0) {
BookListAdapter bookListAdapter = new BookListAdapter(MainActivity.this, R.id.yourlistview, bookModelList );
}
return null;
}
I hope my answer can help you!
lv.setAdapter(adapter);
use AQuery lib.
and just write this code in your custom adapter:
AQuery aQuery = new AQuery(context);
aQuery.id(your image id).image(your url,true,true);
I've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.
My listview doesn't show exact placement of images on its individual custom adapters. I am trying to load the images using AsyncTask. Sometimes the images duplicates and I don't have any idea why. Here is my ArrayAdapter code:
public class NewsPromoAdapter extends ArrayAdapter<NewsPromosDTO> {
private final Context context;
List<NewsPromosDTO> npList;
LayoutInflater inflater;
Bitmap src;
public NewsPromoAdapter(Context context, List<NewsPromosDTO> npList) {
super(context, R.layout.news_and_promos, npList);
this.context = context;
this.npList = npList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
TextView nameText;
TextView date1Text;
ImageView imageView;
ProgressBar prg;
LoadImage loadImg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.news_and_promos, parent,
false);
holder = new ViewHolder();
holder.nameText = (TextView) convertView
.findViewById(R.id.newspromo_name);
holder.date1Text = (TextView) convertView
.findViewById(R.id.newspromo_date);
holder.imageView = (ImageView) convertView
.findViewById(R.id.newspromo_imageView);
holder.prg = (ProgressBar) convertView
.findViewById(R.id.progressBar1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.loadImg.cancel(true);
}
if (!(npList.get(position).getName().equals(""))) {
holder.nameText.setVisibility(View.VISIBLE);
holder.nameText.setText(npList.get(position).getName());
} else {
holder.nameText.setVisibility(View.GONE);
}
if (!(npList.get(position).getDate().equals(""))) {
holder.date1Text.setVisibility(View.VISIBLE);
holder.date1Text.setText(npList.get(position).getDate());
} else {
holder.date1Text.setVisibility(View.GONE);
}
if (!(npList.get(position).getImageURL().equals(""))) {
holder.imageView.setVisibility(View.VISIBLE);
holder.loadImg = new LoadImage(holder.imageView, npList.get(
position).getImageURL(), holder);
holder.loadImg.execute();
} else {
holder.imageView.setVisibility(View.GONE);
holder.prg.setVisibility(View.GONE);
}
return convertView;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
ViewHolder viewH;
private ImageView imv;
private String url;
public LoadImage(ImageView imv, String imageURL, ViewHolder viewH) {
this.imv = imv;
this.url = imageURL;
this.viewH = viewH;
}
#Override
protected Bitmap doInBackground(Object... params) {
BitmapFromURL bmpURL = new BitmapFromURL();
src = bmpURL.getBitmapFromURL(url);
return src;
}
#Override
protected void onPostExecute(Bitmap result) {
// imv.setImageBitmap(result);
// viewH.prg.setVisibility(View.GONE);
viewH.prg.setVisibility(View.GONE);
imv.setImageBitmap(result);
}
}
}
Here is the Activity that handles the ADAPTER. I am implementing the Endless listview approach that some big sites uses. Like Facebook, Twitter, etc..New Items loaded into the listview when scrolling into the bottom. I am not sure if I did it well.
public class ListNewsPromoActivity extends Activity {
List<NewsPromosDTO> npList;
String url, user_email;
Bundle extras;
int user_points;
List<Integer> npIDs;
private ProgressDialog progressDialog;
BitmapFromURL bmpURL;
JSONArray users = null;
String TAG_ID = "id";
String TAG_NAME = "name";
String TAG_PHOTO = "photo";
String TAG_DATE = "date";
String TAG_DESC = "description";
ListView list;
NewsPromoAdapter newsAdapter;
boolean loadingMore = false;
private Runnable returnRes;
int itemsPerPage = 3;
int currentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.news_promo_listview);
list = (ListView) findViewById(R.id.mainView);
extras = getIntent().getExtras();
if (extras != null) {
user_points = extras.getInt("user_points");
user_email = extras.getString("user_email");
}
url = getString(R.string.app_url_news_promos);
npIDs = new ArrayList<Integer>();
npList = new ArrayList<NewsPromosDTO>();
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
list.setOnScrollListener(new OnScrollListener() {
// useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
// is the bottom item visible & not loading more already ? Load
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
Thread thread = new Thread(null, getRunnable());
thread.start();
}
}
});
// Runnable to load the items
// Since we cant update our UI from a thread this Runnable takes care of
// that!
returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
for (NewsPromosDTO np : npList) {
System.out.println(np.getName() + " andito ako!!");
newsAdapter.add(np);
}
newsAdapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
}
protected class loadNewsPromo extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
// Creating JSON Parser instance
loadingMore = true;
JSONParser jParser = new JSONParser();
JSONObject json;
if (jParser.checkServer(url)) {
try {
// Getting Array of UserNews
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All UserNews
for (int i = currentIndex; i < itemsPerPage; i++) {
if (itemsPerPage == i) {
// currentIndex--;
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
} finally {
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) { //
// progressDialog.dismiss();
loadingMore = false;
list();
}
}
public void list() {
// add the footer before adding the adapter, else the footer will not
// load!
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
}
public Runnable getRunnable() {
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Get 15 new listitems
JSONParser jParser = new JSONParser();
JSONObject json;
npList = new ArrayList<NewsPromosDTO>();
if (jParser.checkServer(url)) {
try {
// Getting Array of Contacts
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All Contacts
// if (itemsPerPage > users.length() - currentIndex) {
// itemsPerPage = users.length();
// }
npList = new ArrayList<NewsPromosDTO>();
System.out.println(users.length() + " Laman ng users");
int counter = 0;
for (int i = currentIndex; i < users.length(); i++) {
if (itemsPerPage == counter) {
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
counter++;
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
}
// Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
return loadMoreListItems;
}
}