Android Json to Server sends not data - php

I got a problem. I read a lot here but unfortunately I can't get an answer for my problem.
I want to send a Json post to my Server. The Server should then save the string in my database.
This is my server code so far:
<?php
include('db_connect.php');
$db = new _DB_Connect();
$db->connect();
if(isset($_POST['regid'])){
$data = json_decode($_POST['regid']);
$save_entry = "insert into gcm_users (gcm_regid) values ('$data')";
mysql_query($save_entry) or die (mysql_error());
}else{
echo 'no data get';
}
?>
And this is my method on my android phone.
public String sendJson(View view){
InputStream inputStream = null;
String result = "";
String url2 = "http://192.168.0.5/control_center/functions/incomming.php";
TextView textView_result;
textView_result = (TextView) findViewById(R.id.textView_result);
//strict mode for networking
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url2);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type" , "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("regid", "blablabla");
String json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null) {
System.out.println(convertInputStreamToString(inputStream));
}
else {
result = "Did not work!";
}
textView_result.setText(httpResponse.toString());
System.out.println(jsonObject.toString());
}catch(JSONException e){
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
Now the
System.out.println(convertInputStreamToString(inputStream));
tells me that I got no data
echo 'no data get';
So I get a response form the server but I could find my error, why the post data could not be retrieved.
Would appreciate any help or hints. Thank you.

try this...
JSONObject jsonObject = new JSONObject();
jsonObject.put("regid", "blablabla");
String json = jsonObject.toString();
MultipartEntityBuilder multiPart = MultipartEntityBuilder.create();
multiPart.addTextBody("regid",json);
or
multiPart.addTextBody("regid","blablabla");
httpPost.setEntity(multiPart.build());

Related

Android Java jSON UTF-8 httpResponse Problems

I've got a problem with german characters in utf-8. I work with a MySQL database from which I'll get my data with PHP. The php script converts the data into a json object and sent it to the application. The database contains doubles and strings. First the application send a string with the name of a topic. The php search in the db for the topic, convert the content into a json and send it to the application.
I tried to sent the data without characters like "ä,ü,ö" and it work. When I'm using this german characters it stop on line
HttpResponse response =httpClient.execute(httppost);
I don't know why and what I'm doing wrong.
Here is my application code:
public void getData(String data){
String topic = data; //Parameter for PHP
String result = "";
InputStream isr = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //PHP
nameValuePairs.add(new BasicNameValuePair("topic", topic)); //PHP
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.179.20:80/PHP/getData.php"); //PHP-Script on localhost
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //PHP
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Could not connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),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 {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
double Lat = json.getDouble("Latitude");
double Lng = json.getDouble("Longitude");
String Title = new String(json.getString("Ueberschrift").getBytes("ISO-8859-1"),"UTF-8");
String ShortText = new String(json.getString("Kurzbeschreibung").getBytes("ISO-8859-1"),"UTF-8");
String LongText = new String(json.getString("Inhalt").getBytes("ISO-8859-1"),"UTF-8");
String Thema = new String(json.getString("Thema").getBytes("ISO-8859-1"),"UTF-8");
String Datum = json.getString("Date");
String Url = new String(json.getString("Url").getBytes("ISO-8859-1"),"UTF-8");
s = s +
"Latitude: "+Lat+", "+"Longitude: "+Lng+"\n"+
"Thema: "+Thema+"\n"+
"Titel: "+Title+"\n"+
"Kurzbezeichnung: "+ShortText+"\n"+
"Inhalt: "+LongText+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
Here a part of my php:
mysql_select_db("database", $con);
mysql_query('SET CHARACTER SET utf8');
$thema = $_REQUEST['topic'];
$result = mysql_query("SELECT * FROM locations WHERE Thema='$thema'") or die('Errant query:');
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
//$output = serialize($output);
//$output = iconv('ISO-8859-1', 'UTF-8', $output);
if (function_exists('json_encode'))
{
echo json_encode($output);
echo "JSON Error: ".json_last_error();
}
else { echo "json_encode() is not supported"; }
mysql_close($con);
The json looks like this:
[{"id":"5","Longitude":"11.0730833333333","Latitude":"49.4530833333333","Height":"10","Ueberschrift":"Henkersteg","Kurzbeschreibung":"Der Henkersteg, auch","Inhalt":"Stadtbefestigung\u00a0| Marthakirch","Thema":"D\u00fcrer","Thema_id":"3","Datetime":"15\/02\/2015","Url":"http:\/\/de.wikipedia.org\/wiki\/Henkersteg"}]JSON Error: 0
Thanks in advance for any help.
I changed the line
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
to
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
I changed also the settings of my database. After changed them, I could display my string in the application, but unfortunately I get a "?" instead of a "ü".

Getting data from a server with BasicValuePairName?

I'm using a JSONParser class to create JSON to be sended to the server, but I need to use it for receive information now, but I don't know how to do it, I'm a noob, sorry. I create the json with the next part of code, and the following class.
// Building Parameters
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userid", thought.getUser()));
params.add(new BasicNameValuePair("timestamp", "" + thought.getTimestamp()));
params.add(new BasicNameValuePair("message", thought.getMessage()));
params.add(new BasicNameValuePair("address", thought.getAddress()));
params.add(new BasicNameValuePair("latitude", "" + thought.getLatitude()));
params.add(new BasicNameValuePair("longitude", "" + thought.getLongitude()));
// getting JSON Object
// Note that create product url accepts POST method
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(url_create_thought, "POST", params);
JSONParser.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.equalsIgnoreCase("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.equalsIgnoreCase("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.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
The part in the server I think that it's ok.
Server get values part
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT * FROM thoughts") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["thoughts"] = array();
echo '<center><div class="datagrid"><table>';
echo '<thead><tr><th>ID</th><th>USERID</th><th>TIMESTAMP</th><th>MESSAGE</th><th>ADDRESS</th><th>LATITUDE</th><th>LONGITUDE</th></tr></thead><tbody>';
while ($row = mysql_fetch_array($result)) {
// temp user array
$thought = array();
$thought["id"] = $row["id"];
$thought["userid"] = $row["userid"];
$thought["timestamp"] = $row["timestamp"];
$thought["message"] = $row["message"];
$thought["address"] = $row["address"];
$thought["latitude"] = $row['latitude'];
$thought["longitude"] = $row['longitude'];
echo '<tr><td>'.$row['id'].'</td><td>'.$row['userid'].'</td><td>'.$row['timestamp'].'</td><td>'.$row['message'].'</td><td>'.$row['address'].'</td><td>'.$row['latitude'].'</td><td>'.$row['longitude'].'</td></tr>';
// push single product into final response array
array_push($response["thoughts"], $thought);
}
// success
$response["success"] = 1;
// echoing JSON response
//echo json_encode($response);
echo '</table></center>';
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No events found";
// echo no users JSON
echo json_encode($response);
}
?>
What it's the correct way to get data in android?? What I need to put in params?
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(url_create_thought, **"GET"**, params);
Thanks for your help.
here is a simple way to get what u want from json-return url :
String sURL = "http://freegeoip.net/json/"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
zipcode=rootobj.get("zipcode").getAsString();//just grab the zipcode

Server cannot read json values from Android : Undifined IINdex and json null received at Server

I am going to implement the client-to-Server module which request is sent from Android devices to php . When it comes to the implementation , I have no clue why the server side cannot receive the json sent from Android device . As for the server, the database insert module is OK but cannot catch the json values . Would you please tell me what is wrong with the client side ?
The below is my code
Client side Android
public String postData(String argument , String url) {
String result="";
// Create a new HttpClient and Post Header
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000 * 20;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000 * 20;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpConnectionParams.setSocketBufferSize(httpParameters, 8*1024);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
//Log.d("url" , url);
HttpPost httppost = new HttpPost(url);
try {
System.out.println("Response:"+ "start execute");
JSONObject json = new JSONObject();
json.put("userid","loka");
json.put("password","yoor");
json.put("email","johnsmith#example.com");
//Log.d("test" , jsonString);
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
httppost.setHeader( "Content-Type", "application/json" );
//httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
//If php json response required
if(status==200){
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
System.out.println("result: "+ result);
}else{
System.out.println("2");
result = String.valueOf(status);
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return e.getMessage();
} catch (ConnectTimeoutException e){
e.printStackTrace();
return e.getMessage();
}catch (IOException e) {
e.printStackTrace();
return e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
Server side php
<?php
header('Content-type: application/json');
ini_set('display_errors','On');
require_once 'lib_mysql/insert.php';
$json = file_get_contents('php://input');
$result =insertUser($json);
if($result) {
echo "success";
}
else{
echo "fail";
}
?>
include_once("connection.php");
function insertUser($jsonString){
$usern = $jsonString->userid; //Undefined Variables
$pass = $jsonString->password; //Undefined Variables
$email = $jsonString->email; //Undefined Variables
$conn = getDBConn();
$data = false;
You need to use json_decode() function in php. header('Content-type: application/json'); would not help in this case
Try this way hope this helps you
Relpace
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
with
httppost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));

Problems with json.GetJSONArray("?") in Android

I am trying to get my code work. I want to make a mysql connection
and send the data with json to my android app.
I guess it almost works but my logcat gives me this warning almost at the end:
"error parsing data" value [{"staff_phone":"123","staff_name":"fabian" etc.
I guess i did something wrong in my sql script. This is the script:
mysql_connect($db_host,$db_user,$db_pwd);
mysql_select_db($database);
$result = mysql_query("SELECT * FROM contactlijst");
$array = array();
while ($row = mysql_fetch_assoc($result))
{
array_push($array, $row);
}
print json_encode($array);
mysql_close();
These are my java codes:
public static JSONObject getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader 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 parse the string to a JSON object
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
} }
AND this one:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Get the data (see above)
JSONObject json =
Database.getJSONfromURL("http://fabian.nostradamus.nu/Android/getcontactinfo.php");
try{
JSONArray contactinfo = json.getJSONArray("contactlijst");
//Loop the Array
for(int i=0;i < contactinfo.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = contactinfo.getJSONObject(i);
map.put("voornaam", e.getString("staff_name"));
map.put("achternaam", e.getString("staff_lastname"));
map.put("geboortedatum", e.getString("staff_dateofbirth"));
map.put("adres", e.getString("staff_address"));
map.put("postcode", e.getString("staff_address_postal"));
map.put("woonplaats", e.getString("staff_address_city"));
map.put("email", e.getString("staff_email"));
map.put("telefoon", e.getString("staff_phone"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
So what am I doing wrong?
Thanks alot!
getJSONArray() expects to be given a key whose value is an array. So it expects JSON that looks more like this:
{"contactlijst": [{"staff_phone":"123","staff_name":"fabian"...
If this doesn't work, try validating your JSON to ensure it is formatted correctly. I often use JSONLint for that purpose.

Android mysql php problem

I have an application which gets some data from a remote database.
I use PHP with the following code to connect to the data base.
mysql_connect($host,$username,$password) or die( "no connection");
#mysql_select_db($database) or die( "Unable to select database");
$query = $_REQUEST['query'];
$q=mysql_query($query);
while($e=mysql_fetch_assoc($q)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close();
I then connect via following java code
public void connect(ArrayList<NameValuePair> nameValuePairs) {
result = "";
InputStream is = null;
String url = "http://'ipadress'/PhpProject1/EmptyPHP.php";
//Get the content
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("Connect", "Error in http connection " + e.toString());
}
//Convert content toString
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
//result = replaceString(sb.toString());
} catch (Exception e) {
Log.e("Connect", "Error converting result " + e.toString());
}
}
When i have done that I make a query through
public void query(String query){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("query", query));
connect(nameValuePairs);
}
While this works great with the emulator there is a problem when using it on the phone.
Anyone has a clue why this is?
Thank you in advance
Make sure to connect your real device to the your private network to actually be able to access that server.
Easiest option would be a WiFi network in the same subnet as the server. Otherwise your phone won't be able to access the network as it is not public.

Categories