Android thread finished callback - android

I want execute http post after getting response from server.
If server response is false the http post will execute else not execute.
How can i do for this.
My android main activity code:
if (Utility.isValidMobile(mobileNumber)) {
String isAvailable = userDelegate.checkUser(mobileNumber, context);
if (isAvailable.equals("false")) {
userDelegate.addUser(userMO, context);
Toast.makeText(getApplicationContext(), "Your mobile number is" + mobileNumber + "name is" + userName, Toast.LENGTH_LONG).show();
} else if (isAvailable.equals("true")) {
Toast.makeText(getApplicationContext(), "Your mobile number is already registerd", Toast.LENGTH_LONG).show();
}
}
when i click signup button this above code will executed
My Userdelegate class code :
public void addUser(final UserMO userMo, final Context context) {
final String jsonStringObject = gson.toJson(userMo);
Thread t = new Thread() {
public void run() {
Looper.prepare(); // for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userBO", jsonStringObject));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/addUser");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Toast.makeText(context, "Your user id " + rd.readLine(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
}
public void getMatchingExistingUserList(final String mobile_number, final Context context) {
final String jsonStringObject = gson.toJson(mobile_number);
Thread t = new Thread() {
public void run() {
Looper.prepare(); // for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userBO", jsonStringObject));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/addUser");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
final String responseString = rd.readLine();
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
}
public String checkUser(final String mobile_number, final Context context) {
final StringBuilder isAvailable = new StringBuilder();
Thread t = new Thread() {
#Override
public void run() {
Looper.prepare(); // for the child Thread
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("MobileNumber", gson.toJson(mobile_number)));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/checkUserMobileNumber");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
isAvailable.append(rd.readLine());
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
return isAvailable.toString();
}
Problem is i got response false but the if condition not working.
how to solve this problem.
After changing:
if (Utility.isValidMobile(mobileNumber)) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.checkUser(mobileNumber, context);
}
#Override
protected void onPostExecute(String isAvailable) {
Toast.makeText(getApplicationContext(), isAvailable, Toast.LENGTH_LONG).show();
if (isAvailable.equals("false")) {
Toast.makeText(getApplicationContext(), "Your mobile number is" + mobileNumber + "name is" + userName, Toast.LENGTH_LONG).show();
userDelegate.addUser(userMO, context);
} else if (isAvailable.equals("true")) {
Toast.makeText(getApplicationContext(), "Your mobile number is already registerd", Toast.LENGTH_LONG).show();
}
}
}.execute(null, null, null);
}
The if condition is not working ?

If server response is false the http post will execute else not
execute. How can i do for this
Issue occurring because you are using Threads in checkUser and addUser. Thread's execute with-out stopping execution of current Thread.
For example, when checkUser method is called from main thread then final StringBuilder isAvailable = new StringBuilder(); executing on main thread and Thread t is executing in separately. so system return control to next line which is return isAvailable.toString(); without waiting Thread execution complete means checkUser method always return null or empty string.
Same is for addUser method.
To do task accoding to result of checkUser method response use AsyncTask class.

You are using new threads to do http request here. Therefore your delegate methods are not synchronized. addUser and checkUser will return before your http requests finish.
To write multi thread codes like yours, you may want to use a some kind of a listener to do the threads communication work.
For example, you can pass a listener to your delegate which looks like this
class Listener{
private Handler handler = new Handler();
public void onUserAdded(){
handler.post(new Runnable(){
public void run(){
// Toast your thing
}
});
}
public void onUserChecked(final boolean available){
handler.post(new Runnable(){
public void run(){
if(available){
// Toast your thing
}else{
userDelegate.addUser(userMO, context);
}
}
});
}
}
And all your new Thread(){ run(){ codes should end with all call to the listener.
As you can see I use a Handler to post works back to the UI thread. This is very important for you to notify your UI elements of what is going on in your none-UI threads.
Also, I can't see what you are doing with your Looper.prepare() and Looper.loop(). No child thread is there.

Related

Could not get the value from Edit Text element

Fantastic morg. Below this code to get data from mysql database and displayed into the EditText element.There is no problem with getting data from db its working good using this asyn tesk new checkUserPermission().execute("");.
Problem is
I want to make some calculation from code and dispaly in another Edittext. so i need values thats why i get data from db.while OnCreate() to get the data from db(its working). whenever i call this calculatePL(); method i could not get value.
LOGCAT:
System.out: Empty Value
Why its empty or something. but above my edittext elements hold the
values.
...some declaration of variables and etc....
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.five_activity);
new checkUserPermission().execute(""); //call here
calculatePL();//call the method
}
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
String[] splited = Allvalues.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
//Log.d("Splited String ", "Splited String" + totalamt+expen);
runOnUiThread(new Runnable() {
#Override
public void run() {
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
}
});
Log.i("TAG", "Result Retrieved");
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
// Close progress dialog
Dialog.dismiss();
}
}
public void calculatePL(){
try {
String a_value =totamt.getText().toString().trim();
System.out.println(a_value);
}catch(NumberFormatException numberEx)
{
System.out.println(numberEx);
}
}
Your checkUserPermission executes in background. And immediately you are calling calculatePL() so your main thread is not waiting for checkUserPermission execution to complete.
What you need to do is, make wait your main thread so that after full execution of checkUserPermission calculatePL() will get called. You can achieve it by adding ProgressDialog. Show the ProgressDialog in onPreExecute() and dismiss it in onPostExecute()
Hope it will do your job.
Override protected void onPostExecute in your asyncTask and call calculatePl() here. And you should set Edittext's text in onPostExecute too, because this method is main thread and you don't need to use runOnUIThread.
EDIT with example code:
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return Allvalues;
}
protected void onPostExecute(String result){
String[] splited = result.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
// Close progress dialog
Dialog.dismiss();
calculatePL();
}
}
Make sure totamt is declared as a global. Try logging the value of totamt or an object of the same. Finally check where you have declared it.

How to Update UI from Non-UI thread in android?

I have a Login Fragment that execute AsynkTask and in onPost() I want to update Login Fragment UI .I am already done that need some correction in That.How can I make non-ui thread.
here is my code:-
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.login_screen, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
CMainActivity.m_Drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
m_oLoginSession = new CLoginSessionManagement(getActivity());
init();// initialize controls
return m_Main;
}
public void init() {
m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);
m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);
m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
m_ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
}
});
m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
}
});
m_LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAttempt().execute();
}
});
}
private class LoginAttempt extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
// and now the magic
pDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
pDialog.getWindow().setGravity(Gravity.BOTTOM);
pDialog.getWindow().getAttributes().verticalMargin = 0.5f;
pDialog.show();
// CProgressBar.getInstance().showProgressBar(getActivity(), "Please wait while Logging...");// showing progress ..........
}
#Override
protected String doInBackground(String... params) {
getLoginDetails();// getting login details from editText...........
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
isFirstLogin = true;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(s_szLoginUrl);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szPassword);
jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
// httpPost.setHeader("Accept", "application/json"); ///not required
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null) {
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
}
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return s_szresult;
}
#Override
protected void onPostExecute(final String response) {
super.onPostExecute(response);
m_Handler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
m_Handler.post(new Runnable() {
#Override
public void run() {
CProgressBar.getInstance().hideProgressBar();// hide progressbar after getting response from server......
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
getResponse();// getting response from server ........
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}
public void getResponse() throws JSONException {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
CToastMessage.getInstance().showToast(getActivity(), "You are successfully Logged In");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
CToastMessage.getInstance().showToast(getActivity(), "Please Enter Valid Mobile Number");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
CToastMessage.getInstance().showToast(getActivity(), "Please Enter Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
CToastMessage.getInstance().showToast(getActivity(), "Please enter correct Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
CToastMessage.getInstance().showToast(getActivity(), "You are blocked as You finished your all attempt");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
CToastMessage.getInstance().showToast(getActivity(), "Connection Lost ! Please Try Again");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
CToastMessage.getInstance().showToast(getActivity(), "User not found ! Kindly Regiter before Login");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {
CToastMessage.getInstance().showToast(getActivity(), "Otp not Verify ! Kindly Generate Otp on Sign Up");
}
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
}
}
Move the code that is in a thread in onPostExecute() to doInBackground() because this is running in other thread and them refresh you UI in onPostExecute()
A mock example:
#Override
protected String doInBackground(String... params) {
//RUN ALL THAT YOU WANT IN A DIFFERENT THREAD
}
#Override
protected void onPostExecute(final String response) {
//REFRESH THE UI
}
If you are using AsynkTask, you can have a try on onPreExecute and onPostExecute methods that both runs on the UI thread.
Or you can use a handler to update UI.
In your UI thread create an object of Handler like this
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
//Update UI here
//use msg.obj if you have sent Object from background thread
//use msg.what if you have sent Integer from background thread
//Update UI if you have just trigger the handler using sendEmptyMessage(your UI/View gets data from Global Variable)
}
};
Two ways we can trigger Hanler which is created in UI thread
1)handler.sendMessage(Message);
2)handler.sendEmptyMessage(0);
Inside on postExecute of your AsyncTask write below Code based on your requirement
//Message msg=Message.obtain();
//msg.obj=YourObject;//If you want to pass Object
//msg.what=Integer;//If you want to pass Integer
//handler.sendMessage(msg);//to send Message objectdefined above
handler.sendEmptyMessage(0);//If you simply want to trigger

How to run AsyncTask every X second in Android Studio?

I'm executing AsyncTask that fetch data from my web host. In order for me to retrieve data, I need to re-open my app. How can I fetch data every second? I know that AsyncTask could only be executed once, but I needed it not only for my app but also to learn about this problem. Hope to learn from you guys.
By the way this is my code:
class AsyncDataClass2 extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", params[1]));
nameValuePairs.add(new BasicNameValuePair("password", params[2]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
if (result.equals("") || result == null)
{
Toast msg = Toast.makeText(MapsActivity.this, "connection failed", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, 0, 0);
msg.show();
}
else
{
Toast msg = Toast.makeText(MapsActivity.this, "connected", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER,0,0);
msg.show();
}
try {
JSONArray json = new JSONArray(result);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String point = e.getString("Point");
String[] point2 = point.split(",");
String devStatus = e.getString("Status"); //now, let's process the Status...
String strOwner = e.getString("Owner"); //now, let's process the owner...
//==============================================================================
if (devStatus.equals("fire")) {
IsThereFire=true;
}
} //---End of FOR LOOP---//
}//---end of TRY---//
catch (JSONException e)
{
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is)
{
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try
{
while ((rLine = br.readLine()) != null)
{
answer.append(rLine);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
EDIT:
Sir, this is the timer I used..
///---CODE for the TIMER that ticks every second and synch to database to update status---///
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// HERE IS THE ACTUAL CODE WHERE I CALL THE ASYNCDATACLASS2
AsyncDataClass2 performBackgroundTask = new AsyncDataClass2();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
//---------------------------------------------------------------//
if you need to execute a task at fixed interval of time you can use a Timer with a TimerTask. It runs on different thread than the UI thread, meaning that you can run your http call directly in it. You can find the documentation here
I think you should try to use TimerTask or a job scheduler.
Lots of information about job schedulers can be found here and here.
Check this:
Timer timer;
private void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
new AsyncDataClass2 adc = new AsyncDataClass2("u","p");
adc.execute();
}
}, 0, 1000);
}
Then in onCreate() you write:
startTimer();
Although, you should consider others comments, they're meaningful, requesting updates from web server every second in AsyncTask, it's not so good thing to do.
I do not think that's a really good idea to proceed like this but you can do it, of course with an simple TimerTask (tutorial there)
Basically, it would look like this:
public class MyTimerTask extends TimerTask {
#Override
public void run() {
// Just start your AsyncTask and proceed, I didn't adapt the code to your task
new AsyncDataClass2().execute()
}
}
Your Logic calls it:
TimerTask timerTask = new MyTimerTask();
// They're ms: 1000ms = 1s
timer.scheduleAtFixedRate(timerTask, 0, 1000);
timer.start();
You cancel it when you destroy your Fragment/Activity
timer.cancel();

Android Login with HTTP post, get results

I am trying to create a Login function so i can verify the users. I pass the Username , Password variables to AsyncTask class but i don't know hot to get results in order to use them. Any help? (I am posting part of the source code due to website restrictions)
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(txtUsername.getText().toString().trim().length() > 0 && txtPassword.getText().toString().trim().length() > 0)
{
// Retrieve the text entered from the EditText
String Username = txtUsername.getText().toString();
String Password = txtPassword.getText().toString();
/*Toast.makeText(MainActivity.this,
Username +" + " + Password+" \n Ready for step to post data", Toast.LENGTH_LONG).show();*/
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
new PostDataAsyncTask().execute(params);
// Redirect to dashboard / home screen.
login.dismiss();
}
else
{
Toast.makeText(MainActivity.this,
"Please enter Username and Password", Toast.LENGTH_LONG).show();
}
}
});
Then i use the AsynkTask to do the check but do not know how to get the results and store them in a variable. Any help?
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... params) {
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
String line = null;
String fail = "notok";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
line = resEntity.toString();
Log.v(TAG, "Testing response: " + line);
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
Intent Hotels_btn_pressed = new Intent(MainActivity.this, Hotels.class);
startActivity(Hotels_btn_pressed);
// you can add an if statement here and do other actions based on the response
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}else{
finish();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
Not the best code refactoring, but just to give you a hint.
I would create an interface (lets call it 'LogInListener'):
public interface LoginListener {
void onSuccessfulLogin(String response);
void onFailedLogin(String response);
}
The 'MainActivity' class would implement that interface and set itself as a listener the 'PostDataAsyncTask'. So, creating the async task from the main activity would look like this:
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
PostDataAsyncTask postTask = new PostDataAsyncTask(this);
postTask.execute(params);
I would move 'PostDataAsyncTask' class into a new file:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
private static final String ERROR_RESPONSE = "notok";
private LoginListener listener = null;
public PostDataAsyncTask(LoginListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
String postResponse = "";
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
postResponse = EntityUtils.toString(resEntity).trim();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
#Override
protected void onPostExecute(String postResponse) {
if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
listener.onFailedLogin(postResponse);
} else {
listener.onSuccessfulLogin(postResponse);
}
}
}
So, 'doInBackground' returns the response to 'onPostExecute' (which runs on the UI thread), and 'onPostExecute' routes the result (success or failure) to the MainActivity, which implements the 'LogInListener' methods:
#Override
public void onSuccessfulLogin(String response) {
// you have access to the ui thread here - do whatever you want on suscess
// I'm just assuming that you'd like to start that activity
Intent Hotels_btn_pressed = new Intent(this, Hotels.class);
startActivity(Hotels_btn_pressed);
}
#Override
public void onFailedLogin(String response) {
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}
I just assumed that that's what you wanted to do on success: start a new activity, and show a toast on fail.

Can't show Toast inside AsyncTask inside a DialogFragment

I'm using a DialogFragment to show a simple form, which then is posted to a remote server and a success/fail code is sent back.
However whenever I want to show a Toast when an error occurred I get an exception in which getActivity() returns null. Any idea why this is?
This is a summary of the code:
private class UploadNewGroupToServer extends AsyncTask<String, Void, Void>
{
ProgressDialog createGroupProgressDialog;
#Override
protected Void doInBackground(String... params)
{
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
createGroupProgressDialog = new ProgressDialog(getActivity());
createGroupProgressDialog.setTitle("Creating group...");
createGroupProgressDialog.show();
}
});
String encodedImage = params[0];
String groupTitle = params[1];
String groupDesc = params[2];
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_API_CREATE_GROUP);
try
{
// Add data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(encodedImage != null)
{
nameValuePairs.add(new BasicNameValuePair("picture", encodedImage));
}
nameValuePairs.add(new BasicNameValuePair("title", groupTitle));
nameValuePairs.add(new BasicNameValuePair("desc", groupDesc));
nameValuePairs.add(new BasicNameValuePair("token", "MY_TOKEN_HERE!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Log.d("APP", "Going to execute ");
final String responseBody = httpclient.execute(httppost, responseHandler);
Log.d("APP", "Back from execute, responseBody is " + responseBody);
//More business logic here
// . . . . .
throw new Exception(); //simulate an error
} catch (final Exception e)
{
Log.d("APP", "Exception es " + e.getMessage());
createGroupProgressDialog.dismiss();
getActivity().runOnUiThread(new Runnable() //App dies here!
{
public void run()
{
Toast.makeText(getActivity(), "Error!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
Here's the logcat:
11-04 00:16:18.414: E/AndroidRuntime(7229): Caused by: java.lang.NullPointerException
11-04 00:16:18.414: E/AndroidRuntime(7229): at com.myapp.android.GroupCreateDialogFragment$UploadNewGroupToServer.doInBackground(GroupCreateDialogFragment.java:204)
11-04 00:16:18.414: E/AndroidRuntime(7229): at com.myapp.android.GroupCreateDialogFragment$UploadNewGroupToServer.doInBackground(GroupCreateDialogFragment.java:1)
11-04 00:16:18.414: E/AndroidRuntime(7229): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-04 00:16:18.414: E/AndroidRuntime(7229): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-04 00:16:18.414: E/AndroidRuntime(7229): ... 4 more
When you invoke asynctask use
new UploadNewGroupToServer(getActivity()).execute();.
Now in the constructor
Context mContext;
pulic void UploadNewGroupToServer(Context context)
{
mContext = context;
}
Also move your progressdialog initialization to the constructor
pulic void UploadNewGroupToServer(Context context)
{
createGroupProgressDialog = new ProgressDialog(context);
createGroupProgressDialog.setTitle("Creating group...");
}
In onPreExecute
public void onPreExecute()
{
super.onPreExecute();
createGroupProgressDialog.show();
}
Also instead of displaying toast in doInbackground return result and in onPostExecute dismiss dialog and show toast accordingly.
Could your create a handler in your async task? If handler created in UI thread(If use MainLooper) post method samely runOnUiThread.
private class UploadNewGroupToServer extends AsyncTask<String, Void, Void>
{
ProgressDialog createGroupProgressDialog;
Handler handler;
protected void onPreExecute(){
handler = new Handler();
}
#Override
protected Void doInBackground(String... params)
{
handler.post(new Runnable()
{
public void run()
{
createGroupProgressDialog = new ProgressDialog(getActivity());
createGroupProgressDialog.setTitle("Creating group...");
createGroupProgressDialog.show();
}
});
String encodedImage = params[0];
String groupTitle = params[1];
String groupDesc = params[2];
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_API_CREATE_GROUP);
try
{
// Add data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(encodedImage != null)
{
nameValuePairs.add(new BasicNameValuePair("picture", encodedImage));
}
nameValuePairs.add(new BasicNameValuePair("title", groupTitle));
nameValuePairs.add(new BasicNameValuePair("desc", groupDesc));
nameValuePairs.add(new BasicNameValuePair("token", "MY_TOKEN_HERE!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Log.d("APP", "Going to execute ");
final String responseBody = httpclient.execute(httppost, responseHandler);
Log.d("APP", "Back from execute, responseBody is " + responseBody);
//More business logic here
// . . . . .
throw new Exception(); //simulate an error
} catch (final Exception e)
{
Log.d("APP", "Exception es " + e.getMessage());
createGroupProgressDialog.dismiss();
handler.post(new Runnable() //App dies here!
{
public void run()
{
Toast.makeText(getActivity(), "Error!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}

Categories

Resources