httppost method of android doesnt work with namevalue pairs - android

The code below creates a form whose results are to be posted to server(request to a server)... i tried the same form using html with same form fields it works but here it does not work and redirects to the home page of the website.....
public class MainActivity extends Activity {
Button submit,fpass;
EditText wbpasswd,wblogid;
TextView loginid,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wblogid = (EditText) findViewById(R.id.wblogid);
wbpasswd = (EditText) findViewById(R.id.wbpasswd);
submit = (Button) findViewById(R.id.submit);
fpass = (Button) findViewById(R.id.fpass);
loginid = (TextView) findViewById(R.id.loginid);
password = (TextView) findViewById(R.id.password);
fpass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "You have clicked the fpass button",
Toast.LENGTH_SHORT).show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.ebharatgas.com/ebgas/login");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("wblogid", wblogid.getEditableText().toString()));
nameValuePairs.add(new BasicNameValuePair("wbpasswd", wbpasswd.getEditableText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String t = EntityUtils.toString(response.getEntity());
Intent i = new Intent("com.example.ebharatgas.Activity2");
i.putExtra("code", t);
startActivity(i);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}).start();
//Toast.makeText(getBaseContext(), "You have clicked the fpass button",
//Toast.LENGTH_SHORT).show();
}
});
}
}
Also please tell me how can i display the response from the server on my android activity... and i am a beginner of android programming... please help me.... thanks in advance..

give it a try like this:
private class JsonResponse extends AsyncTask {
String response = "";
protected void onPreExecute()
{
}
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
Intent i = new Intent("com.example.ebharatgas.Activity2");
i.putExtra("code", t);
startActivity(i);
}
}
protected String doInBackground(final String... args)
{ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("wblogid", wblogid.getEditableText().toString()));
nameValuePairs.add(new BasicNameValuePair("wbpasswd", wbpasswd.getEditableText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String t = EntityUtils.toString(response.getEntity());
}
response = "Success";
}
catch(JSONException e)
{
e.printStackTrace();
}
return response;
}
} //Formatting & Code setting required

Related

Submit The Form Via POST Method

While sending the message I got application error and the app stops. I wanted to submit the form using POST method. Please help me to correct the code as i am new to android.
I have taken code reference from http://www.onlymobilepro.com/2013/03/16/submitting-android-form-data-via-post-method/
public class MainActivity extends Activity {
EditText msgTextField;
Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yourdomain.com/serverside-script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); //reset the message text field
Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
You are doing network operation on Main Thread , it needs to be done in seperate Thread .
Do something like this:
To know how to use AsyncTask and set its parameters, see this :
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
EditText msgTextField;
Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v) {
//get message from message box
String msg = msgTextField.getText().toString();
if (!msg.isEmpty()) {
new PostData().execute(msg);
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(), "All fields are required", Toast.LENGTH_SHORT).show();
}
}
public class PostData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yourdomain.com/serverside-script.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", params[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
HttpResponse response = httpclient.execute(httppost);
String op = EntityUtils.toString(response.getEntity(), "UTF-8");//The response you get from your script
return op;
} catch (IOException e) {
e.printStackTrace();
}
//reset the message text field
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
msgTextField.setText("");
Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
}
}

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.

START INPUT: android.widget.EditText

i want to sava data from android app to local host in my pc.
i write a edittext to get my text:
<EditText
android:id="#+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
and write a method to send data to localhost:
public void send(View v3)
{
String msg = edittext2.getText().toString();
// make sure the fields are not empty
if (msg.length()>0)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://localhost/datalog.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
edittext2.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
// Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
and call method by sendbutton:
sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v3) {
// TODO Auto-generated method stub
// send datasend=new send();
//datasend.execute();
send(v3);
}
});
but get a massage that:
08-10 01:14:26.171: V/InputMethodManager(20557): START INPUT: android.widget.EditText{41812b10 VFED..CL .F....ID 0,672-225,731 #7f080013 app:id/text2} ic=com.android.internal.widget.EditableInputConnection#418662b0 tba=android.view.inputmethod.EditorInfo#41866268 controlFlags=#100
i write a php code in server side ti get post variable.
I hope you do the Http Request in a thread outside of the main gui thread.
Can you try this code:
MainActivity:
public class MainActivity extends Activity {
private final static String TAG = MainActivity.class.getSimpleName();
EditText edittext2;
Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext2 = (EditText) findViewById(R.id.text2);
sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send();
}
});
}
public void send() {
String msg = edittext2.getText().toString();
// make sure the fields are not empty
if (!msg.equals(""))
{
Log.d(TAG, "send: " + msg);
// HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost("https://localhost/datalog.php");
//
// try {
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// nameValuePairs.add(new BasicNameValuePair("id", "12345"));
// nameValuePairs.add(new BasicNameValuePair("message", msg));
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// httpclient.execute(httppost);
// edittext2.setText(""); // clear text box
// } catch (ClientProtocolException e) {
// // TODO Auto-generated catch block
// } catch (IOException e) {
// // TODO Auto-generated catch block
// // Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
// }
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<EditText
android:id="#+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/sendButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="send"
android:layout_below="#id/text2"/>
</RelativeLayout>
This is working well for me, i am interested if its same for you
Edit after get more information:
I tested it now with the simple app and another php file at my computer.
The app is connectiong to the php file, which creates a message file. This message file can be accessed eg via Browser.
The Http part have to run in an task which i did this way:
MainActivity:
public class MainActivity extends Activity {
private final static String TAG = MainActivity.class.getSimpleName();
EditText edittext2;
Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext2 = (EditText) findViewById(R.id.text2);
sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyHttpTask mTask = new MyHttpTask();
mTask.execute("");
}
});
}
class MyHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
send();
return "";
}
#Override
protected void onPostExecute(String result) {
Log.d(TAG, "onPostExecute" + result);
edittext2.setText(result);
}
}
public void send() {
String msg = edittext2.getText().toString();
// make sure the fields are not empty
if (!msg.equals(""))
{
Log.d(TAG, "send: " + msg);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.178.60/datalog.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//edittext2.setText(""); // clear text box
} catch (ClientProtocolException e) {
Log.d(TAG, e.toString());
} catch (IOException e) {
Log.d(TAG, e.toString());
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
}
Make sure its NOT localhost do to this is nor possible to connect except theAndroid device is running the http server with php.
php file datalog.php:
<?php
$message=$_POST['message'];
$filename="androidmessages.html";
file_put_contents($filename,$message."<br />",FILE_APPEND);
$androidmessages=file_get_contents($filename);
echo $androidmessages;
?>
I also get a file called "androidmessages.html" with the text i key in into edittext
For me this is working well without any error
The sense of this job would be to have a web page which is logging the messages from the android device. So it would be possible to view the messages from any browser via network connection

Response:wrong. [User registration via android app using http post not working]

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:(

Fail to display server's respond

Here I am trying to retrieve the response from the server and display it, but I am failed to do so, the response text does not appear in my text view, insetead the default value of the string does, may I ask how can I achieve my goal. And why my code cannot finish the task.
Here is my android program:
public class Chico extends Activity {
GrabURL grab;
TextView mRespond;
String line;
#Override
public void onCreate(Bundle savedInstanceState) {
//create the activity
super.onCreate(savedInstanceState);
//set up the layout
setContentView(R.layout.activity_chico);
mRespond = (TextView) findViewById(R.id.Respond);
mRespond.setVisibility(View.GONE);
grab = new GrabURL();
line = "line";
//set up the button for check in
Button btnin = (Button) findViewById(R.id.inbutton);
btnin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//set the values
grab.onPreExecute("TechID", Build.SERIAL);
grab.onPreExecute("Type", "Checkin");
//set the destination and send the request
grab.execute(new String[]{"http://192.168.1.150/Me/testing.php"});
//close the activity
mRespond.setVisibility(View.VISIBLE);
mRespond.setText(line);
//finish();
}
});
}
private class GrabURL extends AsyncTask<String, Void, Void>{
//ArrayList object for storing the string pairs
ArrayList<NameValuePair> nameValuePairs;
public GrabURL() {
//constructor of the class
nameValuePairs = new ArrayList<NameValuePair>();
}
protected void onPreExecute(String key, String value) {
//store the pair of values into the ArrayList
nameValuePairs.add(new BasicNameValuePair(key,value));
}
#Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
//Operation being executed in another thread
try{
//set up the type of HTTPClient
HttpClient client = new DefaultHttpClient();
//set up the location of the server
HttpPost post = new HttpPost(urls[0]);
//translate form of pairs to UrlEncodedFormEntity
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
//set up the entity being sent by post method
post.setEntity(ent);
//execute the url and post the values
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
line = EntityUtils.toString(resEntity);
} catch (Exception e) {
//catch the exception
line = "Can't connect to server";
}
return null;
}
protected void onPostExecute(Void unused) {
Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
}
}
}
And here is the php file, it just prints a line:
<?php
print "testing";
?>
Move this code to your AsyncTask's onPostExecute():
...
mRespond.setVisibility(View.VISIBLE);
mRespond.setText(line);

Categories

Resources