Sending sign up data from user to server - java

EDIT:
I finally figured out where the problem is. I keep getting an IOException on this line
response = httpClient.execute(httpPost).
However, the normal problems that will cause this error (the ones that I searched online, like the url being wrong and such) are not the problem here. The url is correct. Can anyone help or list all of the possible reasons I would get this error. Thank you.
I know this question has been asked several times, and I actually looked at the answers given for those questions in order to originally figure out how to do this but for some reason it's not working and I don't know why.
I have an app that requires a user to sign up. After they sign up I send the information they inputted to the server.
Android code:
//This is the method called when user presses submit button. The variables not declared
//are global
public void registerUser(View v){
context = getApplicationContext();
username = ((EditText) this.findViewById(R.id.username)).getText().toString();
email = ((EditText) this.findViewById(R.id.email)).getText().toString();
password=((EditText)this.findViewById(R.id.password)).getText().toString();
String[] params = {username,email,password};
(new SendRegisterInfo(this.getApplicationContext())).execute(params);
Toast t = Toast.makeText(context, "Thank you for Signing up "+username, Toast.LENGTH_SHORT);
t.show();
//Start Main Page Activity. Page they'll see everytime they login
Intent i = new Intent(this,HomeActivity.class);
startActivity(i);
}
public class SendRegisterInfo extends AsyncTask<String,Void,Void>{
private String tag = "SendRegisterInfo";
private InputStream is;
private Context c;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
public SendRegisterInfo(Context c){
this.c = c;
}
#Override
protected Void doInBackground(String... params) {
String URI="http://www.mysite.com/registerUser.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URI);
HttpResponse response;
String username,email,password;
username = params[0];
email = params[1];
password = params[2];
try {
ArrayList<NameValuePair> submit = new ArrayList<NameValuePair>(2);
submit.add(new BasicNameValuePair("username",username));
submit.add(new BasicNameValuePair("email",email));
submit.add(new BasicNameValuePair("password",password));
httpPost.setEntity(new UrlEncodedFormEntity(submit));
response = httpClient.execute(httpPost);
Log.i(tag,response.getStatusLine().toString());
} catch (ClientProtocolException e) {
Log.e(tag, "Error in http connection "+e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(tag, "Error in http connection "+e.toString());
e.printStackTrace();
}catch (Exception e){
Log.e(tag, "Error in http connection "+e.toString());
e.printStackTrace();
}
return null;
}
}
Manifest File:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
PHP Code:
<?php
$username = $_POST["username"];
$email = $_POST["email"];
$pswrd = $_POST["password"];
$score = 0;
$user = "root";
$password="pword";
$database = "databasename";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die("Unable to Select Database");
$query="INSERT INTO Players VALUES ('','$username','$email','$pswrd','','$score')";
mysql_query($query);
mysql_close();
?>

You have an error reading the (String... params) argument of the doInBackground() method.
When you start the AsyncTask:
String[] params = {username,email,password};
When you read the arguments
String username,email,weight,password;
username = params[0];
email = params[1];
password = params[3]; // should be: password = params[2];
If this isn't works, adds a mySql query asking for the last insert id on the php program and print the result to get the response in the client:
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
Log.i(tag,EntityUtils.toString(entity).toString());
So you can see if you are inserting or not on the db.

This is your issue:
RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
You're attempting to show a Toast from a class that isn't designed to show a Toast. Or, perhaps, isn't prepared to show a tost. What is the class containing the method registerUser

Please check the code below.
Add function name and key to the request along with your data.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add((NameValuePair) new BasicNameValuePair("f", "yourFunctionName."+methodName));
nameValuePairs.add((NameValuePair) new BasicNameValuePair("u", "a0ff8a6a0a831ec25cf4de6c730be54c"));
//u is the key used by server to identify valid request.

Related

Writing from android program to localhost phpmyadmin

I have been solving this problem for 2 days now, but still nothing.
This is my code I use in my main activity:
public void InsertData(final String name, final String email){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String postReceiverUrl = "http://192.168.1.71/insert_data.php";
Log.d("Hello", "postURL: " + postReceiverUrl);
String NameHolder = name ;
String EmailHolder = email ;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", NameHolder));
nameValuePairs.add(new BasicNameValuePair("email", EmailHolder));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("come on man", "it works");
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
When I run this code in my Emulator it works, but when I upload it to my Samsung S3 phone, it doesnt work. The data doesn't get pushed.
This is my insert_data.php
<?php
$hostname = "localhost";
$username = "-";
$password = "-";
$dbname = "test";
$con = mysqli_connect($hostname,$username,$password,$dbname);
$name = $_POST['name'];
$email = $_POST['email'];
$Sql_Query = "insert into GetDataTable (name,email) values ('$name','$email')";
if(mysqli_query($con,$Sql_Query)){
echo 'Data Submit Successfully';
}
else{
echo 'Try Again';
}
mysqli_close($con);
?>
I am wondering why this code doesn't work on my phone. I also tried using my localhost IP address instead of localhost in my PHP file, but still it wasn't working.
I have fixed the problem.
I had to go to my config file of Apache httpd.conf.
You have to search for the lines that look like this:
I have added line 192 and 193 myself, they weren't there in the beginning, thats what solved the problem.
Special thanks to #SISYN for hinting me about the "My first guess is your db doesn't allow external connections by default".

How to send HTTP request from android app to Heroku

I have a android app that uses the twilio sdk and is hosted by heroku server. I'm trying to push a button in my app to send a HTTP request to heroku to send a REST API request to Twilio to update my twiml URL. The current way i'm trying to send the the HTTP request is not working. I have looked through all of the examples that i could find and none of them show how to do this function. Does anybody know how to do this? Thanks in advance.
This is my code for trying to send the HTTP request to heroku
holdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yourappnamehere.herokuapp.com/hello");
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//setting a toast to see if this is being initiated
Toast.makeText(getBaseContext(), "why wont it work!", Toast.LENGTH_SHORT).show();
}
;
});
This is my updated code including the volley library
holdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setting up a request queue from Volley API
//RequestQueue mRequestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
String url = "http://yourappnamehere.herokuapp.com/hello";
// Formulate the request and handle the response.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
Toast.makeText(getBaseContext(), "why wont it work!", Toast.LENGTH_SHORT).show();
}
;
});
I would suggest using a library like Google Volley which is pretty slick
https://developer.android.com/training/volley/index.html
HttpRequest is deprecated from API level 22. It would be best practice to avoid using that. Use java.net.HttpUrlConnection instead.
However, if you still want to use it, the above code needs to be run on a thread other than the UI thread as mentioned in the comment above.

Accessing a login api using http get method in android

I am developing an android app which uses a login api, which will allow its web users to login with their same credentials on the android device.....
the url for the api is
https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user=ecoachguest&pass=ecoachguest
which retuns a response in json
JSON object: {
status: <success or error>,
msg: <response message>,
profile: <user profile object>
}
I tried this code which I found searching on the internet but it isn't working,
private void doLogin(View view) {
//ALERT MESSAGE
_spinner.setVisibility(View.VISIBLE);
Toast.makeText(mContext, "connecting to server.... ",
Toast.LENGTH_SHORT).show();
// URLEncode user defined data
String usernameValue = username.getText().toString();
String passValue = password.getText().toString();
// Create http cliient object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+usernameValue+"&pass="+passValue;
Log.i("httpget", URL);
try
{
String SetServerString ;
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
System.out.println(usernameValue);
System.out.println(passValue);
// Show response on activity
Toast.makeText(getBaseContext(),SetServerString,Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getBaseContext(),"Fail",Toast.LENGTH_LONG).show();
_spinner.setVisibility(View.INVISIBLE);
}
}
will appreciate the help or the positive direction thanks :)
Change your code to get the HttpResponse like below,
String responseBody = "";
HttpResponse response = client.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
Log.i("GET Response Code ",responseCode + "");
switch(responseCode) {
// Means server is responding
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
// Now you can try printing your returned string here, before you go for JSON parsing
}
break;
// Add more case statements to handle other scenarios
}
The code is simple, but if still unable to understand, don't hesitate to ask.

code 401, login required, while using YouTube Data API V3 on Android

I am trying to use the new Youtube Data API on Android to retrieve the Video title from a given ID,
https://www.googleapis.com/youtube/v3/videos?id=6DbS1VB8HGo&part=player&key=XXX
However I keep getting getting a response saying that login required and error code 401.
Am guessing that it has something to do with the authorization token, but I don't understand why I should need this since I am not performing any account specific operations such as updating or deleting from a playlist. All I want is the title and maybe the number of view.
Any help should be appreciated, below is the code I am using:
public class NetTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
//param[0]= "https://www.googleapis.com/youtube/v3/videos?id=6DbS1VB8HGo&part=player&key=xxyy"
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
JSONObject responseJSON = new JSONObject(responseString);
responseJSON.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
API documentation says:
Prerequisites
Register your application with Google so that it can submit API requests.

Open WebView with result from Http post

I having an issue from my HTTP Post.
The code I'm using are working (have tested to post data to a guestbook form and it worked).
Now what I want. I have created two EditText forms, that holds values. I have a submit button there I post this data (like the test I wrote about before), but now I want to post it into a login.php page (that in a normal browser redirects me to the member.php page).
Although I know the forms are correctly filled in and it successfully posted on the "test" site, I wanna get the response from login.php and check if the user is successfully logged in or if it failed, if succeeded -> redirect me to member.php page.
All I know is this:
HttpResponse response = httpclient.execute(httppost);
that executes the command. But how should I achieve the login check? Any further use of the response variable?
Well... your approach is not good at all. If you are going to allow user authenticate through your app, why do you want to redirect the user to a member.php page? why don't you just put the login form in a login.php file on the server and make the user browse through your site?
As user, if an app allows me to authenticate using EditTexts inside UI, I would expect to access all the content through the app instead of being redirected to a web interface.
Anyway, if you decide to continue doing it that way keep in mind that you would have to parse and process cookies manually, and inject them into the WebView (Google about the CookieManager class). That's the way how the user will really be logged-in in your web app.
Can you provide a small example of how to set it up? The stream I will get, is that a special server response for example, a successfully login?
Here you have:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result; // here is a string of the result!!!
}
}
} catch (Exception e) {}
return null; // if it gets here, something wrong happens with the connection
}
private 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();
}
How do you use it? Something like this:
String result = getPostRequest("http://yourpage.com/login.php", "the username", "his/her pass");
if( result.equals("OK") ){
// voila!
}
I'm here supposing that you have something like this in your PHP code:
<?php
// login logic here
if( $success ){
die("OK");
}
?>

Categories