i am building an application in which i prompt users to register. I have a django-restful server running at back end , and i m trying to make HTTP post requests to my server on android client with DefaultHttpClient class. I get email, username etc from user and at the button's onClick event, i create an AsnycTask to execute the request. Here is the code for the activity:
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String userName = usernameEditText.getText().toString();
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if( userName != null && email != null && password != null) {
new RegisterEventHandler().execute(userName , email , password);
}
}
});
....
class RegisterEventHandler extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
RequestHandler handler = new RequestHandler();
return handler.register(params[0], params[1], params[2]);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if( result ) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle(R.string.RegisterSuccessfullTitle);
builder.setMessage(R.string.RegisterSuccessfullMessage);
builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent redirect = new Intent(getApplicationContext() , SmartMapMainActivity.class);
startActivity(redirect);
}
});
builder.create().show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle(R.string.RegisterFailedTitle);
builder.setMessage(R.string.RegisterFailedMessage);
builder.create().show();
}
}
}
The RequestHandler class :
public class RequestHandler {
public boolean register(String userName , String email , String password) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://127.0.0.1/users/");
try {
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", userName);
jsonObj.put("email", email);
jsonObj.put("password", password);
StringEntity entity = new StringEntity(jsonObj.toString());
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200)
return true;
else
return false;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
The problem is, DefaultHttpClient's connManager(ClientConnectionManager) is always null and on the execute() method of the HttpClient, it always throws an IOException. I tried initializing the DefaultHttpClient in my activity , rather than in the AsyncTask's doInBackground method , but the result was the same.
Related
Here i am facing a problem with password validation which is when i entering correct password but it is saying the password is incorrect. Here i am using rest web services below is my code please help me.
EditText password;
String Passwordstr;
Button btn_go;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
password = (EditText) findViewById(R.id.passET);
btn_go = (Button) findViewById(R.id.btn_go);
btn_go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passwordstr = password.getText().toString();
if (Passwordstr.isEmpty()) {
Toast.makeText(Main2Activity.this, "Please, Enter Your Password.", Toast.LENGTH_SHORT).show();
} else {
new MyAsyncTask().execute(Passwordstr);
}
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String res = PostData(params);
return res;
}
public String PostData(String[] args) {
String s = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:82/demo/login.php");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
s = readResponse(httpResponse);
} catch (Exception exception) {
}
return s;
}
protected void onPostExecute(String result) {
if (result.equals("true")) {
Intent intent = new Intent(Main2Activity.this, Main3Activity.class);
intent.putExtra("Password", Passwordstr);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Password incorrect", Toast.LENGTH_LONG).show();
}
}
public String readResponse(HttpResponse res) {
InputStream is = null;
String return_text = "";
try {
is = res.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
StringBuffer sb = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
return_text = sb.toString();
} catch (Exception e) {
}
return return_text;
}
}
}
I am developing an android app in this my aim is to connect to a web page through web-server, here i am using Rest call and java code.Please help me any one.
In your post execute you have to check the null value not the true value like this
protected void onPostExecute(String result) {
if (result!=null) {
Intent intent = new Intent(Main2Activity.this, Main3Activity.class);
intent.putExtra("Password", Passwordstr);
//No Full Name
//MyHomeActivity.putExtra("GetDisplayName",user.getDisplayName());
// MyHomeActivity.putExtra("GetPhotoUrl",user.getPhotoUrl());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Password incorrect", Toast.LENGTH_LONG).show();
// Hide the progress bar
// progressBar.setVisibility(View.GONE);
}
}
try this as you are not create post parameters pair with key and value.
List nameValuePair = new ArrayList(1);
nameValuePair.add(new BasicNameValuePair("password", "password"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
Also hit rest api from postman or hurl.it with same password and check the response.
you can use android-async-http simple , fast
and u can access UI thread an Views on respond methods
RestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
JSONObject firstEvent = timeline.get(0);
String Text = firstEvent.getString("text");
textview.setText(Text);
// Do something with the response
System.out.println(tweetText);
}
});
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
here is my java file and i used onclick function in my xml file as same method working for login button but not for signup please help me to solve this issue.
public class signup extends ActionBarActivity {
EditText username, pass, cpass, mail, phn;
String uname, password, confirmpass, email, phone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
username = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
cpass = (EditText) findViewById(R.id.comfirmpass);
mail = (EditText) findViewById(R.id.email);
phn = (EditText) findViewById(R.id.phone);
Button signupbutton = (Button) findViewById(R.id.signupbutton);
}
//When the send button is clicked
public void sign(View v) {
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
//Method to get list value pair and form the query
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
//Data intialization and Validation
public void validate() {
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
if (password.equals(confirmpass)) {
post();
} else {
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
public void error(boolean flag, String etext) {
if (flag == true) {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
//Code to handle failure
} else {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
setContentView(R.layout.login);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Method to post data to webservice
public void post() {
try
{
// Calling async task to get json
new DownloadOperation().execute();
}
catch (Exception e) {
e.printStackTrace();
}
}
private class DownloadOperation extends AsyncTask<Void, Void, String> {
ProgressDialog dialog;
String uname = "";
String email = "";
String password = "";
String confirmpass = "";
String phone = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
//Initiate ProgressBar
dialog = ProgressDialog.show(signup.this, "Please Wait", "Registering ...");
}
#Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://rgbpallete.in/led/api/signup");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
dialog.dismiss();
Log.d("tag", "Result:\n" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String message = jsonObj.getString("message");
boolean error = jsonObj.getBoolean("error");
error(error,message);
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
}
Have you mention android:onClick="sign" in your signup.xml under layout directory? Please make sure it.
I think your code is corect.
add Log to sign function:
public void sign(View v) {
Log.e("tag","sign function called");
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
if corect, you can show log is: "sign function called"
simply add this on your onCreate() method
signupbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),
"Button is clicked", 3000).show();
///what ever you want to do on signupbtn comes here
//add this try block if you need same functionality as `sign() method`
try {
// CALL validate method
validate();
} catch (Exception ex) {
String error = ex.getMessage();
}
}
});
and every time you cliecked signupbutton this method(Listener) will called.
Or
add this line in you xml file where you define the signupbutton
android:onClick="sign"
But the best way for me is to add clickListener as it makes it very clear from java class side that what is beaing called on clicking the button.
I have web services and I want to create a class that should takes an email and password from server after authentication in hash table, and then saves email and password in shared preferences.
Try this class to call webservice in your app, i am sharing get and post both methods you can use any one as per your need.
public class CallService {
String url;
HttpEntity str1;
String str;
Context context;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public CallService(String url1) {
this.url = url1;
}
public String getResponceWithPost() {
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,5000000);
HttpConnectionParams.setSoTimeout(httpParameters,500000);
HttpConnectionParams.setTcpNoDelay(httpParameters,true);
HttpClient hc = new DefaultHttpClient(httpParameters);
HttpPost post= new HttpPost (url);
HttpResponse rp = hc.execute(post);
// //////////////
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
str = EntityUtils.toString(rp.getEntity());
Log.e("Calling service", str);
return str;
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int getResponceWithGet() {
int code = 0;
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse rp = hc.execute(get);
code= rp.getStatusLine().getStatusCode();
return code;
} catch (IOException e) {
Log.e("calling service", e.toString());
e.printStackTrace();
}
catch(Exception e)
{
Log.e("calling service", e.toString());
}
return code;
}}
this will return response from server like email password or other details.
and you can save these details in sharedpreference .
for shared preference follow this -
http://developer.android.com/guide/topics/data/data-storage.html#pref
and in your activity call your url using my call service class like this-
declare your hashTable in activity like this
Hashtable hashtable = new Hashtable();
call this method
new checkForLogin().execute();
and your async class
class checkForLogin extends AsyncTask<Void, Void,String>
{
#Override
protected void onPreExecute() {
progress= ProgressDialog.show(LoginScreen.this,"Authenticating !","Please Wait");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Parse your json data here that will be in data
CallService cl2=new CallService("your server url here");
Log.e("login url is",""+Urls.loginurl);
data=cl2.getResponceWithPost();
Log.e("server response data","data = "+data);
hashtable.put(“email″, data.getString("email"));
hashtable.put(“pass″, data.getString("pass"));
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}
i hope this ll help you.
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:(