I'm trying to get data using retrofit2 and display those data using a list passing through as a parameter of Custom adapter. When I store data in a List in onResponse() method, in onResponse() method list have some value. But in oncreate() method its give me null. Though, I declared List as global. When I run the app sometimes its display nothing and sometimes app get crash. I know it's sounds like crazy. But it's happen. so, I want to know, what's wrong with my Code? how can I display data in listview?
Forgive me if something wrong with my question pattern yet this my maiden question at this site.
MainActivity`
public class LaboratoryValues extends AppCompatActivity {
public List<Data> productList = null;
List<Data>arrayList = null;
int size;
String st;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_laboratory_values);
//productList = new ArrayList<Data>();
getInvestigation();
for(int i =0; i < size; i++){
st = arrayList.get(i).getName();
}
System.out.println("Name : "+st);//here print Name : null
ListView lview = (ListView) findViewById(R.id.listview);
ListviewAdapter adapter = new ListviewAdapter(this, arrayList);
lview.setAdapter(adapter);
}
private void getInvestigation() {
/* final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false); // set cancelable to false
progressDialog.setMessage("Please Wait"); // set body
progressDialog.show(); // show progress dialog*/
ApiInterface apiService =
Api.getClient(ApiInterface.BASE_URL).create(ApiInterface.class);
Call<Investigation> investigationCall = apiService.getInvestigation();
investigationCall.enqueue(new Callback<Investigation>() {
#Override
public void onResponse(Call<Investigation> call, Response<Investigation> response) {
arrayList = response.body().getData();
//productList.addAll(arrayList);
size = response.body().getData().size();
for (int i = 0; i < size; i++) {
System.out.println("Name : " + arrayList.get(i).getName());//here printing Name is ok
}
}
#Override
public void onFailure(Call<Investigation> call, Throwable t) {
Toast.makeText(getApplicationContext(),"data list is empty",Toast.LENGTH_LONG).show();
}
});
}
}
Custom Adapter (listviewAdapter)
public class ListviewAdapter extends BaseAdapter {
public List<Data> productList;
Activity activity;
//Context mContext;
public ListviewAdapter(Activity activity, List<Data> productList) {
super();
this.activity = activity;
this.productList = productList;
}
#Override
public int getCount() {
return productList.size();
}
#Override
public Object getItem(int position) {
return productList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView name;
TextView normal_finding;
TextView increased;
TextView decreased;
TextView others;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
holder = new ViewHolder();
holder.name = convertView.findViewById(R.id.name);
holder.normal_finding =convertView.findViewById(R.id.normal_finding);
holder.increased = convertView.findViewById(R.id.increased);
holder.decreased = convertView.findViewById(R.id.decreased);
holder.others =convertView.findViewById(R.id.others);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Data item = productList.get(position) ;
holder.name.setText(item.getName());
System.out.println("holderName : "+item.getName() );
holder.normal_finding.setText(item.getNormal_finding());
System.out.println("holderName : "+item.getNormal_finding() );
holder.increased.setText(item.getIncreased());
holder.decreased.setText(item.getDecreased());
holder.others.setText(item.getOthers());
return convertView;
}
}
It's perfectly normal that it dosent work.
putting your method getInvistigation() before the loop does not mean that the response of your request was done
Calling a webservice creates another thread that waits for the server to send the response, sometimes the response takes time depends from the server and the latency of your internet connection.
you simply need to place the treatment (the loop and adapter) inside getInvistagion after getting the data.
Related
Im new in realm db. I completed add and get data in realm db. But, I couldn't sort(ascending and descending).Im my code it display items in listview. Listview contains 5 list and each list contains 4 field(name, age, skill and date). if I sort(ascending) name, need to ascending in 5 list.My code is not work
I post my code here,
private void Ascending_order() {
realm.beginTransaction();
RealmResults<Employee> result = realm.where(Employee.class)
.sort("name", Sort.ASCENDING).findAll();
realm.copyFromRealm(result);
realm.commitTransaction();
employeedetailadapter.notifyDataSetChanged();
}
Adapter class:
public class EmployeeDetailAdapter extends BaseAdapter {
private ArrayList<Employee>employeeDetaillists = new ArrayList<>();
private Context c;
private LayoutInflater inflater;
private OnItemClick mCallback;
private SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy");
public EmployeeDetailAdapter(Context c,ArrayList<Employee> employeeDetaillists, OnItemClick listener) {
this.employeeDetaillists = employeeDetaillists;
this.c= c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mCallback = listener;
}
#Override
public int getCount() {
return employeeDetaillists.size();
}
#Override
public Object getItem(int position) {
return employeeDetaillists.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
Holder holder;
if (v==null){
v= (View) inflater.inflate(R.layout.list_single_item,null);
holder = new Holder();
holder.tvPersonName = (TextView) v.findViewById(R.id.tvPersonName);
holder.tvPersonAge = (TextView) v.findViewById(R.id.tvPersonAge);
holder.tvPersonSkill = (TextView) v.findViewById(R.id.tvPersonSkill);
holder.ivEditPesonDetail=(ImageView)v.findViewById(R.id.ivEditPesonDetail);
holder.tvPersondate=(TextView)v.findViewById(R.id.tvPersondate);
holder.ivDeletePerson=(ImageView)v.findViewById(R.id.ivDeletePerson);
v.setTag(holder);
}else{
holder = (Holder) v.getTag();
}
holder.tvPersonName.setText(employeeDetaillists.get(position).getName());
holder.tvPersonAge.setText(employeeDetaillists.get(position).getAge());
holder.tvPersonSkill.setText(employeeDetaillists.get(position).getSkill());
String strDate = df.format(employeeDetaillists.get(position).getSdate());
holder.tvPersondate.setText(strDate);
holder.ivDeletePerson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Delete(employeeDetaillists.get(position).getName(),position);
}
});
return v;
}
private void Delete(String name, int position) {
mCallback.onClickdelete(name, position);
}
public void updateData(RealmResults<Employee> result) {
}
class Holder {
TextView tvPersonName, tvPersonAge, tvPersonSkill,tvPersondate;
ImageView ivDeletePerson, ivEditPesonDetail;
}
}
Your code does't change db. You just get sorted items but don't use them.
realm.copyFromRealm(result); // this line does nothing
realm.commitTransaction(); // this one too, because you change nothing
employeedetailadapter.notifyDataSetChanged(); // you data is the same, so this line also useless here
To see your data sorted you should use RealmResults in your adapter. With this approach your list always will sorted, even after adding new items. But note: your adapter should extends RealmRecyclerViewAdapter.
You should run this code before creating adapter and use result inside adapter:
RealmResults<Employee> result = realm.where(Employee.class)
.sort("name", Sort.ASCENDING).findAll();
Also you can try manually update data of your adapter.
private void Ascending_order() {
RealmResults<Employee> result = realm.where(Employee.class)
.sort("name", Sort.ASCENDING).findAll();
employeedetailadapter.updateData(result); // update data inside adapter before calling `notifyDataSetChanged`
employeedetailadapter.notifyDataSetChanged();
}
You need to create updateData method yourself:
public void updateData(RealmResults<Employee> result) {
employeeDetaillists = new ArrayList<Employee>(result);
}
First of all, while getting data from Realm you don't need to write it in Transaction. Write Transaction is required only when you are adding data in realm or updating any realm object.
And about your problem, To get sorted data from realm, You can do it like this
RealmResults<Employee> result = realm.where(Employee.class).sort("name", Sort.ASCENDING).findAll();
Now the data you got is sorted, If you still see wrong order in your ListView then there could be some issue in your Adapter. If you share your adapter code, then I can help further :)
Updated:
Adapter Class
public class EmployeeDetailAdapter extends BaseAdapter {
private RealmResults<Employee> employeeDetaillists;
private Context c;
private LayoutInflater inflater;
private OnItemClick mCallback;
private SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy");
public EmployeeDetailAdapter(Context c,RealmResults<Employee> employeeDetaillists, OnItemClick listener) {
this.employeeDetaillists = employeeDetaillists;
this.c= c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mCallback = listener;
}
#Override
public int getCount() {
return employeeDetaillists.size();
}
#Override
public Object getItem(int position) {
return employeeDetaillists.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
Holder holder;
if (v==null){
v= (View) inflater.inflate(R.layout.list_single_item,null);
holder = new Holder();
holder.tvPersonName = (TextView) v.findViewById(R.id.tvPersonName);
holder.tvPersonAge = (TextView) v.findViewById(R.id.tvPersonAge);
holder.tvPersonSkill = (TextView) v.findViewById(R.id.tvPersonSkill);
holder.ivEditPesonDetail=(ImageView)v.findViewById(R.id.ivEditPesonDetail);
holder.tvPersondate=(TextView)v.findViewById(R.id.tvPersondate);
holder.ivDeletePerson=(ImageView)v.findViewById(R.id.ivDeletePerson);
v.setTag(holder);
}else{
holder = (Holder) v.getTag();
}
holder.tvPersonName.setText(employeeDetaillists.get(position).getName());
holder.tvPersonAge.setText(employeeDetaillists.get(position).getAge());
holder.tvPersonSkill.setText(employeeDetaillists.get(position).getSkill());
String strDate = df.format(employeeDetaillists.get(position).getSdate());
holder.tvPersondate.setText(strDate);
holder.ivDeletePerson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Delete(employeeDetaillists.get(position).getName(),position);
}
});
return v;
}
private void Delete(String name, int position) {
mCallback.onClickdelete(name, position);
}
public void updateData(RealmResults<Employee> result) {
}
class Holder {
TextView tvPersonName, tvPersonAge, tvPersonSkill,tvPersondate;
ImageView ivDeletePerson, ivEditPesonDetail;
}
}
In your Activity please change following function
private void Ascending_order() {
result = realm.where(Employee.class)
.sort("name", Sort.ASCENDING).findAll();
employeedetailadapter.notifyDataSetChanged();
}
"result" list should be declared on class level and should be passed to Adapter's constructor as well.
Like
class Activity {
RealmResults<Employee> result;
EmployeeDetailAdapter employeedetailadapter;
//// Other Code
public onCreate(Bundle b) {
result = realm.where(Employee.class).findAll();
employeedetailadapter = new EmployeeDetailAdapter(this, result, listener);
// Other code
}
}
I'm using view pager with swiping tab layouts. And i'm displaying list view of data using custom adapter. And also onclick of list view i have a list view detail activity where I'm displaying data in more detail. In these detail activity i'm performing some changes to the data(some post method). after that I create an instance of customAdapter class and call notifyDataSetChanged() in order to refresh list view. My problem over here is the list view some times refreshes quickly and some times there is a delay of some seconds.
So, Can somebody suggest me proper usage of list view and what changes needs to be done in order to refresh list view whenever a post method is performed.
My code Fragment class:
private void showJsonData(String response) {
try {
String serviceID = LoggedInUserStore.getLoggedInServiceId(getContext());
List<Complaint> userList = new ArrayList<>(); //ArrayList of type user(POJO CLASS)
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
if (serviceID.equals(jsonArray.getJSONObject(i).getString("ServiceID"))) {
if (jsonArray.getJSONObject(i).getString("CallStatusID").equalsIgnoreCase("1")) {
userList.add(0, Complaint.fromJson(jsonArray.getJSONObject(i))); //
}
}
}
assignAdapter = new AssignAdapter(getActivity(), userList);
listView.setAdapter(assignAdapter);
listView.invalidateViews();
assignAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
My custom adapter class
public class AssignAdapter extends BaseAdapter implements Filterable {
List<Complaint> ticket = new ArrayList<>();
private Context context;
String ticketNo, complaint, raiseDate;
Complaint user;
List<Complaint> temporaryList = new ArrayList<>();
/*String status, priority;*/
public AssignAdapter(Context context, List<Complaint> ticket) {
this.context = context;
this.ticket = ticket;
this.temporaryList = ticket;
}
#Override
public int getCount() {
return temporaryList.size();
}
#Override
public Object getItem(int position) {
return temporaryList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class viewHolderItem {
TextView ticketNumberText, complaintNameText, raisedDateText;
}
//Set the layout for the fragment and return it.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolderItem holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_list_view, null, true);
holder = new viewHolderItem();
holder.ticketNumberText = (TextView) convertView.findViewById(R.id.ticketIdSupervisor);
holder.complaintNameText = (TextView) convertView.findViewById(R.id.complaintNameSupervisor);
convertView.setTag(holder);
} else {
holder = (viewHolderItem) convertView.getTag();
}
user = temporaryList.get(position);
if (user != null) {
//Get the Ticket Number
Typeface custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSerif.ttf");
ticketNo = temporaryList.get(position).getTicketNumber();
holder.ticketNumberText.setText(ticketNo);
holder.ticketNumberText.setTag("ticketNumber");
holder.ticketNumberText.setTypeface(custom_font);
//Get the complaint Name
complaint = temporaryList.get(position).getComplaintDetails();
holder.complaintNameText.setText(complaint);
holder.complaintNameText.setTag("complaint");
holder.complaintNameText.setTypeface(custom_font);
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context.getApplicationContext(), ComplaintDetailsSupervisor.class);
i.putExtra("COMPLAINT NAME", temporaryList.get(position).getComplaintDetails());
i.putExtra("RAISED DATE", temporaryList.get(position).getRaisedDate().substring(0, 10));
context.startActivity(i);
}
});
notifyDataSetChanged();
return convertView;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
My List view detail activity class
dialogButtonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
assignComplaint();
al.remove(position);
AssignAdapter assignAdapter = new AssignAdapter(getApplicationContext(), al);
assignAdapter.notifyDataSetChanged();
ComplaintDetailsSupervisor.this.finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
dialogButtonNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
});
}
public void assignComplaint() throws JSONException {
//my custom method...
}
In the list view detail activity class i'm doing this
al.remove(position);
AssignAdapter assignAdapter = new AssignAdapter(getApplicationContext(), al);
assignAdapter.notifyDataSetChanged();
ComplaintDetailsSupervisor.this.finish();
Removing the position of list view and immediately calling adapter. This works fine but I don't know why sometimes it does not refreshes..May be when list view has a single item it does not refreshes immediately.
You are creating a new adapter and calling notifyDatasetChanged on it but have not called setAdapter with the new adapter as a parameter, hence why your list ist not refreshed.
You need to call
setAdapter(assignAdapter)
or reuse your existing assignAdapter and then call notifyDatasetChanged() on it.
Am trying to update my listview on every selection of the spinner. but its not working. Instead of getting new data, listview is repeating the same values.
I am unable to find out what is my mistake.
here is my avtivity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.activity_performance_details);
PerfList = new ArrayList<PerformanceListItem>();
months = (Spinner) findViewById(R.id.load_month);
listview_performance = (ListView) findViewById(R.id.performance_details_list);
sadapter = new PerformanceAdapter(PerformanceDetails.this, PerfList);
months.setOnItemSelectedListener(this);
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner a=(Spinner)parent;
if(a.getId() == R.id.load_month) {
monthid =1+(int)months.getSelectedItemPosition();
Toast.makeText(getApplicationContext(),""+monthid,Toast.LENGTH_LONG).show();
new setAsyncTask_performance().execute();
}
}
after selecting spinner data it is sent to server and from server its relevant data is fetched and sent back to the list view. now when i first time select the spinner it show the data accordingly. But on second selection it will include the previous data without updating the listview
Adapter Code:
public class PerformanceAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private Context context;
private List<PerformanceListItem> performanceList;
public PerformanceAdapter(Activity activity, List<PerformanceListItem> PList) {
this.activity = activity;
this.performanceList = PList;
}
#Override
public int getCount() {
return performanceList.size();
}
#Override
public Object getItem(int position) {
return performanceList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.performance_itemlist, null);
}
Animation slideUp = AnimationUtils.loadAnimation(activity, R.anim.slide_up);
TextView staffName = (TextView) convertView.findViewById(R.id.perf_staffName);
TextView staffDesignation = (TextView) convertView.findViewById(R.id.perf_Design);
TextView staffPerformance = (TextView) convertView.findViewById(R.id.perf_performance);
PerformanceListItem plist = performanceList.get(position);
staffName.setText(plist.getpStaffName());
staffDesignation.setText(plist.getpDesignation());
staffPerformance.setText(plist.getpPerformance());
slideUp.setDuration(500);
convertView.startAnimation(slideUp);
slideUp = null;
return convertView;
}
}
and this is my performance list to get and set data
PerformanceListItems code:
public class PerformanceListItem {
private String pSid;
private String pStaffName;
private String pDesignation;
private String pPerformance;
private String pList;
public PerformanceListItem(){
}
public PerformanceListItem(String pList){
this.pList = pList;
}
public String getpSid(){
return pSid;
}
public void setpSid(String pSid){
this.pSid = pSid;
}
public String getpStaffName(){
return pStaffName;
}
public void setpStaffName(String pStaffName){
this.pStaffName = pStaffName;
}
public String getpDesignation(){
return pDesignation;
}
public void setpDesignation(String pDesignation){
this.pDesignation = pDesignation;
}
public String getpPerformance(){
return pPerformance;
}
public void setpPerformance(String pPerformance){
this.pPerformance = pPerformance;
}
}
After debugging the entire code i found that my JSONObject is not updating with new value
any help would be appreciable.
Update the data of your adapter when you execute this
new setAsyncTask_performance().execute();
If you want to show only the new data just remove all your listview items then update the data and set the adapter again.
dont set adapter in oncreate. Set your adapter in Asynctask Post execute. and set your array inside doinbackground along with getting data task.
I'm using ListView that retrieves data from external URL with JSON.
When I run my app, it shows only maximum of 10 results since my api query returns maximum of 10 results PER page.
What i'm trying to do is, that when the user scrolls down to the end of this 10 results, it will load more results (one by one would be even greater) from my JSON external URL (API).
This is how I'm using my ListView & JSONAdapter:
TabFragment1.java
ListView mainListView = (ListView) v.findViewById(R.id.main_listview);
mJSONAdapter = new JSONAdapter(getActivity(), inflater);
mainListView.setAdapter(mJSONAdapter);
getUpdates();
getUpdates()
private void queryUpdates(double lat, double lon, int distance) {
// Create a client to perform networking
AsyncHttpClient client = new AsyncHttpClient();
// Show ProgressBar to inform user that a task in the background is occurring
mProgress.setVisibility(View.VISIBLE);
// Have the client get a JSONArray of data
// and define how to respond
client.get(API_URL + "?lat=" + lat + "&lon=" + lon + "&distance=" + distance,
new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject jsonObject) {
// 11. Dismiss the ProgressDialog
mProgress.setVisibility(View.GONE);
// update the data in your custom method.
mJSONAdapter.updateData(jsonObject.optJSONArray("docs"));
}
#Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
// 11. Dismiss the ProgressDialog
mProgress.setVisibility(View.GONE);
getActivity().setContentView(R.layout.bad_connection);
}
});
}
My JSONAdapter.java
public class JSONAdapter extends BaseAdapter implements StickyListHeadersAdapter {
Context mContext;
LayoutInflater mInflater;
JSONArray mJsonArray;
public JSONAdapter(Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
mJsonArray = new JSONArray();
}
#Override
public int getCount() {
return mJsonArray.length();
}
#Override
public Object getItem(int position) {
return mJsonArray.optJSONObject(position);
}
#Override
public long getItemId(int position) {
// your particular dataset uses String IDs
// but you have to put something in this method
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// check if the view already exists
// if so, no need to inflate and findViewById again!
if (convertView == null) {
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.row_place_update, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.myImageView = (ImageView) convertView.findViewById(R.id.myImage);
holder.myTextView = (TextView) convertView.findViewById(R.id.myText);
// hang onto this holder for future recyclage
convertView.setTag(holder);
} else {
// skip all the expensive inflation/findViewById
// and just get the holder you already made
holder = (ViewHolder) convertView.getTag();
}
// More code after this
// Get the current book's data in JSON form
JSONObject jsonObject = (JSONObject) getItem(position);
// Grab the title and author from the JSON
if (jsonObject != null) {
//Get from JSON
String myImage = jsonObject.optString("myImage");
String myText = jsonObject.optString("myText");
//Replace Them
Picasso.with(mContext).load(myImage).placeholder(R.drawable.loading).into(holder.myImageView);
holder.myTextView.setText(myText);
}
return convertView;
}
// this is used so you only ever have to do
// inflation and finding by ID once ever per View
private static class ViewHolder {
public ImageView myImageView;
public TextView myTextView;
}
public void updateData(JSONArray jsonArray) {
// update the adapter's dataset
mJsonArray = jsonArray;
notifyDataSetChanged();
}
}
how I can show more results by adding &page=2, &page=3 to the API_URL and load these results in my ListVIew, in addition to the old results?
I'm using ListView to show search results. I have a Coustomized arrayListAdapter which returns a list of Objects. This is working fine. My listView is showing just a TextView nothing else.
But I want to clear the List when I again go to the search page. I have tried
#Override
protected void onResume()
{
mListAdapter.clear();
mListAdapter.notifyDataSetChanged();
super.onResume();
}
And the SearchListAdapter
public class SearchListAdapter extends ArrayAdapter<Chapter>
{
public Context context;
private static String searchText = null;
public SearchListAdapter(Context context)
{
super(context, R.layout.favorite_tab_list_view_row);
this.context = context;
}
#Override
public void clear()
{
for (int i = 0; i < getCount(); i++)
getSearchChapters().remove(i);
notifyDataSetChanged();
super.clear();
}
private ArrayList<Chapter> getSearchChapters()
{
ArrayList<Chapter> chapter = new ArrayList<Chapter>();
if (searchText != null)
for (int i = 0; i < DataStore.getHierarchicalChapters()
.getSubChapters().size(); i++)
{
String str = DataStore.getHierarchicalChapters()
.getSubChapters().get(i).getChapterContent()
.toLowerCase();
Pattern pat = Pattern.compile(searchText.toLowerCase());
Matcher mat = pat.matcher(str);
while (mat.find())
{mat.start()); //
chapter.add(DataStore.getHierarchicalChapters()
.getSubChapters().get(i)); // the
break;
// occurrance
}
if (DataStore.getHierarchicalChapters().getSubChapters().get(i)
.hasSubchapters())
{
for (int j = 0; j < DataStore.getHierarchicalChapters()
.getSubChapters().get(i).getSubChapters().size(); j++)
{
str = DataStore.getHierarchicalChapters()
.getSubChapters().get(i).getSubChapters()
.get(j).getChapterContent();
mat = pat.matcher(str);
while (mat.find())
{
chapter.add(DataStore.getHierarchicalChapters()
.getSubChapters().get(i).getSubChapters()
.get(j));
break;
}
}
}
}
return chapter;
}
#Override
public int getCount()
{
return getSearchChapters().size();
}
#Override
public Chapter getItem(int position)
{
return getSearchChapters().get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.favorite_tab_list_view_row, parent,
false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.chapterName = (TextView) row
.findViewById(R.id.favoriteChapterTextViewId);
row.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) row.getTag();
viewHolder.chapterName.setText(getSearchChapters().get(position)
.getTitle());
return row;
}
static class ViewHolder
{
public TextView chapterName;
}
public static void setSearchText(String searchText)
{
SearchListAdapter.searchText = searchText;
}
}
My question is, How can I clear the list ?
Thank You.
I think you have to override the method clear() for your custom ArrayAdapter and manually empty the list of objects on which your adapter is based(and don't forget to call notifyDataSetChanged()). This is what the default ArrayAdapter is doing.
EDIT :
Your code will never work now because your custom adapter gets its data from calling the method private ArrayList<Chapter> getSearchChapters() which rebuilds the adapter's data every time the method is called(for example every time the adapter calls getView() it will rebuild the data). My advice is to make a private field in your adapter :
ArrayList<Chapter> data;
and then in your adapter's constructor initialize it by calling the method getSearchChapters() :
data = getSearchChapters();
Then you can override the method clear():
#Override
public void clear() {
data.clear();
notifyDataSetChanged();
super.clear();
}
Also you can't call clear from onResume() because your list will never get populated with data(the adapter will be empty). I didn't understand when you want to clear the list so i can't tell you when to call the adapter.clear(). You can make a test with a button that calls clear() to see if this clears the adapter.
Clear the ArrayList that the Adapter is using then call notifyDataSetChanged() on Adapter