Access custom ListView object from outside - android

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
}
}

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;
}

Getting error while clicking on the button on which I am calling Async task? [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
Here is my code in which on clicking I am calling AttemptLogin method.
class NewActivity extends AppCompatActivity implements View.OnClickListener {
EditText editEmail, editPassword, editName;
Button btnSignIn, btnRegister;
private ProgressDialog pDialog;
String URL= "https://xyz/restapi/registration";
JSONParser jsonParser=new JSONParser();
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegister=(Button)findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(this);
/*btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin= new AttemptLogin();
attemptLogin.execute(editName.getText().toString(),editPassword.getText().toString(),"");
}
});*/
/*btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AttemptLogin().execute();
}
});*/
}
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewActivity.this);
pDialog.setMessage("Attempting for registering...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
ArrayList params = new ArrayList();
params.add(new BasicNameValuePair("cust_firstname", "Sai"));
params.add(new BasicNameValuePair("cust_lastname", "Kumar"));
params.add(new BasicNameValuePair("cust_phoneno", "9989219692"));
params.add(new BasicNameValuePair("cust_confirmpass", "Sai#123"));
params.add(new BasicNameValuePair("cust_pass", "Sai#123"));
params.add(new BasicNameValuePair("cust_username", "sai#gmail.com"));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(),result.getString("message"),Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
on button click i want to post data directly but getting error as
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
If there are any nice tutorials for registering details for Async task means please let me know.
#Override
public void onClick(View v) {
switch(v.getId){
case R.id.button:
new AttemptLogin().execute();
}
}
try this one
The id of the button is correct? It corresponds with the id in XML layout?
Use in onCreate:
btnRegister.setOnClickListener(btnLoginClick);
Then, out of the onCreate declare method:
private View.OnClickListener btnLoginClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
...
//write your code
}
};
Try this out.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnRegister:
new AttemptLogin().execute();
break;
default:
break;
}
}
The official Android Developer site should be your closed friend. Make sure you read this:
https://developer.android.com/reference/android/os/AsyncTask

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.

why my asynctask not working within fragment?

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();
}
}

Use the same AsyncTask to update different views

I have a button on 6 different Activities. Clicking on that button does almost the same task with different params depending on the Activity.
This will be done using an AsyncTask and in onPostExecute() the button state will be changed.
someButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Task().execute("param1", "param2");
}
}
private class Task extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//background task using params[0], params[1]
return "success" or "error";
}
#Override
protected void onPostExecute(String result) {
if (result == "success") {
//change the someButton state
}else{
//show an error message
}
}
Instead of having the same AsyncTask in all the 6 Activities, how can I use a single Asynctask from all the Activities and change the respective view?
You should create Task, with methods onSuccess, onFailure and override them.
public class Task extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//background task using params[0], params[1]
return "success" or "error";
}
#Override
protected void onPostExecute(String result) {
if (result == "success") {
onSuccess(result);
}else{
onFailure(result);
}
}
protected void onSuccess(String result) {};
protected void onFailure(String result) {};
}
and then in activity use it like this:
someButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Task(){
#Override
protected void onSuccess(String result){
// do what you want
}
#Override
protected void onFailure(String result){
// do what you want
}
}.execute("param1", "param2");
}
}
Put your Task in its own file and make it public.
Create a callback interface:
public interface TaskCallback {
public void onSuccess(String result);
public void onFailure(String errorMessage);
}
Give such a callback to your Task:
public class Task extends AsyncTask<String, Void, String> {
private TaskCallback callback;
public Task(TaskCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(String... params) {
//background task using params[0], params[1]
return "success" or "error";
}
#Override
protected void onPostExecute(String result) {
if (result == "success") {
callback.onSuccess(result);
} else{
callback.onFailure(errorMessage);
}
}
}
And then implement the callback when creating the Task instance in your activity:
someButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
private TaskCallback callback = new TaskCallback() {
#Override
public void onSuccess(String result) {
//change the someButton state
}
#Override
public void onFailure(String errorMessage) {
//show an error message
}
}
new Task(callback).execute("param1", "param2");
}
}

Categories

Resources