how to prevent the footerview show when pulltorefresh load all data? - android

I use pulltorefreshListview in my project, I set Mode.Both. I want the result when I pull from end for loading more,and scroll the end ,already load all data ,I hope the footerview hide. but now when I scroll the listview to end ,the footerview is showing, How can I for that?
private void pullRefresh() {
morelist.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
if (refreshView.isShownHeader()) {
//refresh
new GetDataTask().execute();
}else if (refreshView.isShownFooter()) {
//load more
number = number+20;
new GetDataTask().execute();
}
}
});
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
try {
if (isDown) {
getData(number,"-1");
} else {
getData(number,"1");
}
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
morelist.onRefreshComplete();
super.onPostExecute(result);
}
}

Related

AsyncTask to update ui counter which is invoked in other class in android

I need to update file upload count dynamically into Ui progressbar which is invoked in other class method. How can communicate between AsyncTask doInBackground() and myClass.uploadFiles(). please help me
this is activity
public class MyActivity extends AppCompatActivity {
private ProgressDialog dialog = null;
String status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
CounteTask task = new CounteTask();
task.execute();
}
private class CounteTask extends AsyncTask<String, Integer, Void> {
#Override
protected Void doInBackground(String... params) {
try {
status = myClass.uploadFiles(MyActivity.this);
} catch (Exception e) {
dialog.dismiss();
}
return null;
}
#Override
protected void onPostExecute(Void resultGetlogin) {
dialog.dismiss();
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Sync_Records.this, "", "Please wait, file count..");
}
protected void onProgressUpdate(Integer... values) {
}
}
}
MyClass.java from here need to update ui thread.
public void MyClass{
public static String uploadFiles(Context context) {
for (count=0 ; count <= 10; count++) {
try {
upload(count); //need to show each count of file which is currently uploading
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return status;
}

Recycleview pagination not bind adapter android

Hello friends i want to integrate pagination in my recycleview so below is my code
in onCreateVIew
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.task_recycle);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int current_page) {
if (OnzupApplication.mPendingDatas.size() < total) {
page++;
new getPendingTask(false,true).execute();
}
}
});
if (mAllMethods.check_Internet() == true) {
new getPendingTask(true,false).execute();
} else {
mAllMethods.ShowDialog(getActivity(), "", getString(R.string.net_not_available), "OK");
}
Call AsyncTask
public class getPendingTask extends AsyncTask<Void, Void, Void> {
private boolean showLoading;
boolean pagination;
public getPendingTask(boolean showLoading,boolean page) {
this.showLoading = showLoading;
this.pagination=page;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (showLoading == true) {
mProgressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.loading));
}
}
#Override
protected Void doInBackground(Void... voids) {
mGetPendigTask = (GetAllPendigTask) mPostParseGet.getPendingTask(mGetPendigTask, token, page);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (showLoading == true) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
}
try {
if (mPostParseGet.isNetError) {
mAllMethods.ShowNoConnectionDialog(mActivity, mContext, "", getString(R.string.net_not_available), getString(R.string.setting), getString(R.string.cancel));
} else if (mPostParseGet.isOtherError) {
if (!mPostParseGet.isRequestTimeOutError) {
new ActivityHelper(mActivity).sendMail(token);
}
mAllMethods.ShowDialog(mActivity, "", getString(R.string.data_not_found), "OK");
} else {
if (mGetPendigTask.isSuccess() == true) {
mPendingDatas = getData();
total = Integer.parseInt(mGetPendigTask.getTotalitems());
if (mGetPendigTask.getTasks().size() > 0) {
mTextViewNoData.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mAllPendingRecyclerAdapter = new AllPendingRecyclerAdapter(getActivity(), OnzupApplication.mPendingDatas);
if (pagination==false)
{
mRecyclerView.setAdapter(mAllPendingRecyclerAdapter);
}
mAllPendingRecyclerAdapter.notifyDataSetChanged();
} else {
mTextViewNoData.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
When i call above code 1 page is loaded but when i scroll second page data is not loaded any idea how can i solve this?
Because of this line
mAllPendingRecyclerAdapter = new AllPendingRecyclerAdapter(getActivity(), OnzupApplication.mPendingDatas);
You did create the Adapter at the first time, when you use load more function in recyclerview. You should add your data in your own Adapter instead of create the new one

Recyclerview Position changing to first position when I Update

I am using onLoadMoreListener when i scroll RecyclerView. It will update the RecyclerView data when you scroll to bottom. After updating the Recyclerview data. The Recyclerview goes back up to the top. Ideally, I would like to retain the position in the RecyclerView. Any thoughts on how I should go about doing this?
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
new GroupData().execute();
}
});
InnerClass
public static class GroupData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try{
GroupList gm = new GroupList();
.....
groupvalues.add(gm);
} catch (Exception e){
Log.d("Grouplist ", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mAdapter = new GroupAdapter(groupvalues,mrecyclerview);
mrecyclerview.setAdapter(mAdapter);
progressDialog.dismiss();
mAdapter.notifyDataSetChanged();
}
}
}
Try this,
public static class GroupData extends AsyncTask<Void, Void, Void> {
int size = 0;
#Override
protected void onPreExecute() {
size = groupvalues.size();
}
#Override
protected Void doInBackground(Void... voids) {
try {
GroupList gm = new GroupList();
.....
groupvalues.add(gm);
} catch (Exception e) {
Log.d("Grouplist ", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mAdapter.notifyItemRangeChanged(size, groupvalues.size() - size);
progressDialog.dismiss();
}
}
When you are loading you must be knowing the position of top element of new loaded items. just call:
recyclerView.scrollToPosition(position);
or just save the last know position of your recyclerView and Scroll to that position when you load more items
Just notify your adapter in onPostExecute. No need to initialise your adapter again.
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
mAdapter.notifyDataSetChanged();
}
Initialise your adapter in onCreate
mAdapter = new GroupAdapter(groupvalues,mrecyclerview);
mrecyclerview.setAdapter(mAdapter);

Android how to pass value from async task to fragment

In My Android Project I am using TabLayout,I have
Fragment1 --> Fragment2(AlertDialog)
|
button1--- name:
listview Id:
okButton--->AsyncTask
Here,In Fragment1 after pressing button1 calls another fragment(Fragment2), there after fillup the form pressing okbutton calls AsyncTask to receive data from server.then the data needs to display in Fragment1's
listview
My classes:
interface
public interface TaskCompleted {
// Define data you like to return from AysncTask
public void onTaskComplete(Integer result);
}
Fragment1
public class Fragment1 extends Fragment implements TaskCompleted {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
btn1 = (Button) view.findViewById(R.id.button1);
listview = (ListView) view.findViewById(R.id.listview);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment picker = new SearchFragment();
picker.show(getActivity().getFragmentManager(), "dialog");
}
});
return view;
}
public static void submit(final String serverResponse) {
#SuppressWarnings("unused")
final class DownloadJSON extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
try {
//code to process response
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
//display into adapter
}
}
}
}
Fragment2
public class Fragment2 extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View content = inflater.inflate(R.layout.dialog_fragment, null);
builder.setView(content);
builder.setMessage("form")
// Positive button
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new JSONfunctions(getActivity()).execute();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
#Override
public void onTaskComplete(String serverResponse) {
// TODO Auto-generated method stub
}}
AsyncTask
public class JSONfunctions extends AsyncTask<String, String, String> {
private TaskCompleted mCallback;
public JSONfunctions(Context context){
this.mContext = context;
this.mCallback = (TaskCompleted) context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String serverResponse="";
try {
====code to connect to server===
return serverResponse; (return result)
}
} catch (Exception e) {
e.printStackTrace();
}
return serverResponse;
}
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
mCallback.onTaskComplete(result);
}
}
and in MainActivity I also have
#Override
public void onTaskComplete(String serverResponse) {
Fragment2.submit(serverResponse);
}
With this code from fragment2 after pressing okbutton it calls asyncTask
and gets successfull response from server..but not displaying into listview..Why?????
Such a complex scenario implemented for such a simple task.
All you need to do is let the Fragment1 implement TaskCompleted interface and create AsyncTask in a separate class and make an attribute of TaskCompleted in this task.
When in onPostExecute just call the listener function and one thing more you have to pass the fragment reference to your async task while creating its object in constructor.
final class DownloadJSON extends AsyncTask<String, String, Void> {
//your attributes
TaskCompleted listener;
public DownloadJSON(TaskCompleted listener){
this.listener = listener;
}
#Override
protected Void doInBackground(String... params) {
try {
jsonarray = new JSONArray(serverResponse);
Gson gson = new Gson();
User[] user = gson.fromJson(jsonarray.toString(), User[].class);
// Contact con = new Contact();
for (int i = 0; i < user.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", user[i].getFullname());
map.put("id", user[i].getId());
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listener.onTaskCompleted(arraylist);
}
}
public class Fragment1 extends Fragment implements TaskCompleted {
#Override
public void onTaskComplete(ArraList<YourListModel> data) {
adapter = new ListViewAdapter(activity, data);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
Also apply null checks where necessary.

Method that returns a value based on an asynchronous call

My program needs to take in a user's name as a String, and makes a call to the API to see if it exists. I made a method that takes in that string, and executes an async task to send the API call. But it looks like the comparison in my method is being executed before my async task finishes. What is the proper way to implement something like this
public boolean checkUser(String name) {
checkedName = name;
checkValidSummoner check = new checkValidSummoner();
check.execute();
if (checkedName == null) {
return false;
} else {
return true;
}
}
private class checkValidSummoner extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... strings) {
try {
checkedName = RiotAPI.getSummonerByName(checkedName).toString();
} catch (APIException e) {
checkedName = null;
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
}
}
You can't do that.
Please use listener.
public boolean checkUser(String name, OnCheckValidEndListener listener) {
checkedName = name;
checkValidSummoner check = new checkValidSummoner(listener);
check.execute();
}
public interface OnCheckValidEndListener {
void onCheckValidEnd(String checkedName);
}
private class checkValidSummoner extends AsyncTask<String, Void, Void> {
private final OnCheckValidEndListener listener;
checkValidSummoner(OnCheckValidEndListener listener) {
this.listener = listener;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... strings) {
try {
checkedName = RiotAPI.getSummonerByName(checkedName).toString();
} catch (APIException e) {
checkedName = null;
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
listener.onCheckValidEnd(checkedName);
}
}
And please use flowing code
checkUser("jon",new OnCheckValidEndListener() {
#Override
public void onCheckValidEnd(String checkedName) {
if (checkedName == null) {
// invalid
} else {
// valid
}
}
});

Categories

Resources