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.
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 have an array of 3 elements which I try to draw in a listview. The issue is that it only draws the first entry because getView always returns a position = 0.
Why is that? What do I do wrong?
my main java (fragment):
public class PSGlobalFragment extends Fragment {
List<PSGitem> listPSGitem;
ListView list;
PSGadaptater psgAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.psglobal, container, false);
}
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String ip;
listPSGitem = new ArrayList<>();
psgAdapter = new PSGadaptater(getActivity(), listPSGitem);
listPSGitem.clear();
StoreDevDiscovery store = new StoreDevDiscovery();
// this is where I store the data
int count = store.getMax();
for(int i=0;i<count;i++){
ip = store.getIPDiscovery(i);
PSGitem item = new PSGitem();
item.setIp(ip);
listPSGitem.add(item);
list.setAdapter(psgAdapter);
}
}
and my adapter:
public class PSGadaptater extends BaseAdapter {
private int size = 0;
private List<PSGitem> listIp;
private LayoutInflater layoutInflater;
Context context;
public PSGadaptater(Context c, List<PSGitem> objects) {
context = c;
listIp = objects;
layoutInflater = LayoutInflater.from(context);
}
#Override
public void notifyDataSetChanged() {
size = listIp.size();
super.notifyDataSetChanged();
}
#Override
public int getCount() {
return listIp.size();
}
public Object getItem(int position) {
return listIp.get(position);
}
public long getItemId(int position) {
return position;
}
private class ViewIPHolder {
TextView ip_psg;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewIPHolder viewHolder;
if(convertView == null) {
viewHolder = new ViewIPHolder();
convertView = layoutInflater.inflate(R.layout.listview_item_psg, null);
viewHolder.ip_psg = (TextView) convertView.findViewById(R.id.ipaddr_psg);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewIPHolder) convertView.getTag();
}
viewHolder.ip_psg.setText(listIp.get(position).getIpaddr());
// position always = 0 this is my issue
return convertView;
}
}
and the PSCitem.java:
public class PSGitem {
private String ip1;
public String getIp(){
return ip1;
}
public void setIp(String ip){
ip1 = ip;
}
}
The problem is that you are creating your Adapter from an empty set of items:
listPSGitem = new ArrayList<>();
psgAdapter = new PSGadaptater(getActivity(), listPSGitem);
If you wish to add items to the adapter later, you should add the items to the adapter listIp list variable, and then let the adapter know about this change with notifyDataSetChanged() method.
Change your onActivityCreated method like below.
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String ip;
listPSGitem = new ArrayList<>();
listPSGitem.clear();
StoreDevDiscovery store = new StoreDevDiscovery();
// this is where I store the data
int count = store.getMax();
for(int i=0;i<count;i++){
ip = store.getIPDiscovery(i);
PSGitem item = new PSGitem();
item.setIp(ip);
listPSGitem.add(item);
}
psgAdapter = new PSGadaptater(getActivity(), listPSGitem);
list.setAdapter(psgAdapter);
}
I have a project where I can add data,delete them and update them using SQLite. Of course I display them in a listview. The last thing I want to do is a use a searchView object,so the user can search the data he wants and check if they are there. However the SearchView object does nothing. I type on purpose something that exists in the listview and the matched row doesn't appear.
Here is my code.
public class DisplayForldersActivity extends AppCompatActivity {
DatabaseHandler dba;
private ArrayList<MyFolder> dbFolders = new ArrayList<>();
private FolderAdapter folderAdapter;
private ListView listView;
SearchView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_forlders);
listView = (ListView)findViewById(R.id.list);
inputSearch = (SearchView) findViewById(R.id.inputSearch);
fetchDataFromDB();
}
private void fetchDataFromDB() {
dbFolders.clear();
dba = new DatabaseHandler(getApplicationContext());
ArrayList<MyFolder> foldersFromDB = dba.getFolderDetails();
for(int i=0; i<foldersFromDB.size();i++){
String plateNo = foldersFromDB.get(i).getPlateNumber();
String owner = foldersFromDB.get(i).getOwnerName();
String cardId = foldersFromDB.get(i).getCardId();
String content = foldersFromDB.get(i).getContent();
String date = foldersFromDB.get(i).getRecordDate();
int mid = foldersFromDB.get(i).getItemId();
MyFolder f = new MyFolder();
f.setPlateNumber(plateNo);
f.setOwnerName(owner);
f.setCardId(cardId);
f.setContent(content);
f.setRecordDate(date);
f.setItemId(mid);
dbFolders.add(f);
folderAdapter = new FolderAdapter(DisplayForldersActivity.this,R.layout.folders_row,dbFolders);
listView.setAdapter(folderAdapter);
folderAdapter.notifyDataSetChanged();
inputSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
folderAdapter.getFilter().filter(newText);
return false;
}
});
}
dba.close();
}
And my adapter's code
private class FolderAdapter extends ArrayAdapter<MyFolder>{
Activity activity;
int layoutResource;
MyFolder myFolder;
ArrayList<MyFolder> mData = new ArrayList<>();
public FolderAdapter(Activity act, int resource, ArrayList<MyFolder> data) {
super(act, resource,data);
activity = act;
layoutResource = resource;
mData = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public MyFolder getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if(row == null || row.getTag()==null){
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource,null);
holder = new ViewHolder();
holder.mPlateNo = (TextView)row.findViewById(R.id.plateNumberList);
//holder.mOwner = (TextView)row.findViewById(R.id.ownerName);
holder.mcardId = (TextView)row.findViewById(R.id.idNumber);
//holder.mContent = (TextView)row.findViewById(R.id.processing);
holder.mDate = (TextView)row.findViewById(R.id.dateText);
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
holder.myF = getItem(position);
holder.mPlateNo.setText(holder.myF.getPlateNumber());
//holder.mOwner.setText(holder.myF.getOwnerName());
//holder.mcardId.setText(holder.myF.getCardId());
//holder.mPlateNo.setText(holder.myF.getPlateNumber());
holder.mDate.setText(holder.myF.getRecordDate());
final ViewHolder finalHolder = holder;
holder.mPlateNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String dateText = finalHolder.myF.getRecordDate().toString();
String owner = finalHolder.myF.getOwnerName().toString();
String cardId = finalHolder.myF.getCardId().toString();
String plateNumber = finalHolder.myF.getCardId().toString();
String content = finalHolder.myF.getContent().toString();
int mid = finalHolder.myF.getItemId();
Intent i = new Intent(DisplayForldersActivity.this,DetailedFolderActivity.class);
i.putExtra("id",mid);
i.putExtra("owner",owner);
i.putExtra("cardId",cardId);
i.putExtra("plateNumber",plateNumber);
i.putExtra("content",content);
i.putExtra("dateText",dateText);
startActivity(i);
}
});
return row;
}
class ViewHolder{
MyFolder myF;
int mid;
TextView mPlateNo;
TextView mOwner;
TextView mcardId;
TextView mContent;
TextView mDate;
}
}
Did I do something wrong? Thanks
You need to call notifyDataSetChanged in the adapter attached to the listView to invalidate the ListView and make it draw the changed/removed/inserted lines.
Your array adapter needs to implement Filterable interface, which will override getFilter() method. Then in your getFilter() method you can perform your filtering opertion.
Check out this stackoverflow link, this code might help you out
No results with custom ArrayAdapter Filter
The SerchView doesn't handle any search, it is just a widget. You have to implement the search logic by your own. Try the solution described here:
http://developer.android.com/guide/topics/search/search-dialog.html
You can also do this by calling SearchView.setOnQueryTextListener(SearchView.OnQueryTextListener listener) and pass in a custom implementation of the listener.
I am currently modifying an android app that I need to add a listview to an existing fragment. As I am new to android, I am just imitating the code from the apps. I created a new arrayadapter, a new class of data and made some modifies to the existing fragment class. The problem is I cannot see my list in the app. Below are my codes.
Adapter
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRec;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRec)
{
super(context, resourceId, checkInRec);
this.resourceId = resourceId;
this.context = context;
this.checkInRec = checkInRec;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_name);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkindate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_points);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
CheckInRecord.CheckInRec checkInrec = checkInRec.get(position);
textViewName.setText(checkInrec.providerName);
textViewCheckInDate.setText(checkInrec.checkInDate);
textViewPoints.setText(checkInrec.providerPoints);
ImageLoader.getInstance().displayImage(checkInrec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRec.get(position).isPrize);}
}
Data type
public class CheckInRecord {
public int userPoints;
public String userName;
public String gender;
public String birthDate;
public String location;
public String userIcon;
public List<CheckInRec> checkInRecList = new ArrayList<CheckInRec>();
public void addCheckInRec(String providerName, String providerLocation, String providerIcon,
String checkInDate, int providerPoints, int isPrize){
CheckInRec checkInRec = new CheckInRec();
checkInRec.providerName = providerName;
checkInRec.providerLocation = providerLocation;
checkInRec.providerIcon = providerIcon;
checkInRec.checkInDate = checkInDate;
checkInRec.providerPoints = providerPoints;
checkInRec.isPrize = isPrize;
checkInRecList.add(checkInRec);
}
public List<String> recImages(){
List<String> resultList = new ArrayList<String>();
if (this.checkInRecList == null){
return resultList;
}
for (CheckInRec rec : this.checkInRecList){
resultList.add(rec.providerIcon);
}
return resultList;
}
public class CheckInRec{
public String providerName;
public String providerLocation;
public String providerIcon;
public String checkInDate;
public int providerPoints;
public int isPrize;
}
}
Fragment
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRec = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppDataManager.getInstance().setAllowCheckIn(true);
progressDialog = ProgressDialog.show(getActivity(), "", "");
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) view.findViewById(R.id.tv_name);
textViewPoints = (TextView) view.findViewById(R.id.tv_points);
ListView listViewCheckInRec = (ListView) view.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity().getApplicationContext(), R.layout.row_record, checkInRec);
listViewCheckInRec.setAdapter(recordArrayAdapter);
return view;
}
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
refreshName();
}
}
public void refreshName() {
progressDialog = ProgressDialog.show(getActivity(), "", "");
AppDataManager dataManager = AppDataManager.getInstance();
ApiManager.getInstance().checkInHistories(dataManager.getUserToken(), dataManager.getUserPhone(), Utility.getPictureSize(), this);
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
// this.checkInRec.clear();
// this.checkInRec.addAll(checkInRecord.checkInRecList);
//
// recordArrayAdapter.notifyDataSetChanged();
}
}
}
The problem is I cannot see my list in the app.
That is because checkInRec does now have any elements inside of it.
I can really tell that it is empty because you commented this out:
// this.checkInRec.clear(); //clear the old data from the list
// this.checkInRec.addAll(checkInRecord.checkInRecList); //add all the data inside the checkInRecord.checkInRecList
//
// recordArrayAdapter.notifyDataSetChanged(); //refreshing the ListView to display the new data
now what are those doing is that clearing the old list array and adding the new set of data from checkInRecord.checkInRecList and refreshing the ListView so those new data are implemented/shown in your ListView.
The following is my Json data from database, i want to list the interest_name in a list(only if visible is true). List must be multilevel. I parsed the json file using Gson library. But i have no idea regarding how to make a multilevel list using listview.
{"interest_id":0,"interest_name":"ROOT","visible":false,"children":
[{"interest_id":1,"interest_name":"Sports","visible":true,"children":[{"interest_id":2,"interest_name":"Archery","visible":true,"children":[]},{"interest_id":3,"interest_name":"Bow Hunting","visible":true,"children":[]}]},{"interest_id":100,"interest_name":"Contry","visible":true,"children":[{"interest_id":101,"interest_name":"Afghanistan","visible":true,"children":[]},{"interest_id":102,"interest_name":"Akrotiri","visible":true,"children":[]}]},{"interest_id":1000,"interest_name":"Education","visible":true,"children":[]},{"interest_id":1200,"interest_name":"Entertainment","visible":true,"children":[]},{"interest_id":1400,"interest_name":"Books","visible":true,"children":[]},{"interest_id":1600,"interest_name":"Services","visible":true,"children":[]},{"interest_id":1800,"interest_name":"Fitness","visible":true,"children":[]},{"interest_id":2000,"interest_name":"Fashion","visible":true,"children":[]},{"interest_id":99999,"interest_name":"Near Me","visible":false,"children":[]}]}
My code:
Home.java
Intent intent = new Intent( Home.this,InterestAddList.class);
startActivity(intent);
finish();
InterestAddList.java
public class InterestAddList extends Activity {
ListView intrestListView;
OneOnOneListAdapter adapter;
List<String> intrestList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intrest_add);
intrestListView = (ListView) findViewById(R.id.InterestList);
//Service Called For retrieving Data
retrieveList();
}
public void retrieveList() {
intrestList = new ArrayList<String>();
StringBuilder urlc = new StringBuilder(urlPrefix + "gai");
String url=urlc.toString();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String result = ServiceClient.getInstance().getResponse(url);
InterestNode ni=gson.fromJson(result, InterestNode.class);
//for(int i=0;i<ni.length;i++){
//Log.e("ni", ni.getInterestName());
//Log.e("ni", String.valueOf(ni.getInterestId()));
/* how to display interest name */
intrestList.add(ni.getInterestName());
}
adapter = new OneOnOneListAdapter(InterestAddList.this,R.layout.intrest_add_row,intrestList);
intrestListView.setAdapter(adapter);
}
private class OneOnOneListAdapter extends ArrayAdapter {
public OneOnOneListAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final int aposition=position;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.intrest_add_row, null);
}
TextView intrestText =(TextView)v.findViewById(R.id.IntrestText);
intrestText.setText(intrestList.get(aposition).toString());
v.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
System.out.println("OnItem CLicked");
Toast.makeText(InterestAddList.this,"Position clicked:"+intrestList.get(aposition).toString(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(InterestAddList.this,SubIntrestAddList.class);
i.putExtra("position", aposition);
startActivityForResult(i,1);
}
});
return v;
}
}}
InterestNode.java
public class InterestNode {
#SerializedName("interest_id")
int interestId;
#SerializedName("interest_name")
String interestName;
#SerializedName("visible")
boolean isVisible;
transient InterestNode parent;
#SerializedName("children")
List<InterestNode> childList = new ArrayList<InterestNode>();
public List<InterestNode> getChildren(){
return new ArrayList<InterestNode>(childList);
}
public int getInterestId() {
return interestId;
}
public String getInterestName() {
return interestName;
}
public InterestNode getParent() {
return parent;
}
public boolean isVisible() {
return isVisible;
}
public void addChild(InterestNode intNode){
childList.add(intNode);
}
public void setInterestId(int interestId) {
this.interestId = interestId;
}
public void setInterestName(String interestName) {
this.interestName = interestName;
}
public void setParent(InterestNode parent) {
this.parent = parent;
}
public void setVisible(boolean isVisible) {
this.isVisible = isVisible;
}
}
It better to use Expandable ListView to add multilevel list, instead. But you want using listview then follow below nice tutorial here step by step three level listiview is achieved.
Android Multilevel ListView Tutorial
hope it helps you!