why my asynctask not working within fragment? - android

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

Related

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: ProgressDialog not shown with AsyncTask

I'm trying to display a ProgressDialog in my Activity while I'm executing a task with AsyncTask. Here my code below.
My problem is that onPreExecute() is called (I checked it with print) but my progressDialog is not shown while my function sendRequest is executed in doInBackground(..). I don't understand what it happens and I don't know how to solve that. I googled it but I didn't find any suitable solution. If you have any idea it would be great for me.
private static Activity activity;
private static ProgressDialog dialog;
public MyClass(Activity activity){
this.activity = activity;
}
public static String sendRequest(String request){
//do something
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(activity,
"ProgressDialog",
"Wait!");
}
#Override
protected String doInBackground(String... params) {
String result = sendRequest(params[0]);
return result;
}
#Override
protected void onPostExecute(final String result) {
dialog.dismiss();
}
Try:
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("title");
progressDialog.setMessage("message");
progrsesDialog.show();
Try this
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(CardPaymentActivity.this,
"Progress", "please wait...");
}
#Override
protected String doInBackground(String... params) {
publishProgress("sleep time..."); // Calls onProgressUpdate()
return null;
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(String... text) {
}
}
and call AsyncTaskRunner class in your activity class like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_payment);
AsyncTaskRunner myTask = new AsyncTaskRunner();
myTask.execute();
}

why method onPostExecute on asynctask is never called

I tried to dismiss(); progressbar dialog when the load by using a method onPostExecute in webview when finished process.
my problem is when i run onPostExecute method in AsynTask is never executed ?
Note : i've read
public class MainActivity extends AppCompatActivity {
WebView webView;
EditText edInput;
Button btnCari;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
edInput = (EditText) findViewById(R.id.editText);
btnCari = (Button) findViewById(R.id.button);
btnCari.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
asynCaller myTask = new asynCaller();
myTask.execute();
}
});
}
private void loadWeb(String url){
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://"+url);
}
public class asynCaller extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
url = edInput.getText().toString();
progressDialog.show(MainActivity.this,"Pesan","Memuat . . .",true);
}
#Override
protected String doInBackground(String... params) {
publishProgress();
return url;
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
loadWeb(url);
}
}
}

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.

Access custom ListView object from outside

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

Categories

Resources