I have created a application for connecting the PHP, Mysql & Android. I am inserting the Name , Price & Description. Layout is good, ids given perfect but the data is not inserting into SQL DB.
package com.oplo.user.demo2;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user on 6/2/2015.
*/
#SuppressWarnings("deprecation")
public class addRecord extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
if(android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final EditText txtA = (EditText) findViewById(R.id.txtA);
final EditText txtB = (EditText) findViewById(R.id.txtB);
final EditText txtC = (EditText) findViewById(R.id.txtC);
final Button getData = (Button) findViewById(R.id.btnSave);
final Button btnBack = (Button) findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
getData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(txtA.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Name", Toast.LENGTH_LONG).show();
}if(txtB.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Price", Toast.LENGTH_LONG).show();
}if(txtC.getText().length()<2){
Toast.makeText(getApplicationContext(), "Input Description", Toast.LENGTH_LONG).show();
}else{
String url = "http://www.xyz.in/demo.php";
List params = new ArrayList();
//noinspection deprecation
params.add(new BasicNameValuePair("strA", txtA.getText().toString()));
params.add(new BasicNameValuePair("strB", txtB.getText().toString()));
params.add(new BasicNameValuePair("strC", txtC.getText().toString()));
#SuppressWarnings("unused")
String resultServer = getHttpPost(url,params);
//result.setText(resultServer);
Toast.makeText(addRecord.this, "1 Record inserted...", Toast.LENGTH_LONG).show();
emtyText();
txtA.requestFocus();
}
}
public void emtyText(){
txtA.setText("");
txtB.setText("");
txtC.setText("");
}
});
}
public String getHttpPost(String url,List params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
PHP Code:
<?php
$host = "localhost";
$user = "xcxc";
$pass = "xcxc";
$database = "xcxc";
$con = mysql_connect($host, $user, $pass) or die("Cannot connect Database");
mysql_select_db($database) or die("Cannot select Database.");
$a = $_POST["strA"];
$b = $_POST["strB"];
$c = $_POST["strC"];
$sql = "INSERT INTO demo (name, price, description) VALUES('$a', '$b', '$c')";
$result = mysql_query("SET NAMES 'UTF8'", $con);
$result = mysql_query($sql, $con);
if(!$result){
die ('Error: '.mysql_error($con));
}
//echo "1 record added...";
mysql_close($con);
Heres my code, but the data is not inserting into SQL.
Please let me know wheres the problem in this code.
thanks in advance.
You are not allowed to do any network related stuff on your main thread,go for asynctask or retrofit.
this link may help
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
Related
I am making an app that needs to post some data in MySQL database. The code doesn't show any errors, but no data is sent. My php file and HttpPost seem to work fine - I tried changing the php file so that it already included the data and then it worked. Here's my php:
<?php
$username = "user";
$password = "password";
$hostname = "mysql.xxx.com";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("myapp_xxx_com",$dbhandle)
or die("Could not select examples");
//retrieve the data
$street = $_POST['Street'];
$house = $_POST['House'];
$city = $_POST['City'];
$comment = $_POST['Comment'];
mysql_query ("INSERT INTO Address (Street, Number, City, Comment, TimeOrdered) VALUES('$street', '$house, '$city', '$comment', NOW())");
mysql_close($dbhandle);
?>
And here's my java code:
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class OrderSummary extends Activity implements OnClickListener {
private EditText editStreetText, editNumberText, editCityText, editCommentText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_summary);
editStreetText = (EditText) findViewById(R.id.summary_street);
editNumberText = (EditText) findViewById(R.id.summary_house);
editCityText = (EditText) findViewById(R.id.summary_city);
editCommentText = (EditText) findViewById(R.id.summary_comment);
button = (Button)findViewById(R.id.button_post_data);
button.setOnClickListener(this);
#Override
public void onClick(View v) {
String streetValue = editStreetText.getText().toString();
String numberValue = editNumberText.getText().toString();
String cityValue = editCityText.getText().toString();
String commentValue = editCommentText.getText().toString();
new SummaryAsyncTask().execute(streetValue, numberValue, cityValue, commentValue);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public void postData(String street, String number, String city, String comment)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxx.com/postdata.php");
try{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Street", street));
nameValuePairs.add(new BasicNameValuePair("House", number));
nameValuePairs.add(new BasicNameValuePair("City", city));
nameValuePairs.add(new BasicNameValuePair("Comment", comment));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
}
private class SummaryAsyncTask extends AsyncTask<String, Void, Void>{
protected Void doInBackground(String... params){
postData(params[0], params[1], params[2], params[3]);
return null;
}
}
}
}
I based the code on this tutorial http://mobiledevtuts.com/android/android-http-with-asynctask-example/ . I hope someone can help me with this.
You got an error in the PHP: '$house must be '$house'
Java code tested and working I just changed it a little bit
import android.os.Bundle;
import android.app.Activity;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class OrderSummary extends Activity {
String streetValue;
String numberValue;
String cityValue;
String commentValue;
private EditText editStreetText, editNumberText, editCityText, editCommentText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_summary);
editStreetText = (EditText) findViewById(R.id.summary_street);
editNumberText = (EditText) findViewById(R.id.summary_house);
editCityText = (EditText) findViewById(R.id.summary_city);
editCommentText = (EditText) findViewById(R.id.summary_comment);
button = (Button) findViewById(R.id.button_post_data);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
streetValue = editStreetText.getText().toString();
numberValue = editNumberText.getText().toString();
cityValue = editCityText.getText().toString();
commentValue = editCommentText.getText().toString();
new SummaryAsyncTask().execute((Void) null);
}
});
}
class SummaryAsyncTask extends AsyncTask<Void, Void, Boolean> {
private void postData(String street, String number, String city,
String comment) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxx.com/postdata.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Street", street));
nameValuePairs.add(new BasicNameValuePair("House", number));
nameValuePairs.add(new BasicNameValuePair("City", city));
nameValuePairs.add(new BasicNameValuePair("Comment", comment));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}
}
#Override
protected Boolean doInBackground(Void... params) {
postData(streetValue, numberValue, cityValue, commentValue);
return null;
}
}
}
Do not forget the Internet permission on android manifest
<uses-permission android:name="android.permission.INTERNET"/>
You can put the permission after <uses-sdk /> tag
public class RefreshChildren extends AsyncTask{
WebService service;
Helper helper;
RefreshChildren(){
service =new WebService();
helper =new Helper(null);
}
#Override
protected String doInBackground(String... params) {
refreshChildren();
return null;
}
private void refreshChildren() {
Log.d("Refresh", "children started");
List<ChildrenInstallBeen> childrenList=new ArrayList<ChildrenInstallBeen>();
childrenList=service.getChildrenListRefresh();
Iterator<ChildrenInstallBeen> iterator=childrenList.iterator();
while (iterator.hasNext()) {
ChildrenInstallBeen been = (ChildrenInstallBeen) iterator
.next();
Log.d("refresh children : ", ""+been.getFirst_name());
}
}
}
I made login page in my app, But i am getting problem when user input right user and pass it show on screen that User Found but app is not redirecting to next layout.
PHP code is:
<?php
$host="XXXXXXXXXXXXXX";
$username="aXXXXX62";
$password="XXXXXX";
$db_name="XXXXXn";
$tbl_name="mXXXXs";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
echo "User Found";
session_register("myusername");
session_register("mypassword");
}
else {
echo "Wrong Username or Password";
}
?>
and here is my java code:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b,signup;
EditText myusername,mypassword;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
b = (Button)findViewById(R.id.login);
signup = (Button) findViewById(R.id.signup);
myusername = (EditText)findViewById(R.id.username);
mypassword= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent( getBaseContext(), signup.class));
}
});
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://getjobcompleted.info/checklogin.php");
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("myusername",myusername.getText().toString().trim())); ;
nameValuePairs.add(new BasicNameValuePair("mypassword",mypassword.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
startActivity(new Intent(getBaseContext(), view_create_url.class));
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}
the APP show that user is authenticated but when but it is redirecting to the next page.
Please let me know what needs to be change?
You should get the entity from the response and create an input stream from it
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Then read from the input stream and check for the response needed.
Can any one please tell me where to find a simple tutorial that shows how to make an Android application that connects to a external MySQL database, and report back some data?
The tutorials I found on the Internet are not exact - they dont work or the code is not complete.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
public class main extends Activity {
/** Called when the activity is first created. */
Button login;
String name = "", pass = "";
EditText username, password;
TextView tv;
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences;
List<NameValuePair> nameValuePairs;
CheckBox check;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes")) {
username.setText(Str_user);
password.setText(Str_pass);
check.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = username.getText().toString();
pass = password.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if (name.equals("") || pass.equals("")) {
Toast.makeText(main.this, "Blank Field..Please Enter",
Toast.LENGTH_LONG).show();
} else {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(
"http://www.****.com/android/check.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail",
name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password",
pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
} catch (Exception e) {
Toast.makeText(main.this, "error" + e.toString(),
Toast.LENGTH_LONG).show();
}
if (buffer.charAt(0) == 'Y') {
Toast.makeText(main.this, "login successfull",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(main.this,
"Invalid Username or password",
Toast.LENGTH_LONG).show();
}
}
}
});
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now
// checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked()) {
editor.putString("checked", "yes");
editor.commit();
} else {
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void Move_to_next() {
// startActivity(new Intent(this, zzz.class));
}
}
I couldn't easily find a fully described example. But heres where i would start.
Look at content providers for managing your app data and accessing it and storing it for local use. The link below gives an extensive explanation of how content providers work. Though you don't have to use one.
http://www.satyakomatineni.com/akc/display?url=DisplayNoteIMPURL&reportId=2882&ownerUserId=satya
The android content provider example also shows this.
On your server at home look at providing a rest full service layer for your app to request the information from. Rather than perhaps trying to directly access the database iteself. Discussed to some extent here on what to do (not specifically how to do it) https://groups.google.com/forum/?fromgroups#!topic/android-developers/rzV9tYpQZ5Y%5B1-25%5D
Afraid i don't have coded examples.
I'm trying to implement ZXing barcode scanner into my program. After getting the scanned result, I wanted to parse the result to a method named getData() which belong to another Java class. No syntax error on IDE, but mysql.getData(contents) won't call the method no matter what. Please advise.
If I put this code under onCreate, the whole program force closed:
package com.posQR.ip;
import com.posQR.ip.MySQL;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class PosQRActivity extends Activity{
MySQL mysql;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mysql.getData("productID");
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(scanListener);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
TextView textView = (TextView)findViewById(R.id.textView1);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
try {
String contents = intent.getStringExtra("SCAN_RESULT");
Toast.makeText(getApplicationContext(), contents + "from main", Toast.LENGTH_LONG).show();
mysql.getData(contents);
String string = Double.toString(mysql.getPrice());
textView.setText(string);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please scan on the product's QR Code.", Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
private OnClickListener scanListener = new OnClickListener() {
public void onClick(View v) {
try{
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
catch (Exception e){
Toast.makeText(getApplicationContext(), "error opening scanner.", Toast.LENGTH_SHORT).show();
}
}
};
}
.
package com.posQR.ip;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.ParseException;
import android.util.Log;
import android.widget.Toast;
public class MySQL{
double Price;
private Context localContext;
public void getData(String productID) {
InputStream is = null;
String result = "";
Toast.makeText(localContext.getApplicationContext(), productID, Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",productID));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://dl.dropbox.com/u/11233767/mysqlRequest.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(localContext.getApplicationContext(), "Error converting result.", Toast.LENGTH_LONG).show();
}
//paring data
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
json_data = jArray.getJSONObject(0);
Price=json_data.getDouble("price");
}
catch(JSONException e1){
Toast.makeText(localContext.getApplicationContext(), "No City Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
public double getPrice(){
return Price;
}
}
There are many problems here, such as:
the mysql variable is null when you use it in onCreate, you must declare it.
The localContext object in MySql is never initialized, which will cause another NullPointerException when you call getData(). You should create a constructor that accepts a Context object for the MySql class, and use that constructor when you're fixing the first problem. Alternatively you could pass a Context object to getData()
the getData() method accesses the network in the main/UI thread, which will cause another Exception. Call this method in a different thread or spin off a new thread within the method itself. You may want to use an AsyncTask
I'm scratching my head at this problem that I can't seem to figure out. What I'm trying to do is extract the URL following the HTTPpost. This will allow me to go through the Oauth process.
Currently I'm extracting the whole website into my entity.
For example: The data will be posted to https://mysite.com/login and will redirect after the post to https://mysite.com/dashboard?code=3593085390859082093720
How does one extract the url?
If you need any more information or can direct me in the right direction, all is appreciated! Thank you!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener {
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Login button clicked
ok = (Button)findViewById(R.id.submit);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.result);
}
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mysite.com/login");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[unique_id]", username));
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[password]", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("CANVAS", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("CANVAS", str);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
Intent intent = new Intent(getBaseContext(), DashboardActivity.class);
startActivity(intent);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("CANVAS", "TRUE");
result.setText("Login successful");
}else
{
Log.w("CANVAS", "FALSE");
result.setText(ResponseBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
#Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
if you set a redirect handler, you can get back from the response the location the server's sending you to. here's a snippet of code I was just playing with... (and I should point out, if you DON'T set a redirect handler, you'll just get redirected to the final destination, which might be the login screen itself)
DefaultHttpClient htc = getHttpClient();
htc.setRedirectHandler(new RedirectHandler() {
#Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context)
{
Log.d(TAG, "isRedirectRequested, response: " + response.toString());
return false;
}
#Override
public URI getLocationURI(HttpResponse response, HttpContext context)
throws ProtocolException
{
Log.d(TAG, "getLocationURI, response: " + response.toString());
return null;
}
});
HttpResponse resp = null;
StringBuilder out = new StringBuilder();
try
{
HttpGet get = new HttpGet(spec);
resp = htc.execute(get);
for (Header hdr : resp.getAllHeaders())
Log.d(TAG, "header " + hdr.getName() + " -> " + hdr.getValue());
...
}
catch (Exception e)
{
Log.e(TAG, "Error connecting to " + spec, e);
return null;
}
Search for a substring in the HttpPost url