Android JSON to PHP server - php

I am trying to send all data from SQLite to PHP MySQL. I made a JSON object to send data to PHP. I am not receiving any data at PHP end.
Android Code
#Override
protected String doInBackground(Void... params) {
try {
String link = "http://localhost/Myapp/course.php";
handler.open();
Cursor c = handler.returnData();
if (c.getCount() == 0) {
Toast.makeText(context, "No Data Found", Toast.LENGTH_LONG).show();
}
obj = new JSONObject();
while (c.moveToNext()) {
String cid = c.getString(0);
String name = c.getString(1);
obj.put("cid", Integer.parseInt(cid));
obj.put("cname", name);
}
handler.close();
array = new JSONArray();
array.put(obj);
sendObj = new JSONObject();
sendObj.put("course", array);
String data = sendObj.toString();
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
PHP Code
Is there any other way to decode the json data, or should I change something in my android code ?
<?php
require_once("dbconnect.inc");
$data = array();
$data = json_decode($_POST["course"]);
$cid=$data->cid;
$cname=$data->cname;
mysql_query("insert into COURSE values($cid,$cname)") or die(mysql_error());
?>

You need to set the parameters for the URlConnection.
try this:
#Override
protected String doInBackground(Void... params) {
try {
String link = "http://localhost/Myapp/course.php";
handler.open();
Cursor c = handler.returnData();
if (c.getCount() == 0) {
Toast.makeText(context, "No Data Found", Toast.LENGTH_LONG).show();
}
obj = new JSONObject();
while (c.moveToNext()) {
String cid = c.getString(0);
String name = c.getString(1);
obj.put("cid", Integer.parseInt(cid));
obj.put("cname", name);
}
handler.close();
array = new JSONArray();
array.put(obj);
sendObj = new JSONObject();
sendObj.put("course", array);
String data = sendObj.toString();
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoInput (true);
conn.setDoOutput (true);
conn.setUseCaches (false);
conn.setRequestProperty("Content-Type","application/json");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

Related

Unable to send data from Android to PHP JSON

Below is the method in which I use to send data to PHP
public String createUser(String url,String method,List<Pair<String, String>> params){
//Making Http request
HttpURLConnection httpURLConnection = null;
StringBuffer response = null;
String lineEnd = "\r\n";
try{
if(method.equals("POST")){
URL urlPost = new URL(url);
httpURLConnection = (HttpURLConnection) urlPost.openConnection();
httpURLConnection.setDoOutput(true); //defaults request method to POST
httpURLConnection.setDoInput(true); //allow input to this HttpURLConnection
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
//httpURLConnection.setRequestProperty("Content-Type","application/json");
//httpURLConnection.setRequestProperty("Host", "192.168.0.101");
httpURLConnection.connect();
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(params.toString());
//wr.writeBytes("user_email="+userEmailText);
//wr.writeBytes(lineEnd);
wr.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination
wr.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
In my AsyncTask class:
params.add(new Pair<>("user_name", userNameText));
params.add(new Pair<>("user_email", userEmailText));
HttpHandler sh = new HttpHandler();
String jsonStrUserCreation = sh.createUser(url,"POST",params);
System.out.println("userNameText: " + userNameText);
System.out.println("userEmailText: " + userEmailText);
Log.e(TAG, "Response from userCreationURL: " + jsonStrUserCreation);
try{
JSONObject jsonObj = new JSONObject(jsonStrUserCreation);
} catch (JSONException e) {
e.printStackTrace();
}
Below is my PHP code:
<?php
require_once 'connecttodb.php';
$db = new DB();
$con = $db->db_connect();
if(isset($_POST['user_name']) && isset($_POST['user_email'])){
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$sql = "INSERT INTO user_details(user_name,user_email) VALUES('$user_name','$user_email')";
$run = mysqli_query($con,$sql);
if($run){
$response["success"] = 1;
$response["message"] = "Account successfully created";
echo json_encode($response);
}else{
$response["success"] = 0;
$response["message"] = "Account failed to be created";
echo json_encode($response);
}
}else{
$response["success"] = 2;
$response["message"] = "Failed to run inner code";
echo json_encode($response);
}
The script always return "Failed to run inner code" when I have passed in the values for user_name and user_email.
Found the solution as below. Make sure that your string is in the format below
String urlParameters = "user_name="+userNameText+"&user_email="+userEmailText;
And then call it as below:
sh.createUser(url,urlParameters);
You will see the magic.

JSONException: Value cannot be converted to JSONObject

When compiler reaches onPostExecute and trying to run execute JSONArray the line
jsonArray=jsonObject.getJSONArray("server_response");
throws an exception:
org.json.JSONException:
Value[{"code":"login_true","name":"hhh","email":"hhh"}]
of type org.json.JSONArray cannot be converted to JSONObject".
What is the correct statement?
My code:
protected String doInBackground(String... params)
{
String call_type=params[0];
if(call_type.equals("login"))
{
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String email,pass;
email=params[1];
pass=params[2];
String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
bufferedWriter.write(data);
InputStream IS = httpURLConnection.getInputStream();
BufferedReader BR= new BufferedReader(new InputStreamReader(IS));
StringBuilder stringBuilder = new StringBuilder();
String line="";
while ((line=BR.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
//IS.close();
httpURLConnection.disconnect();
Thread.sleep(500);
Log.d("Test","Test 3 pass");
return stringBuilder.toString().trim();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
**strong text**/*my onPostExecute method is as below;*/***
#Override
protected void onPostExecute(String json)
{
try
{
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray=jsonObject.getJSONArray("server_response");
*******//here exception coming org.json.JSONException: Value [{"code":"login_true","name":"hhh","email":"hhh"}] of type org.json.JSONArray cannot be converted to JSONObject and compiler jumps to the exception part*******
JSONObject JO= jsonArray.getJSONObject(0);
String code=JO.getString("code");
String message=JO.getString("message");
if(code.equals("reg_true"))
{
ShowDialog("Registration Success",message,code);
}
else if (code.equals("reg_false"))
{
ShowDialog("Registration Fail",message,code);
}
else if(code.equals("login_true"))
{
Intent intent= new Intent(activity,HomeActivity.class);
intent.putExtra("message",message);
activity.startActivity(intent);
}
else if(code.equals("login_false"))
{
ShowDialog("Login Error,",message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
**/* php scrip is as follows: (login.php)*/**
<?php
require"init.php";
$email=$_POST["email"];
$pass=$_POST["pass"];
$sql_query="select name, email from beneficiary_details where email like '".$email."' and pass like '".$pass."' ";
$result=mysqli_query($con,$sql_query);
$response = array();
$rowcount=mysqli_num_rows($result);
//print_r( $rowcount);
if($rowcount > 0)
{
$row=mysqli_fetch_row($result);
$name=$row[0];
$email=$row[1];
$code="login_true";
array_push($response,array("code"=>$code,"name"=>$name,"email"=>$email));
echo json_encode($response);
}
else
{
$code="login_false";
$message="User not found, Please try again..";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode($response);
}
mysqli_close($con);
?>
**plz find out where I am doing mistake???
Assuming the JSON returned from the server is:
[{"code":"login_true","name":"hhh","email":"hhh"}]
To parse the above JSON:
try {
JSONArray jsonArray = new JSONArray(json);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
String name = jsonObject.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}

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

Get data from mysql to android with php

I am currently trying to develop an app that among other things can send and receive data from a mysql server.
The app calls a php script which makes the connection to the mysql server. I have successfully developed the sending part and now I want to retrieve data from mysql and display it on an android phone.
The mysql table consists of 5 columns:
bssid
building
floor
lon
lat
The php file getdata.php contains:
<?php
$con = mysql_connect("localhost","root","xxx");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$sql = mysql_query("SELECT building,floor,lon,lat FROM ap_location WHERE bssid='00:19:07:8e:f7:b0'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close(); ?>
This part is working fine, when tested in a browser.
The java code for connecting to php:
public class Database {
public static Object[] getData(){
String db_url = "http://xx.xx.xx.xx/getdata.php";
InputStream is = null;
String line = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("bssid",bssid));
Object returnValue[] = new Object[4];
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost, localContext);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}
String result = "";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
returnValue[0] = (json_data.getString("building"));
returnValue[1] = (json_data.getString("floor"));
returnValue[2] = (json_data.getString("lon"));
returnValue[3] = (json_data.getString("lat"));
}catch(JSONException e){
Log.e("log_tag", "Error parsing data" +e.toString());
}
return returnValue;
}
}
This is a modified code used to send data to the mysql server, but something is wrong.
I've tried to test it by setting different returnValues in the code and this shows me that the part with the httpclient connection does not run.
Can you guys help me?
I hope this is not too confussing, and if you want I can try to explain it futher.
Use HttpGet instead of HttpPost and parse your url.
Here is a class I always use to GET
public JSONObject get(String urlString){
URL currentUrl;
try {
currentUrl = new URL(currentUrlString);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
InputStream in;
BufferedReader streamReader = null;
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
try {
urlConnection = (HttpURLConnection) currentUrl.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
while ((inputStr = streamReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
if(null != streamReader){
try {
streamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
return new JSONObject(responseStrBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Try to test with get("http://echo.jsontest.com/key/value");

Categories