MySQL Query from Android app to remote database - java

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 "";
}

Related

Android app not inserting values into MySQL through PHP

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;
}
}

How to parse a large number of nested json objects with different values?

Here is a link: http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js with JSON objects. There are 261 objects with unique value (strings). How to get each object with numbers (2101, 2107 etc.) and 2 strings inside (picture and title)?
So this is my technologies AsyncTask:
ListView listView;
TechnologiesAdapter adapter;
ArrayList<Technologies> techList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView);
techList = new ArrayList<Technologies>();
new TechnologiesAsyncTask().execute("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
}
public class TechnologiesAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
//How to get the other objects?
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
You can get all of the names to a json array, then get every json object from the names in json array.
Following is a simple example.
private class DataAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("technology");
JSONArray nameArray = jsonObject.names();
final int size = nameArray.length();
for (int i = 0; i < size; i++) {
JSONObject object = jsonObject.getJSONObject(nameArray.getString(i));
// get id, title and pictures, etc
Log.d(TAG, nameArray.getString(i) + " " + object.getString("title") + " " + object.getString("picture"));
}
} catch (IOException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
After you get the "technology" object just create another JSONObject from that like this:
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
// Get the 2101 object
JSONObject jObj3 = jObj2.getJSONObject("2101");
// Get the picture and title of 2101
String picture = jObj3.getString("picture");
String title = jObj3.getString("title");
Your JSON looks like it might be better suited to use a JSONArray instead of nested JSONObjects though.
JSONObject jPages=jQuery.getJSONObject("pages");
Iterator < String> keys = jPages.keys();
while(keys.hasNext()){
JSONObject jPageId=jPages.getJSONObject(keys.next());
//Action need to be performed
}

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 Sending String in JSON format to Server

i have wrote a method to send some data to server and receive a integer value :
private void sendOrder(Order order,String cid) {
InputStream inputStream = null;
String result = "";
int statusCode = 0;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(send_url);
JSONArray jsonArray = new JSONArray();
for (OrderDetails detail : order.getOrders()) {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("c_id", cid);
jsonObject.accumulate("r_id", String.valueOf(detail.getR_id()));
jsonObject.accumulate("f_id", String.valueOf(detail.getF_id()));
jsonObject.accumulate("count",
String.valueOf(detail.getCount()));
jsonArray.put(jsonObject);
}
String json = jsonArray.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = Util.convertInputStreamToString(inputStream);
else
result = "0";
} catch (Exception e) {
Log.d("send order", e.toString());
}
Log.d("order result", result);
return Integer.parseInt(result);
}
the cid is numbers stored in a string like : "30111"
but in the server there is a problem in receiving c_id. its's value in server is like :"c_id":"\"30111\""
i want to c_id to be in the server as same as it is in the client.
how can i fix that ? UPDATE this is my json string in android log :
[{"count":"1","r_id":"8","f_id":"10033","c_id":"\"30111\""},{"count":"2","r_id":"8","f_id":"10034","c_id":"\"30111\""}]
This is my code, working really fine
Make a class -
public class AddQuery extends AsyncTask<Void, Void, Void> {
private Context context;
private ProgressDialog pd;
private String url;
private String jsonResult;
private String qrs;
private String cId;
public AddQuery(Context context, String qrs, String cid) {
// TODO Auto-generated constructor stub
this.context = context;
this.qrs = qrs;
this.cId = cid;
url = "http://" + context.getResources().getString(R.string.url)
+ "/ques.php";
pd = new ProgressDialog(context);
pd.setIndeterminate(true);
pd.setMessage("Retrieving Data..");
pd.setCancelable(false);
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences prefs = context.getSharedPreferences("com.multisoft",
Context.MODE_PRIVATE);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("go", "add"));
params.add(new BasicNameValuePair("qrs", qrs));
params.add(new BasicNameValuePair("cid", cId));
params.add(new BasicNameValuePair("uid", prefs.getString("userID", "0")));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent())
.toString();
}
catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
JSONObject jsonResponse;
jsonResponse = new JSONObject(jsonResult);
//do what you want to do here from text apeared from your php and stored in jsonResult
String c_id = jsonResponse.optString("c_id");
}
execute the above class in your main activity like this-
new AddQuery(MyActivity.this, "4","23").execute();

Database is not updated even after data post from Android App was successful

I have an android app that I am programming to post an array of data to a php file in local server. The data is in the format as bellow.
Name1->Quantity1
Name2->Qunatity2
I am trying to send it as json array but the problem is that whenever I am sending the data it shows that it is successful in posting that data. However i am not able to see any change of database that was suppose to be as a result of data that was sent form the android app. I will be thankful if someone guides or solves this problem of mine. please help me in this.
Bellow are the classes i am using to send and receive data
This is the class which is sending the data
public class Thirdscreen extends Activity {
private static String url = "http://10.0.2.2/bootstrap-dist/postingdata.php";
public ArrayList<QantityModelProduct> quantitymodel=new ArrayList<QantityModelProduct>();
// Progress Dialog
private ProgressDialog pDialog;
// Json parser object
JSONParser jsonParser = new JSONParser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdscreen);
QantityModelProduct qmp;
TextView showCartContent = (TextView) findViewById(R.id.showCart);
TextView showCarttotal = (TextView) findViewById(R.id.showtotal);
Button btn = (Button) findViewById(R.id.subtractQuantity);
final Controller aController = (Controller) getApplicationContext();
int cartSize = aController.getCart().getCartSize();
String showString = "";
int total = 0;
for (int i = 0; i < cartSize; i++) {
String pName = aController.getCart().getProducts(i)
.getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int quantity = aController.getCart().getProducts(i)
.getProductQuantity();
int dataProQuantityStore = aController.getCart()
.getProducts(i).getDatabaseProductQuantity();
String pDisc = aController.getCart().getProducts(i)
.getProductDesc();
total = total + (pPrice * quantity);
showString += "\n\nProduct Name : " + pName + "\n" + "Price : "
+ pPrice + "\t" + "Quantity: " + quantity + "\n"
+ "Discription : " + pDisc + ""
+ "\n -----------------------------------";
//databaseQuantity-Current quantity
int finalVal = dataProQuantityStore - quantity;
String finalstringValue=""+finalVal;
qmp=new QantityModelProduct(pName,finalstringValue);
quantitymodel.add(qmp);
}
showCarttotal.setText("Your Total is: " + total + "Tk");
showCartContent.setText(showString);
final int productSize=quantitymodel.size();
Toast.makeText(getApplicationContext(),"Array size: "+productSize, Toast.LENGTH_SHORT).show();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new getQuantity().execute();
}
});
}
class getQuantity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Thirdscreen.this);
pDialog.setMessage("Processing your request..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONArray jsonArray = new JSONArray();
for (int i=0; i < quantitymodel.size(); i++) {
jsonArray.put(quantitymodel.get(i).getJSONObject());
}
jsonParser.getandpostJSONFromUrl(url, "POST",jsonArray);
return null;
}
#Override
protected void onPostExecute(String file_url) {
final Controller aController = (Controller) getApplicationContext();
// dismiss the dialog once done
pDialog.dismiss();
aController.getCart().clearCart();
aController.getProductsArraylist().clear();
Toast.makeText(getBaseContext(), "I am in second loop", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getBaseContext(), FirstScreen.class);
finish();
startActivity(i);
}
}
}
public class QantityModelProduct {
private String ProductName;
private String ProductQuantity;
public QantityModelProduct(String productName, String productQuantity) {
ProductName = productName;
ProductQuantity = productQuantity;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Name", ProductName);
obj.put("Quantity", ProductQuantity);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
The following is the Json Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(name.toString()));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpPost.setHeader("jsonArray",json.toString());
HttpEntity httpEntity = httpResponse.getEntity();
int response = httpResponse.getStatusLine().getStatusCode();
is = httpEntity.getContent();
Log.e("posting Status", "Post status: " + response);
}
if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
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;
}
}
and lastly the php file that is suppose to receive those datas.
?php
define('DB_NAME', 'sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
if (isset($_POST['jsonArray'])){
$jArray = json_decode($jsonArray,true);
foreach ($jArray['jsonArray'] as $obj) {
$ProductName = $obj['Name']; //String
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
echo $ProductName." ".$ProductQuantity;
}
}else {
echo 'empty';
}
?>
Firstly, you should not be comparing strings using ==
Try this!
if (method.equals("POST"))
Next, to debug, see what data you are sending via the Android app to the PHP webservice, by sending the same request as response. So you know exactly if you are sending the data.
If the above step works fine, means the issue is on the PHP end. Use http://hurl.it or Postman client in Chrome to do a Post via browser, and then debug the PHP code. See if the data is being inserted.
This should solve your problem.
Nithin

Categories

Resources