I am trying to show some data offline from SQLite database. Data is coming fine but I am not able to show that on listview with adapter.
libraryList.clear();
libraryList = dBhelper.localQuestionBank(student_uuid, questionBankId);
if (libraryList.size() > 0) {
offSetFlag = libraryList.size();
libraryListView.setAdapter(questionBankAdapter);
questionBankAdapter.notifyDataSetChanged();
libraryListView.removeFooterView(loadMoreView);
loadingMore = false;
}
localQuestionBank method:
public ArrayList<Map<String, String>> localQuestionBank(String student_uuid, String question_bank_id) {
ArrayList<Map<String, String>> localQuestionBankList = new ArrayList<>();
ArrayList<Map<String, String>> questionBankList = new ArrayList<>();
String[] columns = new String[]{QUESTION_BANK_LABEL, AIP_UUID, QUESTION_SEQUENCE_NAME, QUESTION_MARKS, DESCRIPTION};
SQLiteDatabase db = mDbHelper.getWritableDatabase();
try {
Cursor cursor = db.query(LOCAL_QUESTION_BANK, columns, STUDENT_UUID+"=?" +" and "+ QUESTION_BANK_ID+"=?", new String[] { student_uuid, question_bank_id }, null, null, null);
if (cursor.moveToFirst()) {
do {
Map<String, String> subMap = new HashMap<String, String>();
subMap.put("aep_uuid", cursor.getString(cursor.getColumnIndex(AIP_UUID)));
subMap.put("question_marks", cursor.getString(cursor.getColumnIndex(QUESTION_MARKS)));
subMap.put("question_sequence_name", cursor.getString(cursor.getColumnIndex(QUESTION_SEQUENCE_NAME)));
subMap.put("description", cursor.getString(cursor.getColumnIndex(DESCRIPTION)));
subMap.put("question_bank_label", cursor.getString(cursor.getColumnIndex(QUESTION_BANK_LABEL)));
questionBankList.add(subMap);
} while (cursor.moveToNext());
localQuestionBankList.addAll(questionBankList);
questionBankList.clear();
}
cursor.close();
db.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
return localQuestionBankList;
}
Listview and Adapter:
questionBankAdapter = new QuestionBankAdapter(getActivity(),libraryList);
libraryListView.setAdapter(questionBankAdapter);
questionBankAdapter:
package eukti.myafterclass.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Map;
import eukti.myafterclass.R;
import eukti.myafterclass.ui.QuestionBankDetailsView;
import eukti.myafterclass.utils.InternetConnectionDetector;
public class QuestionBankAdapter extends BaseAdapter {
private final Activity context;
private ArrayList<Map<String, String>> dashboardList;
private static LayoutInflater inflater=null;
public QuestionBankAdapter(Activity context,
ArrayList<Map<String, String>> dashList) {
this.context = context;
this.dashboardList = dashList;
if (context!=null) {
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
#Override
public int getCount() {
return dashboardList.size();
}
#Override
public Object getItem(int position) {
return dashboardList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView sequence;
TextView marks;
WebView description;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
View rowView;
Log.d("LocalQBadapter:", dashboardList.get(position).get("question_sequence_name"));
rowView = inflater.inflate(R.layout.questionbank_items, null);
holder.sequence=(TextView) rowView.findViewById(R.id.questionSequenceName);
holder.marks=(TextView) rowView.findViewById(R.id.marks);
holder.description=(WebView) rowView.findViewById(R.id.description);
holder.description.getSettings().setJavaScriptEnabled(true);
String heading = dashboardList.get(position).get("question_sequence_name");
holder.sequence.setText(Html.fromHtml(heading));
holder.marks.setText("Marks : "+dashboardList.get(position).get("question_marks"));
String description = dashboardList.get(position).get("description");
String allAns = "<html><body>"+description.replace("\r\n", "<br/>")+"</body></html>";
holder.description.loadDataWithBaseURL(null, allAns, "text/html", "utf-8", null);
holder.description.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
holder.description.setLongClickable(false);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!InternetConnectionDetector.isNetworkAvailable(context)) {
Toast.makeText(context, "Check your connection and try again.", Toast.LENGTH_LONG).show();
} else {
Intent redirect = new Intent(context, QuestionBankDetailsView.class);
redirect.putExtra("aep_uuid", dashboardList.get(position).get("aep_uuid"));
redirect.putExtra("question_sequence_name", dashboardList.get(position).get("question_sequence_name"));
redirect.putExtra("question_marks", dashboardList.get(position).get("question_marks"));
redirect.putExtra("description", dashboardList.get(position).get("description"));
context.startActivity(redirect);
}
}
});
return rowView;
}
}
It seems fine for me but data is not showing in Listview.
What you have typed
#Override
public Object getItem(int position) {
return dashboardList.size();
}
what i think it should be
#Override
public Object getItem(int position) {
return dashboardList.get(position);
}
try it and let me know
In your getItem() method you are returning the size. You need to give the actual object from the dataset dashboardList.
#Override
public Object getItem(int position) {
return dashboardList.get(position);
}
Also in the getView code you can call the getItem method instead of accessing the dataset directly.
Map<String, String> item = (Map<String, String>) getitem(position);
Bind your UI from this item object. Also try to use a Viewholder pattern in your Adapter.
Related
I have a problem, I have created custom adapter with custom filtering on Contact object in Contacts app, it filters names of contacts just fine and list of filteredContacts is saved properly. The problem is that when I type anything in searchView, the number of found rows is correct but informations about found rows are not correct. The problem seems to be about getView function in adapter, it is not called when it should. For example if i have three contacts: "abc", "aaa", "aba" and they are shown at the beggining in this order from top to bottom, then if I type "ab" in searchView then it finds 2 rows but they are still the same as at the beggining, they should be "abc" and "aba" but they are "abc" and "aaa". The first ever view created by adapter seems to be stuck for some reason.
My activity class:
package com.example.androidlab;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class AllContactsActivity extends AppCompatActivity {
static ArrayList<Contact> contacts = new ArrayList<>();
ContactsAdapter contactsAdapter;
ListView listView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_contacts);
FloatingActionButton addContact = findViewById(R.id.newContact);
listView = findViewById(R.id.allContactsList);
searchView = findViewById(R.id.searchContacts);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.tanay.thunderbird.contacts", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("contacts", null);
Type type = new TypeToken<ArrayList<Contact>>() {
}.getType();
contacts = gson.fromJson(json, type);
if (contacts == null) {
contacts = new ArrayList<>();
}
if (contacts.size() == 0)
Toast.makeText(this, "There are no contacts.", Toast.LENGTH_LONG).show();
contactsAdapter = new ContactsAdapter(this, contacts);
listView.setAdapter(contactsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), EditContactActivity.class);
intent.putExtra("noteID", position);
startActivity(intent);
finish();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
contactsAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
contactsAdapter.getFilter().filter(query);
return false;
}
});
addContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), NewContactActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
public void onBackPressed() {
finish();
}
}
My adapter class:
package com.example.androidlab;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ContactsAdapter extends BaseAdapter implements Filterable {
Context context;
List<Contact> contacts;
List<Contact> filteredContacts;
ContactFilter mFilter = new ContactFilter();
String filterString;
ContactsAdapter(Context context, List<Contact> contacts) {
this.context = context;
this.contacts = contacts;
filteredContacts = contacts;
}
#Override
public int getCount() {
if(contacts.size() != filteredContacts.size() || filterString != null)
{
return filteredContacts.size();
}
else {
filteredContacts = contacts;
return contacts.size();
}
}
#Override
public Object getItem(int position) {
return contacts.get(position);
}
#Override
public long getItemId(int position) {
return contacts.indexOf(getItem(position));
}
#Override
public Filter getFilter() {
return mFilter;
}
private class ViewHolder {
ImageView imageView;
TextView name;
TextView phoneNumber;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(AllContactsActivity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_contacts, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.contactName);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageOfContact);
holder.phoneNumber = (TextView) convertView.findViewById(R.id.phoneNumber);
Contact contact;
if(filteredContacts.size() != contacts.size()) contact = filteredContacts.get(position);
else contact = contacts.get(position);
if (contact.getAvatar() == null) {
if (contact.getGender() == true)
holder.imageView.setImageResource(R.drawable.ic_man);
else holder.imageView.setImageResource(R.drawable.ic_woman);
} else {
byte[] decodedString = Base64.decode(contact.getAvatar(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.imageView.setImageBitmap(decodedByte);
}
holder.name.setText(contact.getName());
holder.phoneNumber.setText(String.valueOf(contact.getPhoneNumber()));
}
return convertView;
}
private class ContactFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<Contact> list = contacts;
int count = list.size();
final ArrayList<Contact> nList = new ArrayList<Contact>();
for (int i = 0; i < count; i++) {
if(contacts.get(i).getName().contains(filterString)) nList.add(contacts.get(i));
}
results.values = nList;
results.count = nList.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredContacts = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
}
EDIT: I got rid of if(contentView == null) in getView function and everything works fine
The check for convertView == null should only handle the inflation of your View and the creation of a new ViewHolder the rest of you getView code should always run.
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_contacts, null);
// attach a new holder to the inflated view
holder = new ViewHolder();
convertView.setTag(holder);
} else {
// get an existing holder from the existing view
holder = (ViewHolder) convertView.getTag();
}
// update your holder here:
// e.g. holder.name.setText(contact.getName());
return convertView;
}
I have created an SQLiteDatabase that holds information from user input. The user inputs data about their own recipe for a meal they want to share with others over facebook. This user data is stored and then displayed inside a listview. This works fine for the most part but when the listview is scrolled to observe more entries, a nullpointer occurs. I store 3 types of text information into this database but I only want the listview to display the entryID of the rows and display the rest of the information when the item is clicked.
The error message:
This is the adapter class it refers to:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class RecipeAdapter extends ArrayAdapter {
List list = new ArrayList();
public RecipeAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Recipe object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecipeHolder recipeHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.display_entry_row,parent,false);
recipeHolder = new RecipeHolder();
recipeHolder.tx_id = (TextView)row.findViewById(R.id.t_id);
}
else{
recipeHolder = (RecipeHolder) row.getTag();
}
Recipe recipe = (Recipe)getItem(position);
recipeHolder.tx_id.setText(recipe.getId_entry().toString());
return row;
}
static class RecipeHolder{
TextView tx_id;
}
}
This is the line it is referring to:
recipeHolder.tx_id.setText(recipe.getId_entry().toString());
The Recipe Task with getter and setter:
public class Recipe {
private String id_entry;
public Recipe(String id_entry){
this.setId_entry(id_entry);
}
public String getId_entry() {
return id_entry;
}
public void setId_entry(String id_entry) {
this.id_entry = id_entry;
}
}
And if needed my background task for the database itself:
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String, Recipe, String> {
Context ctx;
RecipeAdapter mRecipeAdapter;
Activity activity;
ListView listView;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseOperations dbOperations = new DatabaseOperations(ctx);
//adds information into database
if (method.equals("add_information")){
String entry = params[1];
String ingred = params [2];
String direc = params [3];
SQLiteDatabase db = dbOperations.getWritableDatabase();
dbOperations.putInformation(db, entry, ingred, direc);
return "One Row Inserted";
}
//gets information from database and places inside listview
else if (method.equals("get_info")){
listView = (ListView) activity.findViewById(R.id.listVrecipe);
SQLiteDatabase db = dbOperations.getReadableDatabase();
Cursor cursor = dbOperations.getInformation(db);
mRecipeAdapter = new RecipeAdapter(ctx,R.layout.display_entry_row);
String entry;
//loops through all row information
while (cursor.moveToNext()){
//grabs entry id
entry = cursor.getString(cursor.getColumnIndex(TableData.TableInfo.EntryID));
Recipe recipe = new Recipe(entry);
publishProgress(recipe);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Recipe... values) {
mRecipeAdapter.add(values[0]);
}
#Override
protected void onPostExecute(String result) {
//after execution update listview with new entries
if(result.equals("get_info")){
listView.setAdapter(mRecipeAdapter);
}
else{
Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
}
}
}
As per your attached image, its states that you are getting NullPointerException at your adapters getView() method.
From my point of view, there are two possibilities.
1. RecipeHolder is null, as you did not set tag to recipeHolder by using row.setTag(recipeHolder).
2. May be Recipe object is null.
When you are using ArrayAdapter, its best practice to use this as below:
Update your RecipeAdapter as below:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class RecipeAdapter extends ArrayAdapter<Recipe> {
public RecipeAdapter(Context context, int resource, ArrayList<Recipe> list) {
super(context, resource, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RecipeHolder recipeHolder;
if(convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.display_entry_row,parent, false);
recipeHolder = new RecipeHolder();
recipeHolder.tx_id = (TextView) convertView.findViewById(R.id.t_id);
convertView.setTag(recipeHolder);
}
else{
recipeHolder = (RecipeHolder) convertView.getTag();
}
Recipe recipe = (Recipe) getItem(position);
recipeHolder.tx_id.setText(recipe.getId_entry().toString());
return row;
}
static class RecipeHolder {
TextView tx_id;
}
}
Update BackgroundTask as below:
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String, Recipe, String> {
Context ctx;
RecipeAdapter mRecipeAdapter;
Activity activity;
ListView listView;
List<Recipe> listRecipe;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
listRecipe = new ArrayList<Recipe>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseOperations dbOperations = new DatabaseOperations(ctx);
//adds information into database
if (method.equals("add_information")){
String entry = params[1];
String ingred = params [2];
String direc = params [3];
SQLiteDatabase db = dbOperations.getWritableDatabase();
dbOperations.putInformation(db, entry, ingred, direc);
return "One Row Inserted";
}
//gets information from database and places inside listview
else if (method.equals("get_info")){
listView = (ListView) activity.findViewById(R.id.listVrecipe);
SQLiteDatabase db = dbOperations.getReadableDatabase();
Cursor cursor = dbOperations.getInformation(db);
// Adapter
mRecipeAdapter = new RecipeAdapter(ctx, R.layout.display_entry_row, listRecipe);
String entry;
//loops through all row information
while (cursor.moveToNext()){
//grabs entry id
entry = cursor.getString(cursor.getColumnIndex(TableData.TableInfo.EntryID));
Recipe recipe = new Recipe(entry);
// Add recipe to list
listRecipe.add(recipe);
mRecipeAdapter.notifyDataSetChanged();
//publishProgress(recipe);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Recipe... values) {
//mRecipeAdapter.add(values[0]);
}
#Override
protected void onPostExecute(String result) {
//after execution update listview with new entries
if(result.equals("get_info")){
listView.setAdapter(mRecipeAdapter);
} else {
Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
}
}
}
Hope this will help~
I am creating an application in which I am parsing data using Json parsing. I've implemented listview and in my response i have totalpage and current page objects,
A new user will get items from the first page. While the user is scrolling through the listview, the list expands with items from the next page (and the next and the next etc.)
this is my response
http://pastie.org/10259792
The following is code I've tried:
HomeFragment
public class HomeFragment extends Fragment {
// Listview Adapter
ListViewAdapter adapters;
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONparserr jsonParser = new JSONparserr();
ArrayList<HashMap<String, String>> WebsiteList;
// albums JSONArray
JSONArray data = null;
String link_url;
ArrayList<HashMap<String, String>> arrayTemplist;
private AutoCompleteTextView inputSearch;
private ListView lv;
private static final String URL_ALBUMS = "";
private static final String WEBSITE_MENU_ID ="Brand_name";
private static final String TAG_MATCH="data";
//private static final String TAG_NAME="Brand_name";
private static final String TAG_PROFILE="id";
private static final String TAG_CAST="Company";
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
lv = (ListView)rootView.findViewById(R.id.listpehlu);
cd = new ConnectionDetector(getActivity());
WebsiteList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
inputSearch = (AutoCompleteTextView)rootView.findViewById(R.id.autoCompleteTextViewhomefrag);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =inputSearch.getText().toString().toLowerCase();
for (int i = 0; i < WebsiteList.size(); i++)
{
String currentString =WebsiteList.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(WebsiteList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
SimpleAdapter adapters = new SimpleAdapter(getActivity(), arrayTemplist,R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapters);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Selected_Product_Listing tf = new Selected_Product_Listing();
Bundle bundle = new Bundle();
bundle.putString("prducts_name", WebsiteList.get(position).get((WEBSITE_MENU_ID)));
// bundle.putString("prducts_name", aList.get(position).get(INTEREST_ACCEPT_NAME));
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
// Toast.makeText(getActivity(),"lets"+ WebsiteList.get(position).get(convertToBase64(convertToBase64(WEBSITE_MENU_ID))), Toast.LENGTH_LONG).show();
}
});
lv.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
}
}
});
return rootView;
}
public String convertToBase64(String text) {
byte[] data = null;
try {
data = text.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Base64.encodeToString(data, Base64.DEFAULT);
}
class LoadAlbums extends AsyncTask<String, String, String> {
private JSONObject jsonObj;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
if (json != null) {
try {
jsonObj = new JSONObject(json);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_MATCH);
String totpage=jsonObj.getString("total_page");
System.out.println("Total Page"+totpage);
String curpage=jsonObj.getString("current_page");
System.out.println("Total Page"+curpage);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(WEBSITE_MENU_ID,c.getString(WEBSITE_MENU_ID));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_CAST, c.getString(TAG_CAST));
WebsiteList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
ListAdapter adapter = new SimpleAdapter(
getActivity(), WebsiteList,
R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapter);
}
}
EndlessAdapter
public class EndLessAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> items;
private int layoutId;
public EndLessAdapter(Context context, List<String> items, int LayoutId) {
super(context,LayoutId,items);
this.context = context;
this.items = items;
this.layoutId = LayoutId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(layoutId,parent,false);
TextView tView = (TextView)convertView.findViewById(R.id.txt);
tView.setText(items.get(position));
return convertView;
}
}
EndlessLisView
public class EndlessListView extends ListView implements OnScrollListener {
private Context context;
private View footer;
private boolean isLoading;
private EndLessListener listener;
private BaseAdapter adapter;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context) {
super(context);
this.setOnScrollListener(this);
this.context = context;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
// 4
public void addNewData() {
this.removeFooterView(footer);
// adapter.addAll(products);
adapter.notifyDataSetChanged();
isLoading = false;
}
public void setLoading()
{
isLoading = false;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
if(getAdapter() == null)
return;
if(getAdapter().getCount() == 0)
return;
int l = visibleItemCount + firstVisibleItem;
System.out.println("List View Total Item Count = "+totalItemCount+" , l = "+l+", is_loading = "+isLoading);
if(l >= totalItemCount && !isLoading){
// add footer layout
this.addFooterView(footer);
// set progress boolean
isLoading = true;
System.out.println("$$$$$$$$$ call loaddata $$$$$$$$$$$");
// call interface method to load new data
listener.loadData();
}
}
// Calling order from MainActivity
// 1
public void setLoadingView(int resId) {
footer = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(resId, null); // footer = (View)inflater.inflate(resId, null);
this.addFooterView(footer);
System.out.println("addfooter ====######");
}
// 2
public void setListener(EndLessListener listener) {
this.listener = listener;
}
// 3
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
this.adapter = adapter;
this.removeFooterView(footer);
}
public void removeFooter(){
this.removeFooterView(footer);
}
}
You can achieve this by using the following library in Github
https://github.com/nicolasjafelle/PagingListView
Simple create your PagingAdapter and add it to com.paging.listview.PagingListView.
You have to implements the new Pagingable interface and its onLoadMoreItems() method. For example:
listView.setHasMoreItems(true);
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
if (pager < 3) {
new CountryAsyncTask(false).execute();
} else {
listView.onFinishLoading(false, null);
}
}
});
Finally you can use the onFinishLoading(boolean hasMoreItems, List newItems) method to update the list.
listView.onFinishLoading(true, newItems);
Also remember to use this package in your layout files:
<com.paging.listview.PagingListView
android:id="#+id/paging_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Hello here you can find the nostra library for lazy loading and then you can
implement the following example for lazzy loading
https://github.com/nostra13/Android-Universal-Image-Loader
you can achieve Lazy loading by using the below
code
Lets start the coding about the lazy loading.
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.sunil.adapter.CustomAdapter;
public class ImageListActivity extends Activity implements OnItemClickListener{
private ListView listview=null;
private String[] imageUrls;
protected ImageLoader imageLoader=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagelist);
listview=(ListView)findViewById(R.id.listView_image);
imageLoader = ImageLoader.getInstance();
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray("stringarrayimage");
CustomAdapter adapter=new CustomAdapter(ImageListActivity.this, imageUrls);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra("imageurlpostion", imageUrls);
intent.putExtra("imagepostion", position);
startActivity(intent);
}
#Override
public void onBackPressed() {
AnimateFirstDisplayListener.displayedImages.clear();
super.onBackPressed();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
imageLoader.clearDiscCache();
return true;
default:
return false;
}
}
}
activity_main.xml
<button android:id="#+id/button_listview" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="ListView ImageLoad">
imagelist.xml
<listview android:id="#+id/listView_image" android:layout_height="match_parent" android:layout_width="match_parent">
</listview>
item_list_row.xml
<imageview android:adjustviewbounds="true" android:contentdescription="#string/descr_image" android:id="#+id/image" android:layout_height="72dip" android:layout_margin="3dip" android:layout_width="72dip" android:scaletype="centerCrop">
<textview android:id="#+id/text" android:layout_gravity="left|center_vertical" android:layout_height="wrap_content" android:layout_marginleft="20dip" android:layout_width="fill_parent" android:textsize="22sp">
For the Example above you need to download the library universal image loader you can download the library ... happy coding :)
you didn't use EndlessListView in your Fragment. As I looked your response, it includes pagination. So, you need to request with page number to use endless scroll.
This is just flow for Endless Listview. If your code still doesn't work, I hope you can learn sample projects after read this messages. I added only parts you need. Thanks
Endless scroll only shows limited data on listview. When user scroll down to bottom, it will get next limited data from server. So you need to add current_page paramater in your request. I don't know exactly your api.
First, you need variable for current_page which initialize with 0
You have to know when to stop. You response has total_page field for that. Save and add validation
Then you need to know when to request next page. For that,you already have codes in onScroll within EndlessListView. That code calculate and tell when user scroll down to bottom and it called
listener.loadData();
to request new data. But you still need to add listener for that. You already have
public void setListener(EndLessListener listener) {
this.listener = listener;
}
You need to create Interface with the name EndlessListener and implements in your fragment. EndlessListener Interface will include loadData() function that request to server. After that you need to add listener for the listview.
endlessListView.setListener(this);
Try Loading data when listview reaches it's end. Implement OnScrollListener in your fragment. Refer this link Android - ListView to load more items when reached end
You MUST use Paging 3 library to resolve all problems in simplest way.
ListView XMl:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/orderlistview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
/>
</LinearLayout>
OrderList class
public class OrderList {
int _orderId;
int _orderincrement_id;
String _orderstatus;
String _orderdate;
String _ordership_to;
String _ordertotal;
String _ordercurrency_symbol;
// Empty constructor
public OrderList() {
}
// constructor
public OrderList(int _orderId, int _orderincrement_id, String _orderstatus,
String _orderdate, String _ordership_to, String _ordertotal,
String _ordercurrency_symbol) {
this._orderId = _orderId;
this._orderincrement_id = _orderincrement_id;
this._orderstatus = _orderstatus;
this._orderdate = _orderdate;
this._ordership_to = _ordership_to;
this._ordertotal = _ordertotal;
this._ordercurrency_symbol = _ordercurrency_symbol;
}
public int get_orderId() {
return _orderId;
}
public void set_orderId(int _orderId) {
this._orderId = _orderId;
}
public int get_orderincrement_id() {
return _orderincrement_id;
}
public void set_orderincrement_id(int _orderincrement_id) {
this._orderincrement_id = _orderincrement_id;
}
public String get_orderstatus() {
return _orderstatus;
}
public void set_orderstatus(String _orderstatus) {
this._orderstatus = _orderstatus;
}
public String get_orderdate() {
return _orderdate;
}
public void set_orderdate(String _orderdate) {
this._orderdate = _orderdate;
}
public String get_ordership_to() {
return _ordership_to;
}
public void set_ordership_to(String _ordership_to) {
this._ordership_to = _ordership_to;
}
public String get_ordertotal() {
return _ordertotal;
}
public void set_ordertotal(String _ordertotal) {
this._ordertotal = _ordertotal;
}
public String get_ordercurrency_symbol() {
return _ordercurrency_symbol;
}
public void set_ordercurrency_symbol(String _ordercurrency_symbol) {
this._ordercurrency_symbol = _ordercurrency_symbol;
}
}
Activity
public class OrderListFragment extends Fragment {
View rootView;
ListView lv;
List<OrderList> list ;
MyListAdapter adt;
DatabaseHandler db ;
ProgressDialog progress;
SharedPreferences pref;
public OrderListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragmentorderlist, container,
false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
if(list.size() == 0){
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data.....");
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String customer_id = pref.getString("customer_id", null);
Log.v("log_tag", "customer_id"+customer_id);
if(customer_id != null){
Log.v("log_tag", "customer_id 2332 ::: "+customer_id);
new FetchOrderListData().execute(customer_id);
}
}
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Bundle bundle = new Bundle();
bundle.putString("orderlist_increment_id", list.get(position).get_orderincrement_id()+"");
Fragment fragment = new OrderdetailFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = OrderListFragment.this
.getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = fragmentManager
.beginTransaction();
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.replace(R.id.Frame_Layout, fragment)
.commit();
}
});
return rootView;
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custom_orderlistdata,
null);
TextView ordernumbertxt = (TextView) convertView
.findViewById(R.id.ordernumberTxt);
TextView orderdate = (TextView) convertView
.findViewById(R.id.orderdateTxt);
TextView orderamount = (TextView) convertView
.findViewById(R.id.orderAmountTxt);
TextView orderSatusTxt = (TextView) convertView
.findViewById(R.id.orderSatusTxt);
ordernumbertxt.setText(Html.fromHtml("<b>Order Number : </b>"+list.get(position).get_orderincrement_id()+""));
orderdate.setText(list.get(position).get_orderdate());
orderSatusTxt.setText(list.get(position).get_orderstatus());
String parts = list.get(position).get_ordertotal();
double d = Double.parseDouble(parts);
double dval = roundTwoDecimals(d);
orderamount.setText(Html.fromHtml("<b>Total : </b>"+list.get(position).get_ordercurrency_symbol()+" "+dval));
return convertView;
}
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
}
private class FetchOrderListData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject listSize = null;
Integer cust_id = Integer.parseInt(args[0]);
try {
listSize = DBAda.getAllOrderListData(cust_id);
////*** call your HTTP Service over here ***////
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listSize;
}
protected void onPostExecute(JSONObject jsonObj) {
db = new DatabaseHandler(getActivity());
if (progress != null) {
progress.hide();
}
if (jsonObj == null) {
return;
}
JSONArray json;
try {
json = jsonObj.getJSONArray("records");
for (int i = 0; i < json.length(); i++) {
JSONObject jobj;
try {
jobj = json.getJSONObject(i);
int order_id = Integer.parseInt(jobj.getString("order_id").toString());
int order_IncrementId = Integer.parseInt(jobj.getString("increment_id").toString());
String orderStatus = jobj.getString("status");
String orderdate = jobj.getString("date");
String ordershipto = jobj.getString("ship_to");
String ordertotal = jobj.getString("order_total");
String ordersymbol = jobj.getString("currency_symbol");
//db.addWishlistItem(new WishList(entity_id,quentity,comment,name,short_description,thumbnails,itemId));
db.addOrderListItem(new OrderList(order_id, order_IncrementId, orderStatus, orderdate, ordershipto, ordertotal, ordersymbol));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
}
}
}
Hello I'm working on an app which has an edittext to search for items on the listview. If the user types a letter in the edittext the listview is getting filtered perfectlty.Have used Adapter also.Now i have following issues:
1)when i m clearing letters edittext my listview is not getting Updated..
2) if i enter wrong letter or letter which does not corrorsponds to any item of a listview the listview is getting clear.
Have gone thorugh exmaples in SO
Android filter listview custom adapter
And googled also for same problem but not getting solved it..Plz anybody help me..
Here is my code:
package com.AAAAA.AAAAA;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.AAAAA.adapter.UpdateSingleItemViewActivity;
import com.AAAAA.adapter.UpdatesAdapterList;
import com.AAAAA.local.database.DBController;
import com.AAAAA.AAAAA.AAAAA.constant.Constant;
import com.AAAAA.AAAAA.AAAAA.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setTextFilterEnabled(true);
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
//adapter.getFilter().filter(arg0);
}
});
}
}
Here is my Adapter:
package com.AAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.AAAA.AAAA.Cardiology_updates;
import com.AAAA.AAAA.R;
import com.AAAA.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String,String>> filterData;
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
//resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
}); return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(data);
}else{
for (HashMap<String,String> row: data) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
Activity opens on cliking listview items:
package com.AAAAA.adapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
public class UpdateSingleItemViewActivity extends Activity {
int position;
String UpdateTile;
String UpdateDescription;
String population;
String UpdateImage;
//String position;
ViewPager viewPager;
PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_update_single_item_view);
Log.e("UpdateSingleItemViewActivity class",
"UpdateSingleItemViewActivity class");
/*
* WebView webview = new WebView(this); setContentView(webview);
*/
Button btnback = (Button) findViewById(R.id.Button01);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
//WebView webview = (WebView) findViewById(R.id.webview);
Intent i = getIntent();
// Get the result of rank
UpdateTile = i.getStringExtra("UpdateTile");
// Get the result of country
UpdateDescription = i.getStringExtra("UpdateDescription");
// Get the result of population
population = i.getStringExtra("population");
// Get the result of flag
UpdateImage = i.getStringExtra("UpdateImage");
//i.putExtra("POSITION_KEY", position);
position = i.getExtras().getInt("position");
//webview.loadData(UpdateDescription, "text/html", null);
viewPager = (ViewPager) findViewById(R.id.viewpager_layout);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(UpdateSingleItemViewActivity.this, Cardiology_updates.FinalLocalDataList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
}
}
its Corrosponding adapter:
package com.AAAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
import com.AAAAA.imageloader.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class ViewPagerAdapter extends PagerAdapter {
String UpdateTile;
String UpdateDescription;
//String population;
String UpdateImage;
String position;
LayoutInflater inflater;
Context context;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
ArrayList<HashMap<String,String>> filterData;
public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
WebView webview;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
//resultp =data.get(position);
webview=(WebView)itemView.findViewById(R.id.webview1);
//webview.setText(webview[position]);
webview.loadData(filterData.get(position).get(Cardiology_updates.UpdateDescription), "text/html", null);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
When used custom adapter always try to implement ViewHolder design pattern for ListView performance and use custom filter function instead Filterable implementation :
Custom filter funcation required two array list one is filterable data list and another one is for orignal data list :
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
Example :
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
public class UpdatesAdapterList extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> filterData;
private ArrayList<HashMap<String,String>> orignalData;
public ImageLoader imageLoader;
public UpdatesAdapterList(Context context,ArrayList<HashMap<String, String>> orignalData) {
this.context = context;
this.orignalData = orignalData;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.orignalData);
imageLoader = new ImageLoader(this.context);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
I want to be able to click on the "username" which will lead me to a new class - SetMed.java. Along with the username, i would like it's ID's to be passed on as well. I have tried using Intent but it does not work. Any help is greatly appreciated.
This is my MainActivity.java
package com.checkbox.main;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ListView_CheckBoxActivity extends Activity {
//Adapter
CheckboxAdapter listItemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Buttons and incident response
Button getValue=(Button)findViewById(R.id.get_value);
getValue.setOnClickListener(listener);
//listview
ListView list = (ListView) findViewById(R.id.list);
//Array list to store the data
ArrayList<HashMap<String, Object>> listData=new ArrayList<HashMap<String,Object>>();
String []name={"Diabetes","example","example","example","example"};
String []id={"Insulin, Glucagon, Prandin","example","example","example","example"};
for(int i=0;i<5;i++)
{
HashMap<String, Object>
map=new HashMap<String, Object>();
map.put("friend_image", R.drawable.icon);
map.put("friend_username", name[i]);
map.put("friend_id", id[i]);
map.put("selected", false);
//Add data
listData.add(map);
}
//Adapter
listItemAdapter = new CheckboxAdapter(this, listData);
list.setAdapter(listItemAdapter);
}
//Incident Response
OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(ListView_CheckBoxActivity.this, SetMed.class);
boolean[] array = new boolean[5];
array[0] = CheckboxAdapter.isChecked();
intent.putExtra("status", array);
HashMap<Integer, Boolean> state =listItemAdapter.state;
String options="Medicine Selected:";
for(int j=0; j<listItemAdapter.getCount(); j++)
{
System.out.println("state.get("+j+")=="+state.get(j));
if(state.get(j)!=null)
{
#SuppressWarnings("unchecked")
HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
String username=map.get("friend_username").toString();
options+="\n"+username;
}
}
//Display selection
startActivity(intent)
}
};
}
This is my CheckBoxAdapter class.
package com.checkbox.main;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
public class CheckboxAdapter extends BaseAdapter {
Context context;
ArrayList<HashMap<String, Object>> listData;
//Record checkbox state
HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
// Constructor
public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData)
{
this.context = context;
this.listData = listData;
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
// Rewrite View
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
LayoutInflater mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.item, null);
ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
image.setBackgroundResource((Integer) listData.get(position).get("friend_image"));
TextView username = (TextView) convertView.findViewById(R.id.friend_username);
username.setText((String) listData.get(position).get("friend_username"));
TextView id = (TextView) convertView.findViewById(R.id.friend_id);
id.setText((String) listData.get(position).get("friend_id"));
CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
state.put(position, isChecked);
} else
{
state.remove(position);
}
}
});
check.setChecked((state.get(position) == null ? false : true));
return convertView;
}
public static boolean isChecked() {
// TODO Auto-generated method stub
return false;
}
Class SetMed
public class SetMed extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_set_med);
TextView diabetes = (TextView) findViewById(R.id.diabetes);
Bundle bundle = this.getIntent().getExtras();
if (bundle.getBoolean("Diabetes", false)) {
diabetes.setText("Diabetes");
} else {
diabetes.setText("");
}
}
}