First here is my json.
[{"MemberId":"MI001","MemberName":"Member 1"},
{"MemberId":"MI002","MemberName":"Member 2"},
{"MemberId":"MI003","MemberName":"Member 3"}]
here how i put my json to my adapter
#Override
public void onResponse(JSONArray response) {
try {
Model_member m_member = new Model_member();
List<String> list = new ArrayList<String>();
for(int i = 0; i < response.length(); i++){
m_member.setMember_id(response.getJSONObject(i).getString("MemberId"));
m_member.setMember_name(response.getJSONObject(i).getString("MemberName"));
Log.d("ASDF", response.getJSONObject(i).getString("MemberName"));
memberList.add(m_member);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
and here is my adapter.
public class Adapter_member extends ArrayAdapter{
private ArrayList<Model_member> mData;
public Adapter_member(Context context, ArrayList<Model_member> m_member) {
super(context, 0, m_member);
this.mData = m_member;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.single_member_layout, parent, false);
}
Model_member m_member = getItem(position);
TextView memberName = convertView.findViewById(R.id.membername);
memberName.setText(m_member.getMember_name());
return convertView;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Model_member getItem(int position) {
return mData.get(position);
}
}
and here is my pojo
public class Model_member {
String member_id,member_name;
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
public String getMember_name() {
return member_name;
}
public void setMember_name(String member_name) {
this.member_name = member_name;
}
#Override
public String toString() {
return getMember_name().toString();
}
}
So my problem is when i enter MI00 there result is like this
i only see MI003. the data is looping, i mean all of the result are MI003.
How can i make this working properly ? Did i miss something ?
Just clear your previous List before inserting new items.
#Override
public void onResponse(JSONArray response) {
if (memberList == null) memberList = new ArrayList<>();
memberList.clear();
Reason
Because you have attached memberList to your adapter, when each time
response come, then you don't clear previous List, and add new items
again.
That is what I could find in your code.
Related
I want to display status and wilayah details from tbl_pegawai table.. If i select an item (name) from the spinner, i want to display the corresponding data (status and wilayah) matches with that item from the database.
Here is my android MainActivity.class file..
Spinner spinnernama, spinnerstatus, spinnerwilayah;
EditText inputstatus, inputwilayah;
Adapterspinner adapter;
List<String> valueId = new ArrayList<String>();
List<String> valueNama = new ArrayList<String>();
List<ModelSpinner> listspinner = new ArrayList<ModelSpinner>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cobaspinner);
spinnernama = findViewById(R.id.spin1);
spinnerstatus = findViewById(R.id.spin2);
spinnerwilayah = findViewById(R.id.spin3);
inputstatus = findViewById(R.id.input1);
inputwilayah = findViewById(R.id.input2);
spinnernama.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
inputstatus.setText(listspinner.get(position).getStatus());
inputwilayah.setText(listspinner.get(position).getWilayah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
adapter = new Adapterspinner(cobaspinner.this, listspinner);
spinnernama.setAdapter(adapter);
callData();
}
private void callData() {
AndroidNetworking.get("http://192.168.43.20:8080/mopp/getDataPegawai.php")
.setTag("Get Data")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
Boolean status = response.getBoolean("status");
if(status){
JSONArray jsonArray = response.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ModelSpinner item =new ModelSpinner();
item.setId(jsonObject.getString("id"));
item.setNama(jsonObject.getString("nama"));
item.setStatus(jsonObject.getString("status"));
item.setWilayah(jsonObject.getString("wilayah"));
listspinner.add(item);
}
}
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
}
});
}
}
here is my spinneradapter...
private Activity activity;
private LayoutInflater inflater;
private List<ModelSpinner> item;
public Adapterspinner(Activity activity, List<ModelSpinner> item) {
this.activity = activity;
this.item = item;
}
#Override
public int getCount() {
return item.size();
}
#Override
public Object getItem(int location) {
return item.get(location);
}
#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.activity_cobaspinner, null);
EditText status = (EditText) convertView.findViewById(R.id.input1);
EditText wilayah = (EditText) convertView.findViewById(R.id.input1);
ModelSpinner data;
data = item.get(position);
status.setText(data.getStatus());
wilayah.setText(data.getWilayah());
return convertView;
Here output when I running and select data from spinner no data display on spinner
I have been following some tutorials to retrieve json data and add it to a listview using volley. I have been stuck in this error trying to solve it for some time, so i had to seek out some help. I tried many examples, this one seems the most intuitive to learn, but i just cant get passed this error, thank you
i cant solve this error
this is my model class
public class Trilhos {
private int id;
private String titulo;
private int id_user;
private String dificuldade;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public int getId_user() {
return id_user;
}
public void setId_user(int id_user) {
this.id_user = id_user;
}
public String getDificuldade() {
return dificuldade;
}
public void setDificuldade(String dificuldade) {
this.dificuldade = dificuldade;
}
}
my adapter
public class AdapterTrilhos extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Trilhos> triList;
public AdapterTrilhos(List<Trilhos> triList, Activity activity) {
this.activity = activity;
this.triList = triList;
}
#Override
public int getCount() {
return this.triList.size();
}
#Override
public Object getItem(int position) {
return this.triList.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.dadoslista, null);
TextView idtxt = (TextView)
convertView.findViewById(R.id.txtid);
TextView tittxt = (TextView)
convertView.findViewById(R.id.txttit);
TextView usertxt = convertView.findViewById(R.id.txtuser);
TextView diftxt = (TextView)
convertView.findViewById(R.id.txtdif);
Trilhos t = triList.get(position);
idtxt.setText(t.getId());
tittxt.setText(t.getTitulo());
usertxt.setText(t.getId_user());
diftxt.setText(t.getDificuldade());
return convertView;
}
}
my main_activity (listarTrilhos)
public class ListarTrilhos extends Activity {
private static final String
urlget="http://192.168.1.68/loginsignup/getTrilhos.php";
private ListView listView;
private AdapterTrilhos adapter;
private List<Trilhos> TrilhosList = new ArrayList<Trilhos>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listatrilhos);
listView=findViewById(R.id.listv);
adapter=new AdapterTrilhos(this,TrilhosList);
listView.setAdapter(adapter);
criarLista();
}
public void criarLista(){
RequestQueue mRequestQueue =
Volley.newRequestQueue(getApplicationContext());
JsonArrayRequest request = new JsonArrayRequest(
urlget,
new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
int count = response.length();
for(int i = 0; i < count; i++){
try {
JSONObject jo = response.getJSONObject(i);
Trilhos tri=new Trilhos();
tri.setId(jo.getInt("id"));
tri.setTitulo(jo.getString("titulo"));
tri.setId_user(jo.getInt("id_user"));
tri.setDificuldade(jo.getString("dificuldade"));
TrilhosList.add(tri);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), response.toString(),
Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "onErrorResponse",
Toast.LENGTH_LONG).show();
}
}
);
Object TAG_REQUEST_QUEUE = new Object();
request.setTag(TAG_REQUEST_QUEUE);
mRequestQueue.add(request);
mRequestQueue.start();
}
}
I didn't read all of your code but noticed that you have constructor
public AdapterTrilhos(List<Trilhos> triList, Activity activity) {
this.activity = activity;
this.triList = triList;}
change adapter=new AdapterTrilhos(this, TrilhosList); to
adapter=new AdapterTrilhos(TrilhosList, this);
I have a listview getting filtered by an edit text on top.However when i click on the item searched i get the result of another item being selected. there r also some data stored in my array which is not visible on listview , is also returning wrong data.
On searching C you get the result filtered as C.But clicking on it results is like the position does not change for the other data but uses the original ArrayList adapter position.
Any help will be appreciated.
My items:
public class Leave_master_items {
public String leave_id;
public String leave_Name;
public String is_hourly;
public Leave_master_items(String leave_Name) {
this.leave_Name = leave_Name;
}
public String getLeave_id() {
return leave_id;
}
public void setLeave_id(String leave_id) {
this.leave_id = leave_id;
}
public String getLeave_Name() {
return leave_Name;
}
public void setLeave_Name(String leave_Name) {
this.leave_Name = leave_Name;
}
public String getIs_hourly() {
return is_hourly;
}
public void setIs_hourly(String is_hourly) {
this.is_hourly = is_hourly;
}
}
My Adapter:
public class Leave_name_adapter extends BaseAdapter implements Filterable{
ArrayList<Leave_master_items> cm = new ArrayList<>();
Context context;
ArrayList<Leave_master_items> mStringFilterList;
ValueFilter valueFilter;
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
// return null;
}
static class ListViewHolder {
TextView leaveType;
}
public Leave_name_adapter(ArrayList<Leave_master_items> cm, Context context) {
this.cm = cm;
this.context = context;
mStringFilterList = cm;
}
#Override
public int getCount() {
return cm.size();
}
#Override
public Object getItem(int position) {
return cm.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ListViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.leaves_listview, parent, false);
viewHolder = new ListViewHolder();
viewHolder.leaveType = (TextView) row.findViewById(R.id.leavestype);
row.setTag(viewHolder);
} else {
viewHolder = (ListViewHolder) row.getTag();
}
Leave_master_items l = (Leave_master_items) getItem(position);
viewHolder.leaveType.setText(l.getLeave_Name());
return row;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// cm.clear();
if (constraint != null && constraint.length() > 0) {
ArrayList<Leave_master_items> filterList = new ArrayList<Leave_master_items>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getLeave_Name().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
Leave_master_items country = new Leave_master_items(mStringFilterList.get(i).getLeave_Name());
filterList.add(country);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
cm = (ArrayList<Leave_master_items>) results.values;
notifyDataSetChanged();
}
}
}
My activity:
leave_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Leave_list().execute();
a.setVisibility(View.INVISIBLE);
b.setVisibility(View.VISIBLE);
v.setBackgroundResource(R.drawable.date_button_bg);
date.setBackgroundResource(R.drawable.leave_button_bg);
leave_btn.setTextColor(Color.parseColor("#293038"));
date.setTextColor(Color.parseColor("#F8F8F8"));
search_leave.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
Leave_application.this.leave_name_adapter.getFilter().filter(arg0);
}
#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
}
});
}
});
private class Leave_list extends AsyncTask<String, Void, Boolean> {
protected void onPreExecute() {
leave_master_itemses.clear();
}
#Override
protected void onPostExecute(final Boolean success) {
leave_name_adapter=new Leave_name_adapter(leave_master_itemses,getApplicationContext());
listview_leave.setAdapter(leave_name_adapter);
listview_leave.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object a = parent.getAdapter().getItem(position);
String b = (String) parent.getItemAtPosition(position);
Leave_master_items leave_master_items=leave_master_itemses.get(position);
selectedFromList=leave_master_items.getLeave_id();
Log.d("Yourtag", selectedFromList);
// Log.d("Clicked item field", " "+ item.getColum(your colum index));
}
});
}
protected Boolean doInBackground(final String... args) {
try {
Login_json_parser jParser = new Login_json_parser();
String s = session.isWEBURL()+"?Function=" + session.isKEY_USERNAME() + "&Emp=" + session.iskey_emp_id();
Log.d("s", s);
JSONObject json1 = jParser.getJSONFromUrl(s);
Log.d("Inputfdfdtsale Stream", "json1");
try {
JSONObject object = (JSONObject) new JSONTokener(json1.toString()).nextValue();
Leave = object.getString("Leave");
Log.d("ew", Leave);
JSONArray jsonArray = new JSONArray(Leave);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = new JSONObject();
jsonObject=jsonArray.getJSONObject(i);
Leave_master_items leave_master_items = new Leave_master_items(null);
leave_master_items.setIs_hourly(jsonObject.getString("is_hourly"));
leave_master_items.setLeave_id(jsonObject.getString("leave_id"));
leave_master_items.setLeave_Name(jsonObject.getString("leave_Name"));
leave_master_itemses.add(leave_master_items);
}
}
catch(JSONException e){
e.printStackTrace();
}
}
catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
}
You have to ask the adapter to get the right object.
Instead of
Leave_master_items leave_master_items = leave_master_itemses.get(position);
try
Leave_master_items leave_master_items = listview_leave.getAdapter().getItem(position);
UPDATE
When you filter you don't have to create a new object with the same content. Just use the object which already exist.
Instead of
Leave_master_items country = new Leave_master_items(mStringFilterList.get(i).getLeave_Name());
filterList.add(country);
Do
filterList.add(mStringFilterList.get(i));
UPDATE2
Don't return 0 in getItemId()
#Override
public long getItemId(int position) {
return position;
}
The problem here is as soon as you start searching something in edittext, your list content changes and you might be using the old list to get the item.
Create a setter in your adapter class for the list you just got after filtering and use that list in your onItemCLick to fetch the position you want to fetch.
I am using on scroll to load more data and show them in list view but my ListView first shows already loaded data then adds the newly added data to ListView
I have used for reference this and many others but unable to solve the issue
Here is my activity class
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
ButterKnife.bind(this);
Users = Users.getCurrentUser(this);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
UIUtility.setStatusColor(this);
Intent intent = getIntent();
try {
entityData = new JSONArray(intent.getStringExtra(EXTRA_DATA));
} catch (JSONException e) {
e.printStackTrace();
}
viewAllCategory = intent.getIntExtra(EXTRA_CATEGORY, 0);
viewAllEntityType = intent.getIntExtra(EXTRA_TYPE, 0);
latitude = intent.getDoubleExtra(EXTRA_LATITUDE, 0);
longitude = intent.getDoubleExtra(EXTRA_LONGITUDE, 0);
setTitle(TITLES[viewAllCategory]);
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser = new ViewAllUserAdapter(this, users);
lvEntity.setAdapter(adapterUser);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook = new ViewAllBookAdapter(this, books);
lvEntity.setAdapter(adapterBook);
}
lvEntity.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!stopLoadingMore) {
if (totalItemCount == firstVisibleItem + visibleItemCount && !isLoading) {
isLoading = true;
showLoading();
loadMoreData();
}
}
}
});
}
private void loadMoreData() {
String loadMoreUrl = buildLoadMoreUrl();
ShareMyBookHttpClient client = new ShareMyBookHttpClient();
client.get(loadMoreUrl, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
hideLoading();
if (responseBody != null) {
start = start+20;
try {
JSONObject jo = new JSONObject(new String(responseBody));
if (!jo.getBoolean(Constants.JsonKeys.ERROR)) {
JSONArray data = jo.getJSONArray(Constants.JsonKeys.DATA);
if (data.length() == 0) {
stopLoadingMore = true;
return;
}
if (data.length() < 20) {
stopLoadingMore = true;
}
for (int i = 0; i < data.length(); i++) {
entityData.put(data.getJSONObject(i));
}
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser.mergeArray(users);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook.mergeArray(books);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
hideLoading();
}
});
}
private String buildLoadMoreUrl() {
switch (viewAllCategory) {
default:
case ViewAllCategory.CATEGORY_USER:
return Constants.createUrlToGetViewAllUsers(Users.getId(), latitude, longitude, Users.getAuthToken(), start, LIMIT);
case ViewAllCategory.CATEGORY_MY_BOOKS:
return Constants.createUrlToGetViewAllMyBooks(Users.getId(), Users.getAuthToken(), start, LIMIT);
}
}
private void showLoading() {
sbLoading = Snackbar.make(coolMain, R.string.view_all_loading, Snackbar.LENGTH_INDEFINITE);
sbLoading.show();
}
private void hideLoading() {
isLoading = false;
if (sbLoading != null) {
sbLoading.dismiss();
}
}
and following is my AdapterClasss
public class ViewAllUserAdapter extends BaseAdapter {
private List<Users> users;
private Context context;
public ViewAllUserAdapter(Context context, List<Users> usersData) {
this.context = context;
users = usersData;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
}
return row;
}
#Override
public int getCount() {
return users == null ? 0 : users.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
public class UserVH extends View {
#Bind(R.id.item_vau_iv_user_image)
ImageView ivUserImage;
#Bind(R.id.item_vau_tv_name)
TextView tvName;
#Bind(R.id.item_vau_tv_distance)
TextView tvDistance;
private int position;
public UserVH(View view, final int position) {
super(context);
this.position = position;
ButterKnife.bind(this, view);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
UIUtility.openUserDetailActivity(context, users.get(position));
}
});
}
}
}
As you already referred this link, Exactly the same issue is happening with you, You should have correct implementation for holder class in getView method.
Update your getView() method as per below :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();
}
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
return row;
}
And update your getItemId and getItem methods as per below :
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
EDIT : clear the list additional users before adding the new objects
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
// Following line to be added
additonalusers.clear();
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
Your implementation of following methods is incorrect.
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
Change them as below
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
So I made an sliding tabs app that loads json into a listview. My question is how would I implement something that would only load 5 listview items in the beginning and would load another 5 when you scroll down? (Instead of loading all of the listview items in the beginning)
I have search the web and I can't really understand how to do this. Any suggestions or ideas will be appreciated.
This is some of my code. These classes is where I think the code would go: I used SlidingTabLayout & strip from the android developer site.
CustomListAdapter code:
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Tanga> tangasItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Tanga> movieItems) {
this.activity = activity;
this.tangasItems = movieItems;
}
#Override
public int getCount() {
return tangasItems.size();
}
#Override
public Object getItem(int location) {
return tangasItems.get(location);
}
#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.list_row, null);
TextView name = (TextView) convertView.findViewById(R.id.name);
// getting movie data for the row
Tanga m = tangasItems.get(position);
// title
name.setText(m.getName());
return convertView;
}
}
Fragment:
public class Tab1 extends Fragment {
private static final String url = "website.json";
private List<Tanga> tangaList = new ArrayList<Tanga>();
private ListView listView;
private CustomListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), tangaList);
listView.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Tanga movie = new Tanga();
//name
String name = obj.getString("name");
movie.setName(name);
// adding movie to movies array
tangaList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: ");
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tabs, container, false);
return v;
}
}
Tanga Code: (model)
public class Tanga {
private String name;
public Tanga() {
}
public Tanga(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
There are multiple ways you could handle this, the simplest way would be to create another ArrayList of type Tanga, let's suppose it's name is tangaList2. What you have to do is in your for loop write this code.
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Tanga movie = new Tanga();
//name
String name = obj.getString("name");
movie.setName(name);
// adding movie to movies array
if(i < 5) {
tangaList.add(movie);
}
else {
tangaList2.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
Now after this you should also implement the onScrollListener in your Fragment:
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if ((++firstVisibleItem) + visibleItemCount > totalItemCount) {
for(int i = 0; i < 5 && tangaList2.size() > 0; i++){
tangaList.add(tangaList2.get(0));
tangaList2.remove(0);
}
}
}
});