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.
Related
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;
}
I'm new to this concept. I read several threads but I block so thanks in advance for your patience!
In a fragment (frag1) I launch an async task. I want to prevent the user of doing anything while the task is not completed so I want to communicate the % of the task completed so the user waits informed.
I've defined an interface in a java SetVal.java:
interface SetVal {
void setVal(int val);
}
My async task:
class AsyncCounter extends AsyncTask<Void, Integer, Void> {
private SetVal sender;
public AsyncCounter(SetVal sv){
this.sender = sv;
}
#Override
protected Void doInBackground(Void... params) {
for(int i=0;i<60;i++){
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
Log.i("ASYNC TASK","val: "+values[0]);
sender.setVal(values[0]);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
public interface SetVal {
public void setVal(int val);
}
public void setListener(SetVal listener) {
this.sender = listener;
}
}
I'm struggling to know how to pass the interface to the task.
Is my code correct?
How do I instantiate the async task?
fragment:
public class Frag1 extends android.app.Fragment implements SetVal {
private static TextView txt;
private int counter;
SetVal listener;
public Frag1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_frag1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt = (TextView) getActivity().findViewById(R.id.txt);
Button btn = (Button) getActivity().findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("Frag1", "val: " + counter);
if (counter > 0) return;
FragmentTransaction ft = getFragmentManager().beginTransaction();
Frag2 f2 = new Frag2();
ft.replace(R.id.content_frame, f2);
ft.addToBackStack("f2");
ft.commit();
}
});
Button btn2 = (Button) getActivity().findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncCounter ac = new AsyncCounter(???????);
ac.execute();
}
});
}
#Override
public void setVal(int val) {
counter = val;
}
}
Not sure what and why you are trying to do that, but you can pass the Fragment :
Try to create a private method:
public void onClick(View v) {
startMyAsync();
}
private void startMyAsync() {
new AsyncCounter(this).execute();
}
finally:
public AsyncCounter(Frag1 context){
this.sender = (SetVal)context;
}
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);
}
}
public class MyFragment extends Fragment implements OnClickListener {
EditText et;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(
R.layout.MyFragment, container, false);
et = (EditText) mLinearLayout.findViewById(R.id.etet);
submit = (Button) mLinearLayout.findViewById(R.id.bsubmit);
submit.setOnClickListener(this);
return mLinearLayout;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bsubmit:
new processet().execute();
break;
}
}
private class processet extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
String text = et.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = null;
Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show();
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
}
}
}
Why is this code not working ?
I have checked that the button onClickListener is working fine..
this is just a simple code , I don't know why it is not working..
I think there must be some changes required so that ASyncTask can work inside the fragment..
private class processet extends AsyncTask<Void, Void, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Show pDialog
}
#Override
protected JSONObject doInBackground(Void... args) {
String text = et.getText().toString();
UserFunctions userFunction = new UserFunctions();
return new jsonObject();
}
#Override
protected void onPostExecute(JSONObject json) {
//dismiss pDialog;
Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show();
}
}
I have ListView with items containing a Button among others. I start an Asynctask from the Adapter class of the ListView:
holder.btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Follow_Async().execute(arr_id.get(position), arr_name.get(position));
}
}
});
This is my Asynctask:
public class Follow_Async extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
//here
Toast.makeText(Activity_Followers2.this, "You are now following " + result, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
try {
params_follow = new ArrayList<NameValuePair>();
params_follow.add(new BasicNameValuePair("session_userid", session_userid));
params_follow.add(new BasicNameValuePair("friend_userid", params[0]));
JSONParser jsonParser; jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(add_follow, "POST", params_follow);
} catch (Exception e) {
e.printStackTrace();
}
return params[1];
}
}
In the PostExecute() I want to change the text of the Button I have just clicked to Unfollow. How can I access it from there?
Just pass your button as a parameter to the AsyncTask constructor:
In the adapter:
final thisButton = holder.btn_follow; // <------------ add a final Button field
thisButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Follow_Async(thisButton). //<------------- pass button to AsyncTask
execute(arr_id.get(position), arr_name.get(position));
}
}
});
And in the AsyncTask:
class Follow_Async extends AsyncTask<String, Void, String> {
private final Button button;
public Follow_Async(Button button) { //<------------- pass button to constructor
this.button = button;
}
#Override
protected void onPostExecute(String result) {
this.button.setText(""); //<--------------- do something with button
}
}