Android app not inserting values into MySQL through PHP - java

I am making an app which performs a transaction through a PHP script stored in the www folder of Wampserver of localhost.
But when I perform the transaction values are not inserted into the database and logcat displays this error:
07-26 16:55:54.036: E/Buffer Error(5511): Error converting result java.lang.NullPointerException
07-26 16:55:54.037: E/JSON Parser(5511): Error parsing data org.json.JSONException: End of input at character 0 of
But my app does not even crash and says the transaction is successful, which is called onPostExecute of my AsyncTask.
Please help me found out the bug that is causing unsuccessful insertion into the database.
I have two classes JSONParser and NewProductActivity as follows:
This one is NewProductActivity.java:
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
// url to create new product use wireless lan adapter wifi ipv4 address using ipconfig
// String url_create_product = "http://192.168.0.100/toll_system/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
String first_name;
String last_name;
String toll_no;
String toll_location;
String trans_amt;
String v_license_no;
String make_model;
String v_type;
String email_id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
TextView tv=(TextView)findViewById(R.id.textView1);
String contents = getIntent().getStringExtra("KEY1");
String ip_address=getIntent().getStringExtra("KEY2");
/* String arr[]=contents.split(",");
String trans_receipt_no=arr[0];
String firstname=arr[1];
String lastname=arr[2];
String toll_no=arr[3];
String toll_location=arr[4];
String trans_amt=arr[5];
String v_license_no=arr[6];
String make_model=arr[7];
String v_type=arr[8];*/
Toast toast = Toast.makeText(this, "Content:" + contents , Toast.LENGTH_LONG);
toast.show();
new CreateNewProduct().execute(contents,ip_address);
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Woooohoooo...");
Log.d("Perform:", "Performing");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// String name = inputName.getText().toString();
// String price = inputPrice.getText().toString();
// String description = inputDesc.getText().toString();
String contents=args[0];
String ip_address=args[1];
String arr[]=contents.split(",");
Log.d("Inside doInBackground :", contents);
//String trans_receipt_no=arr[0];
first_name=arr[0];
Log.d("First_name", first_name);
last_name=arr[1];
Log.d("Last_name", last_name);
toll_no=arr[2];
toll_location=arr[3];
trans_amt=arr[4];
v_license_no=arr[5];
make_model=arr[6];
v_type=arr[7];
email_id=arr[8];
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("name", name));
//params.add(new BasicNameValuePair("price", price));
//params.add(new BasicNameValuePair("description", description));
// params.add(new BasicNameValuePair("trans_receipt_no", trans_receipt_no));
params.add(new BasicNameValuePair("first_name", first_name));
params.add(new BasicNameValuePair("last_name", last_name));
params.add(new BasicNameValuePair("toll_no", toll_no));
params.add(new BasicNameValuePair("toll_location", toll_location));
params.add(new BasicNameValuePair("trans_amount", trans_amt));
params.add(new BasicNameValuePair("v_license_no", v_license_no));
params.add(new BasicNameValuePair("v_make_model", make_model));
params.add(new BasicNameValuePair("v_type", v_type));
params.add(new BasicNameValuePair("email_id", email_id));
// getting JSON Object
String url_create_product = "http://"+ip_address+"/toll_system/create_product.php";
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
// Log.d("Create Response", json.toString());
// check for success tag
/* try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
//startActivity(i);
String s="Transaction done!";
Toast toast = Toast.makeText(getApplicationContext(),"Status:"+s, Toast.LENGTH_LONG);
toast.show();
// closing this screen
finish();
} else {
Toast toast = Toast.makeText(getApplicationContext(),"Status:Failed", Toast.LENGTH_LONG);
toast.show();
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
*/
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("Transaction done!!!");
TextView tv1=(TextView)findViewById(R.id.textView3);
tv1.setText(first_name+" "+last_name);
TextView tv2=(TextView)findViewById(R.id.textView5);
tv2.setText(make_model);
TextView tv3=(TextView)findViewById(R.id.textView7);
tv3.setText(v_license_no);
TextView tv4=(TextView)findViewById(R.id.textView9);
tv4.setText("Rs."+trans_amt);
pDialog.dismiss();
}
}
}
And this is JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}

Related

org.json.JSONException: Value Data of type java.lang.String cannot be converted to JSONObject

This is my code for Android:
public void SendDataToServer(final String name, final String email, final String password){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickPassword = password;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Configs.signup);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Submit Successfully";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(result, "Value");
try {
JSONObject jo = new JSONObject(result);
String status = jo.optString("status");
if (status.equals("0")) {
Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
} else if (status.equals("1")) {
Intent intent = new Intent(Signup.this, Login.class);
startActivity(intent);
Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
finish();
} else if (status.equals("2")) {
Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
}
//}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email, password);
}
This is the error:
07-21 12:55:35.297 24973-24973/com.futegolo.igomessenger W/System.err:
org.json.JSONException: Value Data of type java.lang.String cannot be
converted to JSONObject
This is my json response
{"status":0}
This is because you are not returning the actual response from service in doInBackground() method. You are returning as
return "Data Submit Successfully"
And when you convert that string in onPostExecute() method obviously that is not valid JsonObject
Replace your code after this "HttpEntity entity = response.getEntity();"
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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();
}
And rather returning your hard coded string return result. Hope that helps.
for further reference you can follow below links
https://stackoverflow.com/questions/4457492/how-do-i-use-the-simple-http-client-in-android
Use the code as following:
public void SendDataToServer(final String name, final String email, final String password){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickPassword = password;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Configs.signup);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StringBuffer result= new StringBuffer();
BufferedReader in = new BufferedReader(
new InputStreamReader(entity.getContent()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(result, "Value");
try {
JSONObject jo = new JSONObject(result);
String status = jo.optString("status");
if (status.equals("0")) {
Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
} else if (status.equals("1")) {
Intent intent = new Intent(Signup.this, Login.class);
startActivity(intent);
Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
finish();
} else if (status.equals("2")) {
Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
}
//}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email, password);
}
Appache has already provided a Util class for that called EntityUtils.
Replace return "Data Submit Successfully" with this code
String responseText = EntityUtils.toString(httpResponse.getEntity());
EntityUtils.consume(httpResponse.getEntity());
return responseText;

MySQL Query from Android app to remote database

I want to carry out the following php query on my remote database
$result = mysqli_query($con->myconn, "SELECT id, stake, user, returns, teams, status FROM `bet` WHERE user = $user") or die(mysql_error());
My only problem is I'm not sure how to modify my JSONParser class so that I can simultaneously pass the user parameter to the database and receive the results. It currently looks like this and allows me only to either retrieve values or send values.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
CODE :
public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "***";
JSONParser jParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_GAMELIST = "gamelist";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
JSONArray allgames = null;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
// Hashmap for ListView
ArrayList<HashMap<String, String>> gamesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
*/
/**
* Before starting background thread Show Progress Dialog
*//*
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Bets. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
*/
/**
* getting All products from url
*//*
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Games: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Games
allgames = json.getJSONArray(TAG_GAMELIST);
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
id = c.getString(TAG_ID);
stake = c.getString(TAG_STAKE);
returns = c.getString(TAG_RETURNS);
status = c.getString(TAG_STATUS);
teams = c.getString(TAG_TEAMS);;
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, teams);
map.put(TAG_STAKE, stake);
map.put(TAG_RETURNS, returns);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
gamesList.add(map);
}
// } else {
// no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return "";
}

Variables Not Being Sent To Server

I'm trying to insert data into the database from my app. I can fetch data, but when I try to pass variables to my server, I get the "Required field(s) is missing" error.
I've done this before with a different app, but that was before I had SSL installed on my website. Is there any chance SSL could be stopping the variables.
I tried keeping the code as simple as possible for testing purposes but I just can't figure it out. I have re-done several tutorials just to make sure I'm not making errors, but clearly I'm going wrong somewhere. Any help much appreciated!
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "name"));
params.add(new BasicNameValuePair("price", "2"));
params.add(new BasicNameValuePair("imgurl", "imgurl"));
JSONObject json = jsonParser.makeHttpRequest("http://myserver.com",
"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
finish();
} else {
Log.d("TEST", "Failed to create product");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
PHP Code:
<?php
$response = array();
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['imgurl'])) {
$name = "joey";
$price = "3";
$imgurl = "blowey";
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysqli_query("INSERT INTO products(name, price, imgurl) VALUES('$name', '$price', '$imgurl')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
JSON Parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Try to replace:
post.setEntity(new UrlEncodedFormEntity(dataToSend));
with
post.setRequestBody(dataToSend);

Unable to insert row from Android to MySQL using PHP

I am trying to insert data from android to MySQL but it does not show any error in logcat but displays the json message in the app.
Here is my PHP script.
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
require("config.inc.php");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['userName']) && isset($_POST['userContact']) && isset($_POST['userAddress']) && isset($_POST['userStore']) && isset($_POST['userRequest'])) {
$userName = $_POST['userName'];
$userContact = $_POST['userContact'];
$userAddress = $_POST['userAddress'];
$userStore = $_POST['userStore'];
$userRequest = $_POST['userRequest'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO userrequests(userName, contactNumber, userAddress, storeList, requestBody) VALUES('$userName', '$userContact', '$userAddress', '$userStore', '$userRequest')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Here is my JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.i("log_tag","Line reads: " + line);
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Here is my MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText userName, userContact, userAddress, userRequest;
private Spinner userStore;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
userName = (EditText)findViewById(R.id.EditName);
userContact = (EditText)findViewById(R.id.EditContact);
userAddress = (EditText)findViewById(R.id.EditAddress);
userStore = (Spinner)findViewById(R.id.StoreSpinner);
userRequest = (EditText)findViewById(R.id.EditRequest);
mRegister = (Button)findViewById(R.id.SubmitButton);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = userName.getText().toString();
String usercontact = userContact.getText().toString();
String useraddress = userAddress.getText().toString();
String userstore = userStore.getSelectedItem().toString();
String userrequest = userRequest.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userContact", usercontact));
params.add(new BasicNameValuePair("userAddress", useraddress));
params.add(new BasicNameValuePair("userStore", userstore));
params.add(new BasicNameValuePair("userRequest", userrequest));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
And the error I am getting inside the emulator is this json message in my php script
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
I couldn't find the reason why new row cannot be inserted into MySQL.
POST can not be used by external applications. You have to use GET instead.

Android login authentication to remote MySQL database

Here's my java code:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList < NameValuePair > postParameters = new ArrayList < NameValuePair > ();
postParameters.add(new BasicNameValuePair("username", txtUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", txtPassword.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.sampleweb.com/imba.php", postParameters);
String res = response.toString();
// res = res.trim();
res = res.replaceAll("\\s+", "");
//error.setText(res);
if (res.equals("1")) {
txtError.setText("Correct Username or Password");
//Intent i = new Intent(CDroidMonitoringActivity.this, MenuClass.class);
//startActivity(i);
} else {
txtError.setText("Sorry!! Incorrect Username or Password");
}
} catch (Exception e) {
txtUsername.setText(e.toString());
}
}
});
I thinks there's an error in my res.equals because it keeps saying "Invalid Username or password" even though I've entered the correct username or password. But when I change the res.equals to res.contains it keeps saying "correct username or password" even though i've entered the correct username and password. I really need your help. to all mastered in android development. Hope you could help me on this. And also, when i change the txtError.setText(res) just to check if it returns 1 and 0 it does not.
This needs to be done in the php file not in the Android code:
<?php
define('DB_USER', "root"); //username used to connect to the database.
define('DB_PASSWORD', ""); //password used to connect to the database.
define('DB_DATABASE', "dbname"); //database name
define('DB_SERVER', "127.0.0.1"); //database server address
?>
Using a JSON parser, you would then need to parse the data on the server. You need to use something similar to the following:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
//Method to connect to the database
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
//The following works just as in normal GET and POST methods
try {
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
In a second class, you would then need to define the connection parameters as follows:
public class UserFunctions {
private JSONParser jsonParser;
private static String loginURL = "http://www.sampleweb.com/login.php";
private static String registerURL = "http://www.sampleweb.com/register.php";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
In addition to this, you would finally need to use your application classes to parse data and show it to the users. There are several online tutorials on how this can be done.
Hope this helps :)
It is really difficult to figure out what is going on with out the response from server. To debug the issue, for both valid and invalid user name/password combinations check the response of http://www.sampleweb.com/imba.php using a POST library like curl or Postman

Categories

Resources