I am trying to implement swipe to refresh in my app. When swipe to refresh is triggered, first all the data is fetched from JSON and then stored in the database. After storing the data, all the new data will be added to the top of the recyclerview. I read a few articles and only managed to find out about adding a single item at the top of the list. But in the case of my app, where more than one item may be available to show, what should I do?
Here is my code for the database table where first new post is fetched with the last post id which is shown in recyclerview:
#Override
public ArrayList<Post> getAllNewPost(int T) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Post> postList = null;
try {
postList = new ArrayList<Post>();
String QUERY = "SELECT * FROM " + TABLE_NAME + " INNER JOIN "+TABLE_FOLLOWER+
" ON post_table.user_id = follower.user_id WHERE follower.follow = '1' AND post_table.post_id > "+T+" ORDER BY "+POST_ID+" DESC";
Cursor cursor = db.rawQuery(QUERY, null);
if (!cursor.isLast()) {
while (cursor.moveToNext()) {
Post post = new Post();
post.setPost_id(cursor.getString(0));
Log.d("post_id",cursor.getString(0));
post.setUser_id(cursor.getString(1));
post.setUser_name(cursor.getString(2));
post.setImg_link(cursor.getString(3));
post.setPost_title(cursor.getString(4));
post.setPost_cat(cursor.getString(6));
post.setPost_time(cursor.getString(8));
postList.add(post);
}
}
db.close();
} catch (Exception e) {
Log.e("error", e + "");
}
return postList;
}
Here is array adapter of recyclerview:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> listData = new ArrayList<>();
String rpostid,ruserid,rname,rcat,rdate,rtittle,urlThumnail;
private VolleySingleton volleySingleton;
ImageLoader imageLoader = VolleySingleton.getsInstance().getImageLoad();
public PostAdapter(ArrayList<Post> postList) {
this.listData=postList;
}
public PostAdapter(Context context){
this.context = context;
}
#Override
public PostAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.post_item, viewGroup, false);
return new posts(v);
}
public class posts extends ViewHolder {
TextView tvTittle,tvPostId,tvUseId,tvName,tvCat,tvDate;
ImageView row_img;
public posts(View v) {
super(v);
tvTittle = (TextView) v.findViewById(R.id.row_cmnt);
tvPostId = (TextView) v.findViewById(R.id.row_postid);
tvUseId = (TextView) v.findViewById(R.id.row_userid);
tvName = (TextView) v.findViewById(R.id.row_name);
tvCat = (TextView) v.findViewById(R.id.row_cat);
tvDate = (TextView) v.findViewById(R.id.row_date);
row_img = (ImageView) v.findViewById(R.id.row_img);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
TextView text = (TextView) v.findViewById(R.id.row_postid);
String lst_txt = text.getText().toString().trim();
intent = new Intent(v.getContext(), PostView.class);
intent.putExtra("post_id", lst_txt);
v.getContext().startActivity(intent);
}
});
}
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final posts holder = (posts) viewHolder;
Post post = listData.get(position);
rpostid = post.getPost_id();
ruserid = post.getUser_id();
rname = post.getUser_name();
rcat = post.getPost_cat();
rdate = post.getPost_time();
rtittle = post.getPost_title();
holder.tvPostId.setText(rpostid);
holder.tvUseId.setText(ruserid);
holder.tvName.setText(rname);
holder.tvCat.setText(rcat);
holder.tvDate.setText(rdate);
holder.tvTittle.setText(rtittle);
urlThumnail = post.getImg_link();
Log.d("qwerty","link of image lru: "+ urlThumnail);
if (urlThumnail != null){
imageLoader.get(urlThumnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.row_img.setImageBitmap(response.getBitmap());
Log.d("qwerty","post attached 2");
}
#Override
public void onErrorResponse(VolleyError error) {
Log.d("qwerty","post attached 3");
}
});
}
}
#Override
public int getItemCount() {
return (null != listData ? listData.size() : 0);
}
}
And here is the code by which all the new posts will be fetched from the DB:
private ArrayList<Post> parseJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Log.d("response",post_id+" "+user_id+" "+user_name+" "+img_link);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllPost();
t = Integer.parseInt(postList.get(1).getPost_id().toString().trim());
Log.d("Check", "postid: "+t);
Hpbar.setVisibility(View.INVISIBLE);
Log.d("jsonCount", String.valueOf(postList));
String AdapterData = String.valueOf(postList);
if(AdapterData.equals("[]")){
Htvnopostfound.setVisibility(View.VISIBLE);
}else{
adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
}
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
private ArrayList<Post> swipeJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllNewPost(t);
adapter.notifyItemInserted(1);
Log.d("check","post_id "+t+" hello");
/*adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
Log.d("check","post_id "+t+" hello 2");*/
Log.d("check","post_id "+t+" hello 2");
Hpbar.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
On startup parseJSONResponse is used and for swipeToRefresh swipeJSONResponse is used. In parseJSONResponse, the last displayed post's id is stored in int t and then this int t is passed to swipeJSONResponse to get the new post.
But after refreshing, new data will not show in the list. SO, please tell me how to do so. I've read a few articles where add is used, as such:
listview.add(0, item);
But I don't know how to implement this with multiple rows of data at same time. Thanks in advance.
The correct way to update data in a listView should be:
1) create an update data method in your adapter. In your case could be like this:
public updateData(ArrayList<Post> postList) {
this.listData=postList;
notifyDataSetChanged();
}
or, if you want just append data on the top:
public addNewDataOnTop(ArrayList<Post> postList) {
this.listData.addAll(0,postList);
notifyDataSetChanged();
}
2) When you have new data to add, do not create a new adapter but just update the data
When you create the listView at the beginning you set the empty adapter:
adapter = new PostAdapter(new ArrayList());
listView.setAdapter(adapter);
When you receive the new data, you just update the adapter:
adapter.addNewDataOnTop(postList);
I hope it helped
I would insert each item at the top using:
mArrayList.add(0, item1);
notifyItemInserted(0);
mArrayList.add(0, item2);
notifyItemInserted(0);
Do the following for all your items.
Related
I have a listview in which in each row I have a checkbox along with details o persons. Now on clicking checkboxes, I want to store the id of those persons in arrayList which I am able to store but the arrayList id in adapter. I want to access the arrayList in activity because I want to take a button in activity on clicking which I want to send ids of all the selected persons to another activity. How do I do that.
My code is below:
SendWorkList.java
public class SendWorkList extends AppCompatActivity {
List<SendWorkRow> send_work_array_list;
ListView send_work_list;
JSONArray send_work_jsonArray1,send_work_result_jsonArray2;
JSONObject send_work_jsonObject1,send_work_result_jsonArray2_i;
String[] send_work_id,send_work_name,send_work_bankaccount,send_work_ifsc,send_work_contacts,send_work_department,send_work_cardnumber,send_work_cardexpiry,send_work_cardcvv;
String send_work_status,send_work_result;
ViewGroup send_work_headerView;
Set<Integer> send_work_count;
Intent intent;
Set<String> indexes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_work);
send_work_list=findViewById( R.id.send_work_list);
send_work_array_list=new ArrayList<SendWorkRow>();
send_work_count= new HashSet<>();
}
#Override
protected void onResume() {
super.onResume();
cardDetailsList();
/* send_work_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SendWorkList.this, "assasa", Toast.LENGTH_SHORT).show();
}
});*/
}
private void cardDetailsList()
{
RequestQueue rq = Volley.newRequestQueue(SendWorkList.this);
StringRequest stringRequest = new StringRequest( Request.Method.GET,
"http://grepthorsoftware.in/tst/bank_account/showingdata.php",
new Response.Listener<String>() {
public void onResponse(String response) {
try {
send_work_jsonArray1=new JSONArray(response);
send_work_jsonObject1 = send_work_jsonArray1.getJSONObject(0);
send_work_status= send_work_jsonObject1.getString("status");
if(send_work_status.equals("1")) {
send_work_result = send_work_jsonObject1.getString("result");
send_work_result_jsonArray2 = new JSONArray(send_work_result);
send_work_id = new String[send_work_result_jsonArray2.length()];
send_work_name = new String[send_work_result_jsonArray2.length()];
send_work_bankaccount = new String[send_work_result_jsonArray2.length()];
send_work_ifsc = new String[send_work_result_jsonArray2.length()];
send_work_contacts = new String[send_work_result_jsonArray2.length()];
send_work_department =new String[send_work_result_jsonArray2.length()];
send_work_cardnumber = new String[send_work_result_jsonArray2.length()];
send_work_cardexpiry = new String[send_work_result_jsonArray2.length()];
send_work_cardcvv= new String[send_work_result_jsonArray2.length()];
if ( send_work_name.length > 0 || send_work_id.length > 0 || send_work_bankaccount.length > 0 || send_work_ifsc.length > 0 || send_work_contacts.length > 0)
{
send_work_id = null;
send_work_name = null;
send_work_bankaccount = null;
send_work_ifsc = null;
send_work_contacts = null;
send_work_department= null;
send_work_cardnumber= null;
send_work_cardexpiry= null;
send_work_cardcvv= null;
send_work_id = new String[send_work_result_jsonArray2.length()];
send_work_name = new String[send_work_result_jsonArray2.length()];
send_work_bankaccount = new String[send_work_result_jsonArray2.length()];
send_work_ifsc = new String[send_work_result_jsonArray2.length()];
send_work_contacts = new String[send_work_result_jsonArray2.length()];
send_work_department =new String[send_work_result_jsonArray2.length()];
send_work_cardnumber = new String[send_work_result_jsonArray2.length()];
send_work_cardexpiry = new String[send_work_result_jsonArray2.length()];
send_work_cardcvv= new String[send_work_result_jsonArray2.length()];
}
for(int i=0;i<send_work_result_jsonArray2.length();i++)
{
send_work_result_jsonArray2_i=send_work_result_jsonArray2.getJSONObject(i);
send_work_id[i] = send_work_result_jsonArray2_i.getString("id");
send_work_name[i] = send_work_result_jsonArray2_i.getString("Name");
send_work_bankaccount[i] = send_work_result_jsonArray2_i.getString("Bankaccount");
send_work_ifsc[i] = send_work_result_jsonArray2_i.getString("IFSC");
send_work_contacts[i] = send_work_result_jsonArray2_i.getString("Contact");
send_work_department[i] = send_work_result_jsonArray2_i.getString("Department");
send_work_cardnumber[i] = send_work_result_jsonArray2_i.getString("Cardnumber");
send_work_cardexpiry[i] = send_work_result_jsonArray2_i.getString("Cardexpiry");
send_work_cardcvv[i] = send_work_result_jsonArray2_i.getString("Cardcvv");
}
if ( send_work_array_list.size() > 0) {
send_work_array_list.clear();
}
for (int i = 0; i < send_work_id.length && i< send_work_name.length && i < send_work_bankaccount.length && i < send_work_ifsc.length && i < send_work_contacts.length && i < send_work_department.length && i< send_work_cardnumber.length && i< send_work_cardexpiry.length && i< send_work_cardcvv.length; i++) {
send_work_array_list.add(new SendWorkRow( send_work_id[i], send_work_name[i], send_work_bankaccount[i], send_work_ifsc[i], send_work_contacts[i], send_work_department[i], send_work_cardnumber[i], send_work_cardexpiry[i],send_work_cardcvv[i]));
}
if ( send_work_headerView != null) {
send_work_list.removeHeaderView( send_work_headerView);
}
send_work_headerView = (ViewGroup) getLayoutInflater().inflate(R.layout.send_work_list_view_header, send_work_list, false);
send_work_list.addHeaderView( send_work_headerView);
send_work_list.setAdapter(new SendWorkAdapter(SendWorkList.this, send_work_array_list));
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
rq.add(stringRequest);
}
}
SendWorkAdapter.java
public class SendWorkAdapter extends BaseAdapter {
Context context;
List<SendWorkRow> send_work_array_list;
Set<String> indexes;
public SendWorkAdapter(Context context, List<SendWorkRow> send_work_array_list)
{
this.context=context;
this.send_work_array_list=send_work_array_list;
indexes = new HashSet<String>();
}
#Override
public int getCount() {
return send_work_array_list.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater= (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View view=inflater.inflate( R.layout.send_work_list_view_row,viewGroup,false);
CheckBox textView1=view.findViewById( R.id.send_work_checkbox_row);
TextView textView2=view.findViewById( R.id.send_work_name_row );
TextView textView3=view.findViewById( R.id.send_work_bank_account_row );
TextView textView4=view.findViewById( R.id.send_work_ifsc_row );
TextView textView5=view.findViewById( R.id.send_work_contact_number_row );
TextView textView6=view.findViewById( R.id.send_work_department_row );
TextView textView7=view.findViewById( R.id.send_work_card_number_row );
TextView textView8=view.findViewById( R.id.send_work_expiry_date_row );
TextView textView9=view.findViewById( R.id.send_work_cvv_row );
final SendWorkRow account_details_row=send_work_array_list.get( position );
textView2.setText( account_details_row.getSendWorkCardDetailsName() );
textView3.setText( account_details_row.getSendWorkCardDetailsBankAccount() );
textView4.setText( account_details_row.getSendWorkCardDetailsIfsc());
textView5.setText( account_details_row.getSendWorkCardDetailsContacts() );
textView6.setText( account_details_row.getSendWorkCardDetailsDepartment() );
textView7.setText( account_details_row.getSendWorkCardDetailsCardNumber() );
textView8.setText( account_details_row.getSendWorkCardDetailsCardExpiry() );
textView9.setText( account_details_row.getSendWorkCardDetailsCardCvv() );
textView1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()){
Toast.makeText(context, account_details_row.getSendWorkCardDetailsId(), Toast.LENGTH_SHORT).show();
indexes.add(account_details_row.getSendWorkCardDetailsId());
}
}
});
return view;
}
}
SendWorkRow.java
public class SendWorkRow {
private String send_work_id,send_work_name,send_work_bankaccount,send_work_ifsc,send_work_contacts,send_work_department,send_work_cardnumber,send_work_cardexpiry,send_work_cardcvv;
public SendWorkRow(String send_work_id, String send_work_name, String send_work_bankaccount, String send_work_ifsc, String send_work_contacts,String send_work_department,String send_work_cardnumber,String send_work_cardexpiry,String send_work_cardcvv) {
this.send_work_id = send_work_id;
this.send_work_name = send_work_name;
this.send_work_bankaccount = send_work_bankaccount;
this.send_work_ifsc = send_work_ifsc;
this.send_work_contacts = send_work_contacts;
this.send_work_department = send_work_department;
this.send_work_cardnumber = send_work_cardnumber;
this.send_work_cardexpiry = send_work_cardexpiry;
this.send_work_cardcvv = send_work_cardcvv;
}
//Getters
public String getSendWorkCardDetailsId() {
return send_work_id;
}
public String getSendWorkCardDetailsName() {
return send_work_name;
}
public String getSendWorkCardDetailsBankAccount() {
return send_work_bankaccount;
}
public String getSendWorkCardDetailsIfsc() {
return send_work_ifsc;
}
public String getSendWorkCardDetailsContacts() {
return send_work_contacts;
}
public String getSendWorkCardDetailsDepartment() {
return send_work_department;
}
public String getSendWorkCardDetailsCardNumber() {
return send_work_cardnumber;
}
public String getSendWorkCardDetailsCardExpiry() {
return send_work_cardexpiry;
}
public String getSendWorkCardDetailsCardCvv() {
return send_work_cardcvv;
}
}
Create one method in adapter like
public class SendWorkAdapter extends BaseAdapter {
public List<SendWorkRow> getAllWorkRows() {
return send_work_array_list;
}
}
and access this method using adapter instance in activity.
Another way is you can write a method in Adapter where you will find all selected ids in a List and return. So whenever you will require list of selected ids, call this method from Activity and do your task. like
public class SendWorkAdapter extends BaseAdapter {
public List<SendWorkRow> getAllSelectedWorkRows() {
// write your logic to find selected rows
return result;
}
}
Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.
Here is my code.
private void populateRecycleView() {
if (Utility.checkNetworkConnection(this)) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Searching...");
progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
progressDialog.setCancelable(false);
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
String firstName = jsonObject.getString("fName");
String secondName = jsonObject.getString("sName");
String email = jsonObject.getString("emailid");
String password = jsonObject.getString("pass");
String mobile = jsonObject.getString("mobile");
String bloodRt = jsonObject.getString("blood");
String age = jsonObject.getString("age");
String gender = jsonObject.getString("gender");
String country = jsonObject.getString("country");
String location = jsonObject.getString("location");
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
String profilePicFIleName = jsonObject.getString("picname");
String profilePicURL = jsonObject.getString("pic");
Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
country, location, latitude, longitude, profilePicFIleName, profilePicURL);
donorsList.add(donor);
count++;
}
donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(donorsAdapter);
donorsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("bloodGroup", bloodGroup);
return params;
}
};
NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
} else {
Utility.checkNetworkConnectionFound(this);
}
}
And this is my RecyclerView adapter...
public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {
private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;
public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
this.context = context;
this.donorList = donorList;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
final Donor donor = donorList.get(position);
String displayName = donor.getFirstName() + " " + donor.getSecondName();
holder.tvDisplayName.setText(displayName);
holder.tvEmailID.setText(donor.getEmail());
String userProfileURL = donor.getProfilePicURL();
if (!userProfileURL.equals("")) {
Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
into(holder.ivProfilePic);
} else {
holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
}
bloodGroup = donor.getBloodGroup();
if (bloodGroup.equals("A+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
else if (bloodGroup.equals("A-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
else if (bloodGroup.equals("B+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
else if (bloodGroup.equals("B-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
else if (bloodGroup.equals("O+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
else if (bloodGroup.equals("O-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
else if (bloodGroup.equals("AB+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
else if (bloodGroup.equals("AB-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);
if(Utility.isNetworkEnabled){
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, DisplayDonorDetails.class);
intent.putExtra("donor", donor);
context.startActivity(intent);
}
});
}else {
Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
if(donorList != null){
return donorList.size();
}else {
return 0;
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
TextView tvDisplayName;
TextView tvEmailID;
ConstraintLayout constraintLayout;
public CustomViewHolder(View itemView) {
super(itemView);
ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
}
}
}
Populate your donorsAdapter only with the 50 first elements of your donorsList, create a function that save the position of the latest element displayed and add other 50 donors to your adapter starting from the latest position saved when you need it.
Hope it helps.
EDIT
First create an emptyList:
List<Donor> subElements = new ArrayList<>();
and pass it to your adapter:
donorsAdapter = new DonorsAdapter(FindDonorResult.this, subElements);
Now you can create a method like this (you can call in onClick event for example):
private int LAST_POSITION = 0;
private int DONORS_NUM_TOSHOW = 50;
public void showMoreDonors(){
if(donarsList.size() > Last_postion+50){
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,Last_postion+DONORS_NUM_TOSHOW));
for(Donor a : tempList){
subElements.add(a);
}
Last_postion += DONORS_NUM_TOSHOW;
donorsAdapter.notifyDataSetChanged();
}else{
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,donorsList.size()));
for(Donor a : tempList){
subElements.add(a);
}
donorsAdapter.notifyDataSetChanged();
}
}
Remember to check when donorsList is over.
I didn't test it, but i hope it is usefull to understand the idea.
Finally, I sort this out. I have got an awesome tutorial from this blog.
http://android-pratap.blogspot.in/2015/06/endless-recyclerview-with-progress-bar.html.
I made some changes to populate the list because my data is on a remote server and by using volley library I fetched the data into the list. Remaining things are same.
I am creating an application with a list that list cards based on the value from the server.
I created a StudentCardArrayAdapter to achieve this and everything works fine. All the data has been populated in card list. also I able to get the values on button click in each card separately.
What I need is on clicking the button it will call a method requestion server for data asynchronously and get a value from the server and according to that value, i need to change the button text in that particular card.
My StudentCardArrayAdapter code:
public class StudentCardArrayAdapter extends ArrayAdapter<StudentCard> {
private static final String TAG = "CardArrayAdapter";
private List<StudentCard> cardList = new ArrayList<StudentCard>();
private Context mContext;
String selected = "0";
PreferenceHelper prefs;
CardViewHolder viewHolder;
View row;
ProgressDialog pd;
static class CardViewHolder {
TextView studentname;
TextView stop;
Button selectbutton;
CircleImageView imageId;
}
public StudentCardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.mContext = context;
prefs = new PreferenceHelper(this.mContext);
pd = new ProgressDialog(this.mContext);
}
#Override
public void add(StudentCard object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public StudentCard getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.student_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.studentname = (TextView) row.findViewById(R.id.studentname);
viewHolder.stop = (TextView) row.findViewById(R.id.stop);
viewHolder.selectbutton = (Button) row.findViewById(R.id.selectbutton);
viewHolder.imageId = (CircleImageView) row.findViewById(R.id.imageId);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
StudentCard card = getItem(position);
viewHolder.studentname.setText(card.getStudName());
viewHolder.studentname.setTextColor(Color.parseColor("#000000"));
viewHolder.stop.setText(card.getStudStop());
viewHolder.stop.setTextColor(Color.parseColor("#000000"));
if(card.getSelected().equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
else{
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.select));
viewHolder.selectbutton.setEnabled(true);
}
final String studid = card.getStudId();
final String busname = prefs.getString("busname", "0");
final String schoolid = prefs.getString("schoolid", "");
viewHolder.selectbutton.setOnClickListener(new View.OnClickListener()
{
String updatedvalue = "0";
#Override
public void onClick(View v)
{
Log.e("studid",studid);
Log.e("busname",busname);
Log.e("schoolid",schoolid);
selectstudent(v, studid, busname, schoolid,mContext);
//Toast.makeText(v.getContext(), amountinfo, Toast.LENGTH_SHORT).show();
/*SnackbarManager.show(Snackbar.with(this) // context
.text(amountinfo));*/
}
});
Picasso.with(mContext).load(card.getImageUrl()).fit().error(R.mipmap.ic_launcher).into(viewHolder.imageId);
return row;
}
public void selectstudent(final View v, String studid, String busname, String schoolid, final Context mContext) {
String returnedselected = "0";
Log.e("BASE_URL_STUDENT_UPDATE", Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid);
RestClientHelper.getInstance().get(Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("RESULT", response);
try {
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("status");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String status = post.optString("status");
if (status.equals("true")) {
selected = post.optString("selected");
} else {
selected = post.optString("selected");
String error = post.optString("error");
SnackbarManager.show(Snackbar.with(getContext()) // context
.text(error));
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
if(selected.equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
}
}
#Override
public void onError(String error) {
Log.e("error", error);
selected = "0";
}
});
}
}
I used the below code but nothing works.. No error also.. and not change in button text.I get value of selected as 1 from server.
if(selected.equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
I am new to android.. and is stuck here. Please help me out.
FINALLY IT WORKED
As changes mention by Krish, I updated the code suggested by him.
And added this changes in onClick it worked
if(card.getSelected().equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
Change the code like this,
public void selectstudent(StudentCard card, String studid, String busname, String schoolid, final Context mContext) {
String returnedselected = "0";
Log.e("BASE_URL_STUDENT_UPDATE", Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid);
RestClientHelper.getInstance().get(Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("RESULT", response);
try {
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("status");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String status = post.optString("status");
if (status.equals("true")) {
selected = post.optString("selected");
} else {
selected = post.optString("selected");
String error = post.optString("error");
SnackbarManager.show(Snackbar.with(getContext()) // context
.text(error));
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
if(selected.equals("1")){
card.setSelected("1");
notifyDataSetChanged();
}
}
}
#Override
public void onError(String error) {
Log.e("error", error);
selected = "0";
}
});
}
and change this line like this ,
final StudentCard card = getItem(position);
and call method inside onclick.
selectstudent(card, studid, busname, schoolid,mContext);
I am using listview with dynamic items.It is saving in wrong place(That means 1st item showing in third item, second item showing in 5th item, etc).I dont know how to solve this one.I have added the relevant code.Please check it.
EDIT:
UpcomingGoalAdapter.java:
public class UpcomingGoalAdapter extends ArrayAdapter<UpcomingGoalItems> {
private Context context;
#SuppressWarnings("unused")
private List<UpcomingGoalItems> items;
String eventIdForVol;
private UpcomingGoalAdapter adapter;
String userIdStr, tokenStr;
public UpcomingGoalAdapter(Context context, int resource, List<UpcomingGoalItems> objects) {
super(context, resource, objects);
this.context = context;
this.items = objects;
this.adapter = this;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final UpcomingGoalItems rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adapt_upcoming_goal, null);
holder = new ViewHolder();
holder.tvInterest = (TextView) convertView.findViewById(R.id.tv_interest_goal_adapt);
holder.ivEdit = (ImageView) convertView.findViewById(R.id.iv_edit_goal_adapt);
holder.tvCount = (TextView) convertView.findViewById(R.id.tv_count_goal_adapt);
holder.ivDelete = (ImageView) convertView.findViewById(R.id.iv_delete_goal_adapt);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if((rowItem.getInterest().equals(null) || rowItem.getInterest().equals(""))
&& (rowItem.getLocation().equals(null) || rowItem.getLocation().equals(""))
&& (rowItem.getFromDate().equals(null) || rowItem.getFromDate().equals(""))
&& (rowItem.getToDate().equals(null) || rowItem.getToDate().equals(""))) {
holder.tvInterest.setText("-");
} else {
holder.tvInterest.setText("Looking for "+rowItem.getInterest() + " in " + rowItem.getSplitLocation() + " On ( "
+ rowItem.getFromDate() + " - " + rowItem.getToDate()+" ) ");
}
holder.tvCount.setText(rowItem.getCount());
return convertView;
}
private class ViewHolder {
TextView tvInterest;
ImageView ivEdit;
TextView tvCount;
ImageView ivDelete;
}
UpcomingGoalActivity.java:
ArrayList<UpcomingGoalItems> itemsaArrayList;
UpcomingGoalAdapter itemsAdapter;
ListView listView;
itemsaArrayList = new ArrayList<UpcomingGoalItems>();
itemsAdapter = new UpcomingGoalAdapter(UpcomingGoalActivity.this, R.layout.adapt_upcoming_goal, itemsaArrayList);
listView = (ListView) findViewById(R.id.lv_interest_goal_search);
listView.setAdapter(itemsAdapter);
hitGoalApi();
private void hitGoalApi(){
String myGoalsUrl = PK_MY_GOALS;
Log.e("myGoalsUrl", myGoalsUrl);
StringRequest request = new StringRequest(Request.Method.GET, myGoalsUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
if(response != null && !response.startsWith("<HTML>")){
Log.e("MyGoalsRes", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArrData = jsonObject.getJSONArray("data");
for(int i=0; i < jsonArrData.length(); i++){
JSONObject getDataJsonObj = jsonArrData.getJSONObject(i);
LOCATION = getDataJsonObj.getString("location");
String[] placeArray = LOCATION.split("\\s*,\\s*");
Log.e("placeArray", ""+ Arrays.toString(placeArray));
String placeStr = placeArray[0];
FROM_DATE = getDataJsonObj.getString("fromdate");
TO_DATE = getDataJsonObj.getString("todate");
GOAL_ID = getDataJsonObj.getString("g_id");
getInterest = getDataJsonObj.getString("users_interest_goals");
hitCountApi(GOAL_ID, placeStr, FROM_DATE, TO_DATE, getInterest);
}
}
catch (JSONException e){
e.printStackTrace();
}
}else{
toastShort(getApplicationContext(), "Check Internet");
}
}
}
private void hitCountApi(final String goalId, final String splitLoc, final String fromDate,
final String toDate, final String getInteresn) {
String countUrl = PK_GOAL_SEARCH + goalId + ".json";
Log.e("countUrl", countUrl);
StringRequest request = new StringRequest(Request.Method.GET, countUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
if (response != null && !response.startsWith("<HTML>")) {
Log.e("CountRes", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject metaJsonObj = jsonObject.getJSONObject("_metadata");
String totalRecStr = metaJsonObj.getString("total_records");
Log.e("totalRecStr", "" + totalRecStr);
UpcomingGoalItems items = new UpcomingGoalItems();
items.setSplitLocation(splitLoc);
items.setFromDate(fromDate);
items.setToDate(toDate);
items.setGoalId(goalId);
items.setInterest(getInterest);
items.setCount(totalRecStr); ;
itemsaArrayList.add(items);
itemsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
toastShort(getApplicationContext(), "Check Internet");
}
}
})
Based on the Volley response order I have to show the right id for listview.It takes wrong order.
Let me know why it is ordering at wrong place and how to solve this.Thank You.
tldr: Use ArrayList instead of List:
private ArrayList<UpcomingGoalItems> items;
The ArrayAdapters I use tend to look like this:
(the ArrayList< String> names is an ArrayList created from the names of the ArrayList< Task>)
public class ArrayAdapterTask extends ArrayAdapter<String> {
private final Context context;
private int layoutId;
private ArrayList<Task> tasks;
public ArrayAdapterTask(Context context, ArrayList<String> names, ArrayList<Task> tasks, int layoutId) {
super(context, layoutId, names);
this.context = context;
this.tasks = null;
this.tasks = tasks;
this.layoutId = layoutId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// Do stuff with the tasks.get(position)
}
}
I have a ListView and a list view adapter. The adapter populates the ListView from a List. The list view has a onScrollListener. The problem I have is when on scroll new data are loaded to the view but the scroll bar jumps to the top of the view.
What I want is to keep the scroll position where it was!
Any help?
Thanks
List View class:
private class GetItems extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(AppList.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading more");
mProgressDialog.setMessage("loading);
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
applicationList = new ArrayList();
try
{
GetDataAppList getDataAppList = new GetDataAppList();
JSONArray jsonData = getDataAppList.getJSONData(webfileName, limit, offset);
for (int i = 0; i <= jsonData.length() - 2; i++)
{
JSONObject c = jsonData.getJSONObject(i);
id = c.getString("id");
name = c.getString("name");
logo = c.getString("logo");
developer = c.getString("developer");
rate = c.getInt("rates");
category = c.getInt("category");
fileName = c.getString("filename");
path = c.getString("path");
appSize = c.getDouble("size");
if(category == 1001)
{
String gCat = c.getString("game_category");
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path,gCat));
}
else
{
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path));
}
}
JSONObject sizeObj = jsonData.getJSONObject(jsonData.length() - 1);
size = sizeObj.getInt("size");
}
catch (Exception ex)
{
Log.d("Thread:", ex.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Locate the ListView in listview.xml
listview = (ListView) findViewById(R.id.listView);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Create an OnScrollListener
listview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count - threshold) {
if (size >= offset)
{
new LoadMoreDataTask().execute();
offset = offset + 15;
}
else
{
Toast.makeText(getApplicationContext(), "ختم لست!", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});
RatingBar bar = (RatingBar) findViewById(R.id.ratingBarShow);
}
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(AppList.this);
mProgressDialog.setTitle("Loading more");
mProgressDialog.setMessage("loading);
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
GetDataAppList getDataAppList = new GetDataAppList();
JSONArray jsonData = getDataAppList.getJSONData(webfileName, limit, offset);
for (int i = 0; i <= jsonData.length(); i++) {
JSONObject c = jsonData.getJSONObject(i);
id = c.getString("id");
name = c.getString("name");
logo = c.getString("logo");
developer = c.getString("developer");
rate = c.getInt("rates");
category = c.getInt("category");
fileName = c.getString("filename");
path = c.getString("path");
appSize = c.getDouble("size");
if(category == 1001)
{
String gCat = c.getString("game_category");
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path,gCat));
}
else
{
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path));
}
}
}
catch (Exception ex)
{
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
int position = listview.getLastVisiblePosition();
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
listview.setAdapter(adapter);
listview.setSelectionFromTop(position, 0);
mProgressDialog.dismiss();
}
}
The Adpater class:
public ListViewAdapter(Activity activity, ArrayList<ApplicationPojo> applicationList, ListView listView)
{
this.activity = activity;
this.applicationList = applicationList;
this.inflater = LayoutInflater.from(activity);
downloader = new ApkFileDownloader(activity);
this.listView = listView;
}
#Override
public int getCount() {
return applicationList.size();
}
#Override
public ApplicationPojo getItem(int position) {
return applicationList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent)
{
if (view == null)
{
holder = new ViewHolder();
view = inflater.inflate(R.layout.singleapp, null);
holder.openInstalledAppBtn = (ImageView) view.findViewById(R.id.openInstalledApp);
holder.downloadBtn = (ImageView) view.findViewById(R.id.updateApp);
holder.progressBar = (ProgressBar)view.findViewById(R.id.updateProgress);
holder.cancelBtn = (ImageView) view.findViewById(R.id.cancel);
holder.appName = (TextView) view.findViewById(R.id.appName);
holder.developer = (TextView) view.findViewById(R.id.developer);
holder.size = (TextView) view.findViewById(R.id.size);
holder.appCat = (TextView) view.findViewById((R.id.appCat));
holder.installBtn = (ImageView) view.findViewById(R.id.install);
holder.catlogo = (ImageView) view.findViewById(R.id.catlogo);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
try
{
final View finalView = view;
holder.logo = (ImageView) finalView.findViewById(R.id.appLogo);
logoName = applicationList.get(position).getLogo();
Picasso.with(activity)
.load(IPClass.SERVERIP + logoName)
.into(holder.logo);
// holder.logo.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View arg0) {
//
// }
// });
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String appid = applicationList.get(position).getId();
int category = applicationList.get(position).getCategory();
Intent rec1Intent = new Intent(activity, AppView.class);
activity.startActivity(rec1Intent);
AppView appView = new AppView();
appView.setParameters(appid, category);
AppList.adapter.notifyDataSetChanged();
}
});
final String id = applicationList.get(position).getId();
final String path = applicationList.get(position).getPath();
final String fileName = applicationList.get(position).getFileName();
final String name = applicationList.get(position).getName();
final String developer = applicationList.get(position).getDeveloper();
final double size = applicationList.get(position).getSize();
final String logo = applicationList.get(position).getLogo();
final int category = applicationList.get(position).getCategory();
final String appName = applicationList.get(position).getFileName();
String checkAppInstalled = appName.substring(0,appName.length() - 4);
//------------CHECK IF APPLICATION IS INSTALLED ----------------------------------------
if(appInstalled(checkAppInstalled))
{
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.VISIBLE);
holder.openInstalledAppBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String fileName = (applicationList.get(position).getFileName());
String appToOpen = fileName.substring(0,fileName.length() - 4);
Context ctx = activity.getApplicationContext();
Intent mIntent = ctx.getPackageManager().getLaunchIntentForPackage(appToOpen);
String mainActivity = mIntent.getComponent().getClassName();
Intent intent = new Intent("android.intent.category.LAUNCHER");
intent.setClassName(appToOpen, mainActivity);
activity.startActivity(intent);
}
});
}
//------------- IF APPLICATION IS NOT ALREADY INSTALLED --------------------------------
else
{
//------------------------ CHECK IF APK EXISTS -------------------------------------
String filePath = Environment.getExternalStorageDirectory().toString();
File file = new File(filePath + "/appsaraai/" + fileName);
if(file.exists())
{
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.VISIBLE);
holder.installBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/appsaraai/" + fileName)), "application/vnd.android.package-archive");
activity.startActivity(intent);
for (int i = 0; i < DownloadLists.list.size(); i++) {
if (DownloadLists.list.get(i).getName().equals(name)) {
DownloadLists.list.remove(i);
}
}
}
});
AppList.adapter.notifyDataSetChanged();
}
//------------------ IF APK DOES NOT EXIST -----------------------------------------
else
{
//-----CHECK IF DOWNLOAD IS IN PROGRESS ----------------------------------------
if (ApkFileDownloader.applicationList.containsKey(name))
{
holder.downloadBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
new ApkFileDownloader(activity).getDownloadStatus(holder.progressBar, name, holder.installBtn, holder.cancelBtn);
holder.progressBar.setVisibility(View.VISIBLE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
DownloadLists dlist = new DownloadLists(activity);
dlist.deleteData(name);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try
{
SearchResult.adapter.notifyDataSetChanged();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
});
}
//-------------- IF DOWNLOAD IS NOT IN PROGRESS START NEW DOWNLOAD -------------
else
{
holder.progressBar.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(view.VISIBLE);
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try {
SearchResult.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
}
});
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap logoImg = Picasso.with(activity).load(IPClass.SERVERIP + logo).get();
DownloadLists.list.add(new ApplicationPojo(id, name, developer, size, logoImg, holder.progressBar));
DownloadLists dlist = new DownloadLists(activity);
dlist.insertData(id, name, developer, size, fileName, logoImg);
UpdateServerDownload d = new UpdateServerDownload();
d.updateDownloadNo(id, category);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new ApkFileDownloader(activity).setParameters(path, fileName, name);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try {
SearchResult.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
}
});
}
}
}
holder.appName.setText(applicationList.get(position).getName());
holder.developer.setText(applicationList.get(position).getDeveloper());
String sizeText = " میگابایت ";
String appSize =String.valueOf(applicationList.get(position).getSize()) + sizeText;
holder.size.setText(appSize);
if(category == 1001)
{
String cat = applicationList.get(position).getgCat();
holder.appCat.setText(" " + returnGameCat(cat));
holder.catlogo.setImageResource(R.drawable.gamecatlogo);
}
}
catch (Exception ex)
{
Log.d("Adapter Exception", ex.toString());
}
return view;
}
//--------------- A METHOD TO CHECK IF APPLICATION IS ALREADY INSTALLED ------------------------
public boolean appInstalled(String checkApp)
{
pm = activity.getPackageManager();
try
{
pm.getPackageInfo(checkApp, PackageManager.GET_ACTIVITIES);
isAppInstalled = true;
}
catch (PackageManager.NameNotFoundException e)
{
isAppInstalled = false;
}
return isAppInstalled;
}
You are doing wrong in your GetItems and LoadMoreDataTask AsyncTask. you are setting new adapter each time when you scroll down so when new data are loaded to the view the scroll bar jumps to the top of the view.
You need to call
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
listview.setAdapter(adapter);
only first time then you have to only call
adapter.notifyDataSetChanged()
to update your ListView no need to set adapter each time when making new request and also you have to set OnScrollListener to ListView only one time currently new OnScrollListener is set each time when making new request.
You need to setAdapter first time when adapter is null or you are fetching data first time after it just call notifyDataSetChanged()
Save state of listview before updating and then restore:
// save index and top position
int index = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// notify dataset changed or re-assign adapter here
// restore the position of listview
mListView.setSelectionFromTop(index, top);
The most Optimal Solution will be
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();
// e.g. set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
Reference : Retain Scroll Position Android ListView