json encode array from php sql server and convert to Android - php

Hi i am new in android php client server. At present, i am doing the response from php sql server sending to Android client multiple result from sql row. Previously, i sending a simple string and receive android like below:
$result_data = array(
'ResultArray' => 'success',
);
#Output the JSON data
echo json_encode($result_data);
Then in android:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
String resultLoging = jsonObject.getString("ResultArray");
Now i want to receive from database having 3 columns: id, phone, name. How would i do that? Thank for your helping

use the following format in php
$result = mysql_query("SELECT *FROM tablename") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// products node
$response["details"] = array();
while ($row = mysql_fetch_array($result))
{
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
array_push($response["details"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
In android
get success value
int success = json.getInt(TAG_SUCCESS);
get the datas using following format
JSONArray spi = json.getJSONArray("details");
Use a for loop to get the object values in the array
for (int i = 0; i < spi.length(); i++)
{
JSONObject c = spi.getJSONObject(i);
id = c.getString("id");
}

Use JSONArray for multiple json result :
JSONArray jsonArray = jsonObject.getJSONArray("ResultArray");
Iterate JSONArray and get value from JSONObject :
for (int i=0;i<jsonArray.length();i++){
JSONObject json = jsonArray.getJSONObject(i);
String id = json.getString("id");
String phone = json.getString("phone");
String name = json.getString("name");
}

just found this, would be the best for my question
https://stackoverflow.com/a/3563464/1345454
$results = array();
while($row = mysql_fetch_array($sql))
{
$results[] = array(
'title' => base64_decode($row['title']),
'price' => $row['price'],
'seller_user' => $row['user']
);
}
$json = json_encode($results);

try this
$result_data = array(
'ResultArray' => 'success',
);
echo json_encode(array('result'=>$result_data));
in android
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("url of php file");
JsonArray arry = json.getJSONArray("result");
JSONObject c = arry .getJSONObject(0);
String resultarr= c.getString("ResultArray");
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();
// System.out.println(json);
} 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

Delete row from MySQL table via android

I need to delete an item from a list view on android when clicked. The thing is, my table is not on the phone(SQLite), but on the server. So I'm using a PHP code for this.
I have set up an onClickListener.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v,int position, long id) {
Show_Alert_box(v.getContext(),
"Please select action.", position);
}
});
public void Show_Alert_box(Context context, String message, int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context)
.create();
//alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DBHandlerComments dbhelper = new DBHandlerComments(Comments.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
try{
JSONObject json2 = JSONParser.makeHttpRequest(urlDelete, "POST", params);
try {
int success = json2.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
//adapter.notifyDataSetChanged();
db.close();
}catch(Exception e){
}
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage(message);
alertDialog.show();
}
This is my JSONParser's makehttprequest code:
public static 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;
//from here
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;
}
`
And this is my PHP code:
$response = array();
if (isset($_POST['id'])) {
$id = $_POST['id'];
// include db connect class
$db = mysql_connect("localhost","tbl","password");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("shareity",$db);
// mysql update row with matched id
$result = mysql_query("DELETE FROM comments_activities WHERE id = $id");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
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);
}
I'm adding the params like this:
params.add(new BasicNameValuePair(KEY_ID, id));
params.add(new BasicNameValuePair(KEY_AID, aid));
params.add(new BasicNameValuePair(KEY_ANAME, an));
params.add(new BasicNameValuePair(KEY_EVENT, ev));
params.add(new BasicNameValuePair(KEY_COMMENT, cb));
params.add(new BasicNameValuePair(KEY_USER, cby));
params.add(new BasicNameValuePair(KEY_TIME, cd));
I don't get any result. Can I know why?
I have noticed that you add unneeded parameters although you just need the id.
This is a simple code for deleting the given id, you can try it. If it worked, the error would be in your android code.
<?php
$servername = "your servername";
$username = "your username";
$password = "your password";
$dbname = "your dbname";
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname, $link);
$id=$_POST['id'];
$result = mysql_query("DELETE FROM table_name WHERE id=$id", $link);
$response["success"] = 1;
$response["message"] = "Deleted successfully!";
echo json_encode($response);
?>
Change the servername to your database url and so on the other information.

PHP script to connect MYSQL database to Android DevicePHP Error

I am having a problem with the connection to my PHP script, it keeps on returning "Oops! Its this one." - which is my error message if it could not inset into the mySQL database.
///PHP SCRIPT
<?php
$con = mysqli_connect("postgrad.nmmu.ac.za", "Christian", "Christian123", "drmdb");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// array for JSON response
$response = array();
$PointerID = $_POST['PointerID'];
$ActivityID = $_POST['ActivityID'];
$StartX = $_POST['StartX'];
$EndX = $_POST['EndX'];
$StartY = $_POST['StartY'];
$EndY = $_POST['EndY'];
$Content = $_POST['Content'];
$Head = $_POST['Head'];
$NodeID = $_POST['NodeID'];
$Step = $_POST['Step'];
$result = mysqli_query(
$con,
"INSERT INTO pointersequence(PointerID, ActivityID, StartX, StartY, EndX, EndY, Content, Head, NodeID, Step) VALUES('$PointerID','$ActivityID', '$StartX', '$StartY', '$EndX', '$Content', '$Head', '$NodeID', '$Step')"
);
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Person successfully created hahaha.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! Its this one.";
// echoing JSON response
echo json_encode($response);
}
mysql_close($con);
?>
OUTPUT: Oops! Its this one.
//Method in Android to Insert
private void UploadPointerSequence() {
int num11 = 1;
final String URL12 = "http://drm.csdev.nmmu.ac.za/UploadPointerSequence.php";
for (int x = 0; x <= PointerSequence.size() - 1; x++) {
List<NameValuePair> param12 = new ArrayList<NameValuePair>();
param12.add(new BasicNameValuePair("PointerID", String
.valueOf(num11)));
num11++;
param12.add(new BasicNameValuePair("ActivityID", String
.valueOf(PointerSequence.get(x).getActivityID())));
param12.add(new BasicNameValuePair("StartX", String
.valueOf(PointerSequence.get(x).getStartX())));
param12.add(new BasicNameValuePair("StartY", String
.valueOf(PointerSequence.get(x).getStartY())));
param12.add(new BasicNameValuePair("EndX", String
.valueOf(PointerSequence.get(x).getEndX())));
param12.add(new BasicNameValuePair("EndY", String
.valueOf(PointerSequence.get(x).getEndY())));
param12.add(new BasicNameValuePair("Content", PointerSequence
.get(x).getContent()));
param12.add(new BasicNameValuePair("Head", String
.valueOf(PointerSequence.get(x).isHead())));
param12.add(new BasicNameValuePair("NodeID", String
.valueOf(PointerSequence.get(x).getNodeID())));
param12.add(new BasicNameValuePair("Step", String
.valueOf(PointerSequence.get(x).getStep())));
JSONObject json = jsonParser.makeHttpRequest(URL12, "POST",
param12);
}
}
>JSON CLASS:
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;
}
}
Thanks in Advance!

Save the id only of a row in the SQLite android database

My android app is getting & writing data to the server and to the SQlite database.
I am fetching values for jobaddress.id = 1from server using a query (below). The values in SELECTstatement are displaying perfectly in the UI of android app however when I press "Save", instead of values from the server, I need to save the id 1 from the server in the local database without shwoing the id in the UI.
PHP sript (query only) for retrieving data from server:
$tsql = "SELECT tbl_manufacturers.manufacturers_name, tbl_appliances_models.appliances_models_name, tbl_appliances.appliances_serial, tbl_appliances.appliances_id, jobaddress.id
FROM jobaddress INNER JOIN
tbl_appliances ON jobaddress.id = tbl_appliances.appliances_jobaddress_id LEFT OUTER JOIN
tbl_appliances_models INNER JOIN
tbl_manufacturers ON tbl_appliances_models.appliances_models_manufacturers_id = tbl_manufacturers.manufacturers_id ON
tbl_appliances.appliances_models_id = tbl_appliances_models.appliances_models_id
WHERE (tbl_appliances.appliances_companies_id = 1) AND (jobaddress.id = 1)";
Showing data using JSON Parser:
public void getJobAddress()
{
String result = null;
InputStream isr = null;
try
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://datanetbeta.multi-trade.co.uk/tablet/getJobAddress.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e)
{
Log.e("Log_tag", "Error in hhtp connection " + e.toString());
}
//convert Response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result " + e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++)
{
JSONObject json = jArray.getJSONObject(0);
s = json.getString("address1");
t = json.getString("address2");
u = json.getString("postcode");
}
tvJbAddrs1.setText(s);
if(t == null)
{
tvJbAddrs2.setText("");
}
else
{
tvJbAddrs2.setText(t);
}
tvJbPostcode.setText(u);
}
catch (Exception e)
{
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
} //getJobAddress() ends

Sending and receiving json from android app to php script?

I am new to android development and I am trying to make a login page which sends the password and username to a php script as a json array and the php script returns a json array response which contains the meassage accordingly.
I have made a android code as:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Log.v("Received","Response received . . ."+re);
// Check your log cat for JSON reponse
Log.v("Response: ", re.toString());
int success = re.getInt("success");
if (success == 1) {
return 1;
}
else{
return 0;
}
}
catch(Exception e){ e.getMessage(); }
}
The JsonParser doPost code is as follows:
public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
Log.v("entity",""+entity);
HttpResponse response;
try{
response = httpclient.execute(request);
Log.v("REceiving","Received . . .");
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
Log.v("RESPONSE",""+is);
}
catch(Exception e){
Log.v("Error in response",""+e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.v("Reader",""+reader.readLine());
while ((line = reader.readLine()) != null) {
Log.v("line",""+line);
sb.append(line + "\n");
}
Log.v("builder",""+sb);
is.close();
json = sb.toString();
} catch (Exception e) {
Log.v("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have the php script as:
$response = array();
$con=mysqli_connect("localhost","uname","password","db_manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password'];
$query = "SELECT mm_emp_id,mm_password FROM employee_master WHERE mm_emp_id='$empid'and mm_password='$pass'";
$result = mysqli_query($con, $query);
if(count($result) > 0){
$response["success"] = 1;
$response["message"] = "";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
echo json_encode($response);
}
}
I am getting undefined index at the line where I check for isset(). What am I doing wrong in receiving the json in php script?
If you can see I have used a link for my help
Please do help me out.
In the doPost method you don't use the JSON object (JSONobject c) that contains the variables
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://test.myhodo.in/index.php/test/execute";
#Override
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
Main Activity
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "hello");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}

android username password send through json to php-->sql

im trying to find a way to post username and password using json rather than normal http post that im currently using. i have being going through most of the tutorials and examples to undestand but yet i was unable to get an idea. i have json phasers available to get the data from my sql but not the post json.
thank you for the help
following is the currently used json post
EditText uname = (EditText) findViewById(R.id.log_Eu_name);
String username = uname.getText().toString();
EditText pword = (EditText) findViewById(R.id.log_Epass);
String password = pword.getText().toString();
String result = new String();
result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("username", username));
nameValuePairs
.add(new BasicNameValuePair("password", password));
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.loshwickphotography.com/log.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("SENCIDE", "Execute HTTP Post Request");
String str = inputStreamToString(
response.getEntity().getContent()).toString();
Log.w("SENCIDE", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("SENCIDE", "TRUE");
Toast.makeText(getApplicationContext(),
"FUking hell yeh!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Sorry it failed", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
if (result != null) {
JSONArray jArray = new JSONArray(result);
Log.i("log_tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
}
} else {
Toast.makeText(getApplicationContext(), "NULL",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
private Object inputStreamToString(InputStream is) {
// TODO Auto-generated method stub
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;
}
});
Is this correct which i have written?
how to write the Php for this?
use this
JSONObject myjson=new JSONObject();
myjson.put("userName", "someOne");
myjson.put("password", "123");
and StringEntity se = new StringEntity(myjson.toString());
and httpPost.setEntity(se);

Categories