how i can retrieving result from mysql in array? - java

I want to get results from the database as an array. I have a table "commande" where I have stock. I want to get stock as an array. Something like this: array[0],array[],array[2]
This is the structure of my table commande (idfichecmd idproduit idclt qte datecmd)
This is my code:
String response = null;
String res = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("",));
try {
Log.i("","<<<<<<<<<<<<<<<<<<<<TRY");
response = CustomHttpClient.executeHttpPost("http://0.0.0.0/GetCmdDetails.php",nameValuePairs);
res=response.toString();
// res = res.trim();
//res= res.replaceAll("\\s+","");
//error.setText(res);
} catch (Exception e) {
Log.i("","<<<<<<<<<<<<<<<<<<<<Catch");
}
//parse json data
try{
JSONArray jArray = new JSONArray(res);
//-----------------------------------------
//nom= new String[jArray.length()];
//prenom= new String[jArray.length()];
//----------------------------------------
for (int i=0;i<jArray.length();i++) {
JSONObject json_data = jArray.getJSONObject(i)

First, test if your query is giving the correct result.
I use this solution for getting the jsonarray:
Use HttpClient to call the webservice.
private List<NameValuePair> parameters;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(//yoururl);
int statusCode = -1;
try {
httpPost.setEntity(new UrlEncodedFormEntity(this.parameters));
HttpResponse response = httpClient.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
//Get your inputstream here and convert it to json after
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));

Related

at response of type org.json.JSONObject cannot be converted to JSONArray

I am trying to upload a file using HttpPost and send it to php where I would get a response in JsonArray. However the problem I am having is to use the JsonArray or object to use in android app. The information from the array will then be put in to SQLite db with in the app. I am unable to extract the data from array and getting the following error
"at response of type org.json.JSONObject cannot be converted to
JSONArray" on JSONArray arr =object.getJSONArray("response");
I am not well verse with HttpPost and would appreciate any detail help I can get. I have tried few things from net but was not successful.
Array
(
[response] => Array
(
[Filepathserver] => webaddress
[email] => xyz#email.com
[syncstatus] => yes
)
)
java file
String url = "uploadphpfile.php";
File file = new File(filepath);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(mpEntity);
Log.d("enitity",mpEntity.toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
String result = EntityUtils.toString(r_entity);
JSONObject object = new JSONObject(result);
JSONArray arr =object.getJSONArray("response");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
Log.d("filepathserver",obj.get("Filepathserver").toString());
}
//Do something with response...
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
String responseString = EntityUtils.toString(r_entity);
} else {
String responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (Exception e) {
Log.e(DBHelperReports.class.getName(), e.getLocalizedMessage(),
e);
}
}
php file
$response = array();
$response["Filepathserver"] = $target_path;
$response["email"] = $target_path;
$response["syncstatus"] = 'yes';
echo json_encode(array("response"=>$response));
Logcat
Value
{"Filepathserver":"webaddress","email":"xyz#email.com","syncstatus":"yes"}
at response of type org.json.JSONObject cannot be converted to JSONArray
org.json.JSONException: Value
{"Filepathserver":"webaddress","email":"xyz#email.com","syncstatus":"yes"}
at response of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:100)
at org.json.JSONObject.getJSONArray(JSONObject.java:588)
at com.multiinspectionelite.DBHelperReports$1.run(DBHelperReports.java:383)
at java.lang.Thread.run(Thread.java:762)
your php file produced a json object, not a json array.
so, try JSONObject arr =object.getJSONObject("response");
By the way, your logcat had already reminded you to treat it as a JSONObject.

how to get a json array from php and use its value in android?

i am trying to get the data from database through a php file and then i want to use that data in android.i have tried a lot but it show me this error:type org.json.JSONObject cannot be converted to JSONArray.
followin is my php file and android code.also json array which was return is valid.
<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);
$pro_id=0;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
$res = mysqli_query($con,$sql) or die('i cant');
//$result = array();
$abc="";
while($row = mysqli_fetch_assoc($res)){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
}
$final = array("result"=>$abc);
//echo json_encode(array("result"=>$result));
echo json_encode($final);
mysqli_close($con);
?>
andoid code
public void searchProfession() {
//testin work
String[] stringArray = new String[5];
//
try {
HttpParams httpParams = new BasicHttpParams();
HttpParams p = new BasicHttpParams();
p.setParameter("profession", SearchProfession);
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://abh.netai.net/abhfiles/searchProfession.php";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//fffffffffffffffffffffffffff
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
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);
// 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");
}
result = sb.toString();
// return JSON String
if (inputStream != null) inputStream.close();
//ffffffffffffffffffffffffffff
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("result");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//testin work
String[] myarray;
//till here
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String jsonString = jArray.getString(i);
stringArray[i] = e.toString();
Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0], Toast.LENGTH_SHORT).show();
mylist.add(map);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
My Json : [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id‌​":"76","crtloc_lat":"34.769642","crtloc_lng":"72.361160"},{"user_id":"87","crtloc‌​_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.6971‌​17","crtloc_lng":"72.976631"}]
now i want to get the data in result array and show that data in android.for example i want to use all the(user_id) from that array
I think you got this error because jArray.getJSONObject(0); when i = 0 it's an array not an Object
your Json [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},...]
So jArray.getJSONObject(0); is [] not an object {"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"}
You can check out this post on how to execute GET/POST/MULTIPART POST requests in android and then use that post to see how to parse your JSON data into pojo(s).
Hope that helps.
The error:type org.json.JSONObject cannot be converted to JSONArray is thrown when you try to fetch a JSONObject in the place of an array. An exception will also be thrown if you try to fetch empty objects so please check your code for empties.
start by
$abc="";
while($row = mysqli_fetch_assoc($res)){
if(!empty($row['user_id'])&&!empty($row['crtloc_lat'])&&!empty($row['crtloc_lng'])){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
}
}
Then
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String jsonString = jArray.getString("crtloc_lat");//Use a key here
stringArray[i] = e.toString();
Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0],Toast.LENGTH_SHORT).show();
mylist.add(map);
}

Android: HttpPost not work

Hi guy's (sorry for my english error :P ) i have a problem, I'm trying to post a variable (id_art) to a php page, the problem is that I can't understand if the variable is not sent properly, or if I read it wrong php side.
JAVA CODE:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myurl);
StringBuilder builder = new StringBuilder();
String json, result = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("id_articolo", id_art);
//Convert JSONObject to JSON to String
json = jsonObject.toString();
//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
if (statusCode == 200){
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
System.out.println("DEBUG"+" "+result);
PHP CODE
<?php
include_once('configurazione.php');
header("Content-Type: application/json");
mysql_set_charset('utf8');
$value = json_decode(stripslashes($_POST),true);
var_dump($value);
?>
result is NULL... Why ????
Tnks 4 help
EDIT 1
I try to edit my php code replacing
this : json_decode(stripslashes($_POST),true);
with: $value = json_decode($_POST);
But the result is the same.. NULL
EDIT 2
I try to replace
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = json_decode(file_get_contents('php://input'));
echo $value ;
but result is NULL
in .JAVA
httpPost.setEntity(new StringEntity(yourJson.toString(),"UTF-8"));
in .PHP
$value = file_get_contents('php://input');
var_dump(json_decode($value , true));
try with this
in .JAVA
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", yourJson.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in .PHP
$value = $_POST['json'];
var_dump(json_decode($value , true));
I believe you cannot simply send StringEntity, because POST parameters are expected to be key=>value pairs. That means you need to give a name to your parameter, let's say json.
Then you can do this:
JSONObject jsonObject = new JSONObject();
// here you can set up the data
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", jsonObject.toString()));
// here you can add more POST data using nameValuePairs.add()
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
On the PHP side, you'll just do
$value = json_decode($_POST['json'], true);
var_dump($value);

Sending Byte Array as POST along with BasicNameValuePairs

I am trying to send data to a server as POST data. I have 3 fields, one is a String, another is a TIMEDATE and the last is a BLOB.
I have been trying the following code but it doesn't seem to work. I can't turn the byte array into a String and I am unsure how to append the byte array as a parameter.
If anybody has an idea I would appreciate to hear from you !
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://127.0.0.1/add_new_profile");
ProfileData profileData = getProfileData();
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name",profileData.getName()));
nameValuePairs.add(new BasicNameValuePair("created",profileData.getTimeCreated()));
nameValuePairs.add(new BasicNameValuePair("profile_data",new String(profileData.getDataAsByteArray())));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Server PHP script:
<?php
include('connect_db.php');
include('tools.php');
$name = $_POST['name'];
$created = $_POST['created'];
$profile_data = $_POST['profile_data'];
$query = "INSERT INTO fingerprint_profiles(name,created,fingerprint) VALUES ('".$name."','".$created"','".$fingerprint_data."')";
$result = mysql_query($query);
print_as_json($result);
?>

Error converting a HTTP POST response to JSON

When I try to convert an HTTP POST response to JSONArray I get the error:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
the error happens in the line: JSONArray jArray = new JSONArray(result);
the value of the string result is [{"return":"1"}] but it includes an extra blank character at the beginning that when removed, solves the problem. However, this character is not blank because a trim does not solve the problem. I believe there is some problem with the POST response, maybe badly constructed? (or maybe the POST request is wrong?) Any help is welcome.
A GET request works just fine, but I need to do a POST request.
This is the code:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
this is the code of the function HttpPost()
private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
}
this is the code of the function ConvertResponseToString()
private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-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());
}
return result;
}
this is the code of my php that replies to the POST
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
I'm using this and for me always works fine:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
The problem is solved.
PHP files were saved in UTF-8 WITH BOM, the solution was saving the files in UTF8 no BOM and the initial character in the POST response was removed.

Categories