I am fetching data from server using AsynkTask which works fine but I want to use handler in AsynkTask to reduce load from main Thread.How can I use Handler in AsynkTask. Kindly help me to solve this problem.
Here is my code.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://192.168.0.999:8080/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
#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();
m_oLoginSession = new CLoginSessionManagement(getActivity());
init();
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.setBackgroundColor(Color.TRANSPARENT);
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> {
public Dialog m_Dialog;
public ProgressBar m_ProgressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_Dialog = new Dialog(getActivity());
m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
m_Dialog.setContentView(R.layout.progress_bar);
showProgress("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());
}
System.out.println("s_szResult....." + s_szresult);
System.out.println("password......" + s_szPassword);
// 11. return s_szResult
return s_szresult;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
hideProgress();// 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();
}
}
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();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
showToast("Please Enter Valid Mobile Number");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
showToast("Please Enter Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
showToast("Invalid Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
showToast("You are blocked as You finished you all attempt");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
showToast("Connection Lost ! Please Try Again");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
showToast("User not found ! Kindly Regiter before Login");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {
showToast("Otp not Verify ! Kindly Generate Otp on Sign Up");
}
}
public void showToast(String message) {// method foe showing taost message
Toast toast = Toast.makeText(getActivity(), "" + message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
public void showProgress(String message) {
m_ProgressBar = (ProgressBar) m_Dialog.findViewById(R.id.progress_bar);
TextView progressText = (TextView) m_Dialog.findViewById(R.id.progress_text);
progressText.setText("" + message);
progressText.setVisibility(View.VISIBLE);
m_ProgressBar.setVisibility(View.VISIBLE);
m_ProgressBar.setIndeterminate(true);
m_Dialog.setCancelable(false);
m_Dialog.setCanceledOnTouchOutside(false);
m_Dialog.show();
}
public void hideProgress() {
m_Dialog.dismiss();
}
}
}
As per android docs here
An asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
And loading data from URL with Handler is not a good thing. Instead use Executor or ThreadPoolExecutor to do heavy background tasks.
You Can Use
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getResponse();
}
});
you can do like this:
class MyAsyncTask extends AsyncTask<Object,Object,Object>{
Private Context c;
private Handler handler;
private final static int YOUR_WORK_ID = 0x11;
public MyAsyncTask(Context c,Handler handler){
this.c = c;
this.handler = handler;
}
protected Object doInBackground(Object... params){
//do your work
...
Message m = handler.obtainMessage();
m.what = YOUR_WORK_ID;
...
handler.sendMessage().sendToTarget();
}
}
And in your fragment ,you can init a handler as params to MyAsyncTask,and deal with you work in handleMessage();
Related
I have a Otp verification Screen in which I have a progress bar with timer ,what I want is to dismiss this progressbar once Read Otp from inbox if read successfully from Inbox then dismiss progressbar and execute Jsons Url if not then show progressbar with timer until not read sms from Inbox.for this I am using Broadcast Receiver .Kindly help me .
here is my code of MainActivity :-
public class COtpAutoVerificationScreen extends Fragment {
private static String s_szResult = "";
private final String m_szOTPVERIFICATIONURL = "http://202.131.144.132:8080/resting/rest/json/metallica/validateOTPInJSON";
public ProgressBar pb;
private View m_Main;
private int m_n_ProgressStatus = 0;
private CRegistrationSessionManagement m_oSessionManagement;
private String m_szMobileNumber;
private String m_szEncryptedPassword;
private CircularProgressView m_ProgressView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.otp_auto_verified, container, false);
getUserDetails();// getuser deatails....
init();// initialize controls...
return m_Main;
}
private void getUserDetails() {
m_oSessionManagement = new CRegistrationSessionManagement(getActivity());
}
private void init() {
m_ProgressView = (CircularProgressView) m_Main.findViewById(R.id.progress_view);
m_ProgressView.startAnimation();
m_ProgressView.setVisibility(View.GONE);
pb = (ProgressBar) m_Main.findViewById(R.id.pb);
final TextView tv = (TextView) m_Main.findViewById(R.id.tv);
#SuppressWarnings("UnusedAssignment") final TextView validationText = (TextView) m_Main.findViewById(R.id.validatingmessage);
tv.setText("00:00");
//Initialize a new CountDownTimer instance
long m_MillisInFuture = 30000;
long m_CountDownInterval = 1000;
new CountDownTimer(m_MillisInFuture, m_CountDownInterval) {
public void onTick(long millisUntilFinished) {
#SuppressWarnings("UnusedAssignment") long millis = millisUntilFinished;
String hms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
System.out.println(hms);
tv.setText(hms);
//Another one second passed
//Each second ProgressBar progress counter added one
m_n_ProgressStatus += 1;
pb.setProgress(m_n_ProgressStatus);
}
public void onFinish() {
// retreive user data from shared preferencce........
HashMap<String, String> user = m_oSessionManagement.getRegistrationDetails();
m_szEncryptedPassword = user.get(CRegistrationSessionManagement.s_szKEY_PASSWORD).trim();
m_szMobileNumber = user.get(CRegistrationSessionManagement.s_szKEY_MOBILENUMBER).trim();
// exc=ecuting request for otp verfiifcation to server
new COtpVerify().execute();
}
}.start();
// retreive progress bar count........
int progressBarMaximumValue = (int) (m_MillisInFuture / m_CountDownInterval);
//Set ProgressBar maximum value
//ProgressBar range (0 to maximum value)
pb.setMax(progressBarMaximumValue);
//Display the CountDownTimer initial value
tv.setText(progressBarMaximumValue + "Seconds...");
}
// sending OTP to server to verify Otp
private class COtpVerify extends AsyncTask<String, Void, String> {
public JSONObject m_oResponseobject;
public String m_szResponseAgentCode;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_ProgressView.setVisibility(View.VISIBLE);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... args) {
InputStream inputStream;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(m_szOTPVERIFICATIONURL);
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);
jsonObject.put("pin", m_szEncryptedPassword);
jsonObject.put("otpCode", COTPVerificationDataStorage.getInstance().getM_szOtp());
// 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("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();
// 10. convert inputstream to string
if (statusCode == 200) {
// 10. convert inputstream to string
s_szResult = CJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
} else
s_szResult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("resul" + s_szResult);
// 11. return s_szResult
return s_szResult;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(final String result) {
m_ProgressView.setVisibility(View.GONE);
try {
m_oResponseobject = new JSONObject(result);// getting response from server
getResponse();// getting response from server ...............
} catch (Exception e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
// if server response is successfull then......
if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("Transaction Successful")) {
// if server response is success then setting response odata in shared prefernce...
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CLoginScreen()).commit();
CSnackBar.getInstance().showSnackBarSuccess(m_Main.findViewById(R.id.mainLayout), "OTP verified successfully", getActivity());
}
// if response from server is m_szOtp mismatch.....
else if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("OTP MisMatch")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "OTP not found", getActivity());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpManualVerificationScreen()).commit();
}
}, 3000);
}
// if response from server is m_szOtp empty then......
else if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("otpCode Can Not Be Empty")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "OTP not found", getActivity());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpManualVerificationScreen()).commit();
}
}, 3000);
}
}
}
}
and here is my BroadcastReceiver class:-
public class CSmsBroadcastReceiver extends BroadcastReceiver {
private static final String s_szTAG = CSmsBroadcastReceiver.class.getSimpleName();
private static String m_szOtpCode;
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
assert pdusObj != null;
for (Object aPdusObj : pdusObj) {
#SuppressWarnings("deprecation") SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.e(s_szTAG, "Received SMS: " + message + ", Sender: " + phoneNumber);
// checking sms sender address....
if (phoneNumber.toLowerCase().contains("+919971599707".toLowerCase())) {
// verification code from sms
m_szOtpCode = getVerificationCode(message);
assert m_szOtpCode != null;
String input = m_szOtpCode.trim();
Log.e(s_szTAG, "OTP received: " + m_szOtpCode);
COTPVerificationDataStorage.getInstance().setM_szOtp(input);// getting otp from SMS and set to otpverificationstorage class
} else {
return;
}
}
}
} catch (Exception e) {
Log.e(s_szTAG, "Exception: " + e.getMessage());
}
}
/**
* Getting the OTP from sms message body
* ':' is the separator of OTP from the message
*
* #param message
* #return
*/
#SuppressWarnings("JavaDoc")
private String getVerificationCode(String message) {
String code;
int index = message.indexOf(":");
if (index != -1) {
int start = index + 2;
int length = 6;
code = message.substring(start, start + length);
return code;
}
COTPVerificationDataStorage.getInstance().setM_szOtp(m_szOtpCode);
return null;
}
}
Basically you want to send data from broadcast receiver to activity whenever desired message comes.you can make use of interface to communicate
In you BroadcastReceiver create interface like this
public interface OnSmsReceivedListener {
public void onSmsReceived(String message);
}
add one method to initialize interface reference
OnSmsReceivedListener smsListener;
public void setOnSmsReceivedListener(Context context) {
this.smsListener = (OnSmsReceivedListener) context;
}
use this reference to call function inside onReceive() method
smsListener.onSmsReceived("Message Received!!!");
You are done with posting data ,now give implementation of interface in your Activity and dismiss your dialog.
public class SampleActivity extends Activity implements OnSmsReceivedListener
#Override
public void onSmsReceived(String message) {
//Dismiss your dialog here
}
Other then this approach you can make use of some good third party library like EventBus and Otto which will make your work simple and easy.
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
I am developing an app in which a login screen is visible to user and what I have to send to server is mobilenumber,password and isfirst true to server when user logging in first time and when user logout and again login I have to send isFirst false to server ,How can I achieve this problem.
Note:- I dont have to check value from shared Preference, I have to send isFirst true or false on user login first time and second time,first time is true and second time false to server using Jsons.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://543.168.0.110:8080/ireward/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn;
public ProgressDialog m_PDialog;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public Snackbar m_SnackBar;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
public boolean isFirstTimeLogin = true;
#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();
m_oLoginSession = new CLoginSessionManagement(getActivity());
Toast.makeText(getActivity(), "User Login Status: " + m_oLoginSession.isLogin(), Toast.LENGTH_LONG).show();
init();
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.setBackgroundColor(Color.TRANSPARENT);
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();
m_PDialog = new ProgressDialog(getActivity());
m_PDialog.setMessage("Please wait while Logging...");
m_PDialog.setCancelable(false);
m_PDialog.show();
}
#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());
}
System.out.println("s_szResult....." + s_szresult);
System.out.println("password......" + s_szPassword);
// 11. return s_szResult
return s_szresult;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
m_PDialog.dismiss();
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
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();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Please enter valid mobile number", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Please enter Password", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Invalid Password", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
m_SnackBar = Snackbar.make(m_MainLayout, "You are bloacked", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Connection Lost", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
m_SnackBar = Snackbar.make(m_MainLayout, "User not found ! Kindly Register", Snackbar.LENGTH_LONG);
m_SnackBar.show();
}
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
}
}
In my project , to access the webservice am using http class which is not working properly and my project stops.
Can someone tell me an alternate way for accessing the webservice instead of using http.
Thank you in advance
class httpclass {
String result;
public String server_conn(String user_url)
{
// String user_url="";
String user_url3=user_url.replaceAll(" ","%20");
String user_url2=user_url3.replaceAll("\n","%0D");
HttpClient client = new DefaultHttpClient();
HttpGet siteRequest = new HttpGet(user_url2);
StringBuilder sb = new StringBuilder();
HttpResponse httpResponse;
try {
httpResponse = client.execute(siteRequest);
HttpEntity entity = httpResponse.getEntity();
InputStream in = entity.getContent();
String line = null;
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
result = sb.toString();
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
log in form
public class LoginForm extends FragmentActivity {
/** Called when the activity is first created. */
TextView txt1, txt2, err,forget;
EditText name;
EditText pass;
Button click,vend;
CheckBox savepass;
Button newuser;
Button signin;
#SuppressWarnings("unused")
private Cursor signin1;
SharedPreferences sharedPreferences=null;
public static String str1, str2;
public static String result;
public static String username;
ProgressDialog myProgressDialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); BugSenseHandler.initAndStartSession(this, "68640bea");
setContentView(R.layout.login);
vend=(Button)findViewById(R.id.vend);
name = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
savepass=(CheckBox)findViewById(R.id.savepass);
Button cancel = (Button) findViewById(R.id.cancel);
//Button back = (Button) findViewById(R.id.back);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent second = new Intent( LoginForm.this,canceluser.class);
startActivity(second);
finish();
}
});
sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
String name1=sharedPreferences.getString("p_name", "");
name.setText(name1.toString());
String pass1=sharedPreferences.getString("p_pass", "");
pass.setText(pass1.toString());
//s forget=(TextView)findViewById(R.id.forget);
signin = (Button) findViewById(R.id.signin);
click = (Button) findViewById(R.id.click);
newuser = (Button) findViewById(R.id.signup);
vend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("http://www.iwedplanner.com/vendor/vendorhome.aspx"));
startActivity(viewIntent);
}});
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(LoginForm.this, forgetpwd.class);
startActivity(intent1);
finish();
}});
signin.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(name.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Username");
name.requestFocus();
}
else if(pass.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Password");
pass.requestFocus();
}
else
{
str1 = name.getText().toString();
str2 = pass.getText().toString();
boolean value = false;
// validuser();
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
value = true;
openconn(str1, str2);
}
else
{
alertbox("Message!", "No Internet Connection!");
}
}
}
});
newuser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newuser();
}
});
}
public void openconn(String strr1, String strr2)
{
if (!strr1.equals("") && !strr2.equals(""))
{
err = (TextView) findViewById(R.id.err);
// String user_url = "http://iwedplanner.com/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
// alertbox("",""+result);
if (result != null)
{
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if (result.equals("InvalidUser "))
{
Dialog locationError = new AlertDialog.Builder(
LoginForm.this).setIcon(0).setTitle("Message!")
.setPositiveButton(R.string.yes, null).setMessage(
"Sorry, Invalid Username or Password ")
.create();
locationError.show();
name.requestFocus();
}
else if(result.equals(strr1))
{
// Toast.makeText(getBaseContext(),"Valid User",Toast.LENGTH_SHORT).show();
if(savepass.isChecked())
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name",name.getText().toString());
//editor.putString("p_pass",pass.getText().toString());
editor.commit();
}
else
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name", "");
editor.putString("p_pass","");
editor.commit();
}
validuser();
}
else
{
alertbox("Message!","Error in network connection");
}
}
}
}
public void validuser()
{
username=str1;
name.setText("");
pass.setText("");
Intent userintent = new Intent(this, welcomeuser1.class);
//userintent.putExtra("name5",str1);
//Intent userintent=new Intent(this,WeddingInfo.class);
startActivity(userintent);
finish();
}
public void newuser() {
Intent userintent1 = new Intent(this, newuserform.class);
startActivity(userintent1);
finish();
}
protected void alertbox(String title, String mymessage) {
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
}
#Override
public void onStart() {
super.onStart();
// The rest of your onStart() code.
// // EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
public void onStop() {
super.onStop();
// The rest of your onStop() code.
// EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
}
Error:duplicate files during packaging of APK C:\Users\sentientit\Documents\Wed Studio\app\build\outputs\apk\app-debug-unaligned.apk
Path in archive: META-INF/LICENSE.txt
Origin 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
1 Origin 2: C:\Users\sentientit.gradle\caches\modules-2\files-2.1\joda-
time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can ignore those files in your build.gradle:
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
}
}
Error:Execution failed for task ':app:packageDebug'.
Duplicate files copied in APK META-INF/LICENSE.txt
File 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
File 2: C:\Users\sentientit\.gradle\cache``s\modules-2\files-2.1\joda-time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can do this way:
AsyncTask for Web service:
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("Loading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
String serverGETResponse = getJsonDataStringFormat("Your_Url", "GET", "", "LOGIN_ACTIVITY");
String serverPOSTResponse = getJsonDataStringFormat("Your_Url", "POST", "YOUR_JSON_STRING", "LOGIN_ACTIVITY");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
Now Get Response from server in Background thread:
public static String getJsonDataStringFormat(String url, String method,String jObjStr, String tag) {
InputStream is = null;
String Root_Response = null;
HttpResponse httpResponse;
HttpParams httpParameters = new BasicHttpParams();
DefaultHttpClient httpClient;
HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
try {
httpClient = new DefaultHttpClient(httpParameters);
url = url.replace(" ", "%20");
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jObjStr));
httpResponse = httpClient.execute(httpPost);
is = httpResponse.getEntity().getContent();
} else if (method == "GET") {
HttpGet httpGet = new HttpGet(new URI(url));
httpResponse = httpClient.execute(httpGet);
is = httpResponse.getEntity().getContent();
}
Root_Response = convertStreamToString(is);
Log.i(tag, Root_Response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (URISyntaxException e) {
e.printStackTrace();
}
return Root_Response;
}
Convert Server's Response to String:
public static String convertStreamToString(InputStream inputStream)
throws IOException {
if (inputStream != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
inputStream.close();
}
return sb.toString();
} else {
return "";
}
}
Hope it will help you.
call the method server_conn() inside AsyncTask , and pass the url
private class AsyncTaskTest extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... strings) {
server_conn(strings[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
and call the asynctastk using below syntax
new AsyncTaskTest().execute(url);
You are facing NetworkOnMainThread exception all you have to do is add this code :
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
For more details you can check developer site.
I was able to successfully make login work. Now, I am stuck up with registration. Response is wrong.
public class Register extends Activity implements OnClickListener{
private String mTitle = "Write.My.Action";
private static final String LOGTAG = "tag";
public EditText fullname, email, password;
private Button register;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getActionBar().setTitle(mTitle);
fullname = (EditText) findViewById(R.id.fullname);
email = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText1);
register = (Button) findViewById(R.id.button1);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mDialog = new ProgressDialog(Register.this);
mDialog.setMessage("Attempting to Register...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
mDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
register();
}
}).start();
}
}
void register() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl");
System.out.println("httpPost is: " + httpPost);
String fullname_input = fullname.getText().toString().trim();
String email_input = email.getText().toString().trim();
String password_input = password.getText().toString().trim();
//adding data into list view so we can make post over the server
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("fullname", fullname_input));
nameValuePair.add(new BasicNameValuePair("email", email_input));
nameValuePair.add(new BasicNameValuePair("password", password_input));
System.out.println("namevaluepair is: " + nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
//execute http post resquest
HttpResponse httpResponse = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response is: " + response);
runOnUiThread(new Runnable() {
#Override
public void run() {
mDialog.dismiss();
}
});
if(response.equalsIgnoreCase("Signed Up")){
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Register.this, Registration_Success.class));
}
});
}else {
showAlert();
}
} catch (Exception e) {
mDialog.dismiss();
Log.i(LOGTAG, "Exception found"+ e.getMessage());
}
}
public void showAlert(){
Register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Registration Error");
builder.setMessage("Please, try registration again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Please Note: Every activities are registered in Manifest, INTERNET permission also included.
php file:
include "dbconnection.php";
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];
$insert_data = "INSERT INTO register
Values ('', '$fullname', '$email', '$password')";
$insert_result = mysql_query($insert_data);
//echo "Signed Up";
if($insert_result){
echo "Signed Up";
}
else{
echo "wrong!";
}
I don't understand why it keeps on saying Response is : Wrong. Tired of spending almost a day .. I am here seeking help.
Excuse me if my questions seems naive.
Thank you in advance.
try below code:-
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null)
{
InputStream in = httpResponse.getEntity().getContent();
result = ConvertStreamToString.convertStreamToString(in);
// System.out.println("result =>" + result);
}
convertStreamToString method
public String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
do not under stand :-
HttpResponse httpResponse = httpClient.execute(httpPost); // getting response from server
// where you use this response and why using below line or whats the benefit of below line
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
Follow that tutorial very usefull, and clear how to work on json webservices with android.
How to connect Android with PHP, MySQL
Try this code using AsyncTask
public class Register extends Activity implements OnClickListener{
private String mTitle = "Write.My.Action";
private static final String LOGTAG = "tag";
public EditText fullname, email, password;
private Button register;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getActionBar().setTitle(mTitle);
fullname = (EditText) findViewById(R.id.fullname);
email = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText1);
register = (Button) findViewById(R.id.button1);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mDialog = new ProgressDialog(Register.this);
mDialog.setMessage("Attempting to Register...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
mDialog.show();
new RegisterUser().execute();
}
}
public class RegisterUser extends AsyncTask<Void, Void, String>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl");
System.out.println("httpPost is: " + httpPost);
String fullname_input = fullname.getText().toString().trim();
String email_input = email.getText().toString().trim();
String password_input = password.getText().toString().trim();
//adding data into list view so we can make post over the server
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("fullname", fullname_input));
nameValuePair.add(new BasicNameValuePair("email", email_input));
nameValuePair.add(new BasicNameValuePair("password", password_input));
System.out.println("namevaluepair is: " + nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
//execute http post resquest
HttpResponse httpResponse = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response is: " + response);
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(response.equalsIgnoreCase("Signed Up")){
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Register.this, Registration_Success.class));
}
});
}else {
showAlert();
}
}
}
public void showAlert(){
Register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Registration Error");
builder.setMessage("Please, try registration again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Hope this helps you!!!
If its not working please let me know i will try to help more...
Try using Volley if not. It's faster than the ussual HTTP connection classes.
Example:
RequestQueue queue = Volley.newRequestQueue(this);
String url = "url";
JSONObject juser = new JSONObject();
try {
juser.put("locationId", locID);
juser.put("email", email_input);
juser.put("password", password_input);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, juser, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
Like #Andrew T suggested , I am posting my solution.
The mysql_error()helped me debug the issue. mysql_error() displayed in the Logcat that "register table is not found" .. but the table name is registers. I was missing "s" at the end.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];
$insert_data = "INSERT INTO registers(id, fullname, email, password)
Values ('','$fullname', '$email', '$password')";
$insert_result = mysql_query($insert_data) or die(mysql_error());
//echo "Signed Up";
if($insert_result){
echo "Signed Up";
}
else{
echo "wrong!";
}
Everything worked perfect after that. Again, thank you all for your time and solutions. Everyone's suggestions are great, but I can not accept any answer at this point.. sorry:(