Can not send string to php file using namevaluepair - php

I am trying to send a string to php script using namevaluepair. But i couldn't receive it on the other side. Here is my code.
protected String doInBackground(String... args) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Username",code ));
Log.v("username", code);
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.42.21:8080/sellapp/menuitem.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish {}
}
return result;
}
Here i want to pass the value in the string code to my php script. my php script is
$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id=$_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "
select
cust_code, segment_type, cust_name, cust_address, cust_payment_type, cust_credit_limit, cust_cr_balance
from customer where cust_code='".$cst_id."'
";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push(
$result,
[
'cust_id'=>$row[0],
'cust_seg'=>$row[1],
'cust_name'=>$row[2],
'cust_type'=>$row[3],
'cust_ad'=>$row[4],
'cust_cr'=>$row[5],
'cust_bl'=>$row[6]
]
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
When I am giving the value directly to the php it works. But through name/value pair it returns a null array as result.
Please help me to get an answer.I tried questions related to it. But didn't worked.

<?php
$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id = $_POST['Username']; // --------- not $_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "select cust_code,segment_type,cust_name,cust_address,cust_payment_type,cust_credit_limit,cust_cr_balance from customer where cust_code='".$cst_id."' ";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
['cust_id'=>$row[0],
'cust_seg'=>$row[1],
'cust_name'=>$row[2],
'cust_type'=>$row[3],
'cust_ad'=>$row[4],
'cust_cr'=>$row[5],
'cust_bl'=>$row[6]
]);
}
//echo json_encode(array("result"=>$result));
echo json_encode($result);
mysqli_close($con);
?>

Related

Value [string] <br> [string] <br> of type java.lang.String cannot be converted to JSONArray

I am making an app wherein I fetch user data from the corresponding sql table using php.
<?php
$email = $_POST["email"];
#mysql_connect("localhost","root","root") or die(#mysql_error());
#mysql_select_db("dtbse") or die(#mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(#mysql_error());
$result = array();
while ($y=mysql_fetch_array($x)) {
echo $y["uname"]."<br>";
echo $y["gender"]."<br>";
echo $y["pass"]."<br>";
echo $y["address"]."<br>";
echo $y["email"]."<br>";
}
?>
Any help will be greatly apprecitated. I know this question has been a lot of times but I dont think there is something replicating this issue. Thanks.
Here is the code snippet responsible for fetching and parsing.
final ArrayList arr = new ArrayList();
arr.add(new BasicNameValuePair("email", uname));
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://xxyoxx.esy.es/getDetails.php");
httppost.setEntity(new UrlEncodedFormEntity(arr));
HttpResponse hr = httpclient.execute(httppost);
HttpEntity ent = hr.getEntity();
is = ent.getContent();
Toast.makeText(getApplicationContext(),"1 wrk ",Toast.LENGTH_LONG).show();
} catch (Exception fl) {
Toast.makeText(getApplicationContext(),"First Try error "+fl,Toast.LENGTH_LONG).show();
}
/*// Depends on your web service
httppost.setHeader("Content-type", "application/json");*/
String result=null;
try {
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(),"2 str\n "+result,Toast.LENGTH_LONG).show();
} catch (Exception sl) {
sl.printStackTrace();
Toast.makeText(getApplicationContext(),"2 err\n "+sl,Toast.LENGTH_LONG).show();
}
try{
String aa = "", b = "", c = "";
JSONArray ar = new JSONArray(result);
for (int i = 0; i < ar.length(); i++) {
JSONObject jo = ar.getJSONObject(i);
aa = jo.getString("uname");
b = jo.getString("address");
c = jo.getString("email");
}
nm.setText(aa);
addr.setText(b);
mail.setText(c);
Toast.makeText(getApplicationContext(),"3 wrk"+result,Toast.LENGTH_LONG).show();
}
catch (Exception tl){
Toast.makeText(getApplicationContext(),"3 err "+tl,Toast.LENGTH_LONG).show();
}
Strings separated by <br> are not a valid JSON array. PHP can create JSON strings using json_encode
If you need to read a JSON array in Android you need to echo a JSON array from PHP:
<?php
$email = $_POST["email"];
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("dtbse") or die(mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error());
$result = array();
$res=[];
while ($y=mysql_fetch_array($x)) {
$res[] = [
$y["uname"],
$y["gender"],
$y["pass"],
$y["address"],
$y["email"]
];
}
echo json_encode($res); //Make PHP return a valid JSON response
Also, the error suppression operators may hide valuable debug infomation which may help you diagnose other problems.
If you instead prefer to pass the JSON object to Java then you can do the following (simpler) thing.
<?php
$email = $_POST["email"];
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("dtbse") or die(mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error());
$result = array();
$res=[];
while ($y=mysql_fetch_array($x)) {
$res[] = $y;
}
echo json_encode($res); //Make PHP return a valid JSON response

org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

{"college1":{"data":[{"id":"1","name":"nithin","location":"kannur s","time":"2016-06-20 12:06:30"},{"id":"2","name":"riy","location":"sdsdvxc","time":"2016-06-20 12:49:52"},{"id":"3","name":"royop","location":"kjpooj","time":"2016-06-20 06:15:36"},{"id":"4","name":"butr","location":"kjpooj","time":"2016-06-20 06:16:52"},17:17:03"}],"last_date":["2016-06-20 18:18:15"]}}
json data
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lasttime",lasttime));
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(ip);
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String result="";
if(is !=null)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
is.close();
i am trying to develop communication with android and wamp .when trying to send sqlite date to mysql database. it shows this error message. this is my web service.
$latest = '';
$datetime=mysql_query("SELECT MAX(time) AS latest from college1");
while ($row = mysql_fetch_assoc($datetime))
{
$latest = $row['latest'];
}
if(isset($_POST['lasttime']))
{
$dates=$_POST['lasttime'];
$datetime=mysql_query("SELECT * from college1 WHERE time > '{$dates}'");
while ($row = mysql_fetch_assoc($datetime))
{
//print_r($row);
//$array1[] = $row;
$retArr['college1']['data'][] = $row;
$retArr[$row['id']] = $row;
$retArr[$row['id']]['latest'] = $latest;
}
$retArr = json_encode($retArr);
echo $retArr;
//echo($retArr);
}
mysql_close($con);
?>
org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject.
this error shows when passing data to server and respose as null

Value [] of type org.json.JSONarray cannot be converted to JSONObject

I have an error as stated in the title when trying to read SQL and encode it back to android.
I have tried the following:
Verified the value of $androidIMEI by printing to log file, value is returned as expected.
Verified the output of $sql and the query is OK (including the $_POST['myIMEI_toString']) value from android.
Verified the value of $json array, 2 arrays are returned as the query returns 2 rows from SQL, OK.
Replacing
$androidIMEI = isset($_POST['myIMEI_toString']) ? $_POST['myIMEI_toString'] : '';
WITH
$androidIMEI = "000000000000000" //works fine but I want to get that programmatically.
Code:
Android (Send IMEI):
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
myIMEI = mngr.getDeviceId();
myIMEI_toString = myIMEI.toString();
...............
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myIMEI_toString",myIMEI_toString));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://path_on_server/file.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
System.out.println("Error catch");
}
return id;
}
Android (JSON):
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("myarray");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Request_Name");
number = jsonChildNode.getString("Request_Number");
username = jsonChildNode.getString("Request_Username");
status = jsonChildNode.getString("Status");
arrName.add(name);
arrNumber.add(number);
arrUsername.add(username);
arrStatus.add(status);
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
PHP:
<?php
include 'config.php';
//$androidIMEI = "000000000000000";
$androidIMEI = isset($_POST['myIMEI_toString']) ? $_POST['myIMEI_toString'] : '';
//$f = fopen("log.txt", "w");
//fwrite($f, print_r($androidIMEI, true));
//fclose($f);
$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$sql = "SELECT * from users WHERE Request='0' AND IMEI = '$androidIMEI' ";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['myarray'][]=$row;
}
}
else
{
//$error = "Error selecting record: " . $conn->error " ";
//$f = fopen("$error.txt", "w");
//fwrite($f, print_r($error, true));
//fclose($f);
}
$f = fopen("log.txt", "w");
fwrite($f, print_r($sql, true));
fclose($f);
mysql_close($con);
echo json_encode($json);
?>
Logcat Error:
org.json.JSONException: Value [] of type org.json.JSONarray cannot be converted to JSONObject
(i have asked this question before but will try again with more information)

Android, Connecting to MySQL using PHP: Null Pointer exception

Im a newbie to android, I am learning to connect to a server through android client using Php, MySql and JSON. For testing purpose im running on localhost.
So for here's what I've done.
Database demo.php
public class Database_demo extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
List<String> r = new ArrayList<String>();
try{
//http post
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PhpAndMySql/category.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//END Convert response to string
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("category"));
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
}
}
category.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY 'category'.'category' ASC");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
MySQL
CREATE TABLE `test`.`category` (
`category_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`category` VARCHAR( 255 ) NOT NULL
) ENGINE = MYISAM ;
I am getting a NullPointer Exception, when I execute in android.
Is the Php File correct?
Please I need your help with this!
Thanks
I'm thinking your php should be as follows (instead of quotes on the table.column use backticks).
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY `category` ASC");
$output = array();
while($row = mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

Adding information into the database

private void AddGroupTasks(){
title1 = tTitle.getText().toString();
detail1 = tDetail.getText().toString();
ArrayList<NameValuePair> b = new ArrayList<NameValuePair>();
Tasks = new ArrayList<String>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost ("http://203.209.111.88/AddGroupTasks.php");
httppost.setEntity(new UrlEncodedFormEntity(b));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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");
}
So, When I click add,the information is supposed to be added to database. However, it gives a null value. By the way, I'm writing a to-do list app.
$Title = $_REQUEST['tTitle'];
$Detail = $_REQUEST['tDetail'];
$Group = $_REQUEST['spin'];
$DueDate = $_REQUEST['tDueDate'];
$Title = "'".$Title."'";
$Detail = "'".$Detail."'";
$Group = "'".$Group."'";
$DueDate = "'".$DueDate."'";
print $Title;
$database = "CloudList";
mysql_connect("localhost","root","1234");
mysql_select_db($database) or die("Unable to select database");
$q = "INSERT INTO message(group_name,message_title,message_details,message_due) VALUES($Group,$Title,$Detail,$DueDate)";
$result = mysql_query($q);
print $q;
mysql_close();
Here, This is my PHP Script.
Try this code, replace with your code and let me know what happen,
private void AddGroupTasks(){
title1 = tTitle.getText().toString();
detail1 = tDetail.getText().toString();
ArrayList<NameValuePair> b = new ArrayList<NameValuePair>();
Tasks = new ArrayList<String>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost ("http://203.209.111.88/AddGroupTasks.php");
b.add(new BasicNameValuePair("tTitle",
"anyTitle"));
b.add(new BasicNameValuePair("tDetail",
"anyDetail"));
b.add(new BasicNameValuePair("spin",
"AnythingaboutSpin"));
b.add(new BasicNameValuePair("tDueDate",
"anytDueDate"));
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(b, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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");
}
Try to set quotes in your Values section. It should look like:
$q = "INSERT INTO message(group_name,message_title,message_details,message_due) VALUES('$Group','$Title','$Detail','$DueDate')";

Categories