i'm trying to fetch value of an array from mysql database in php and display those in android activity.
php code:
Here my array has two values, say $j[] has 1 and 2.
for($y=0;$y<2;$y++){
$val2 ="t".$y;
$set = mysql_query("SELECT col3 FROM table WHERE col2 ='size' AND col1 ='".$j[$val2]."'",$con); //col1 has two value hence given in for loop
$res= mysql_fetch_array($set); //it displays two size value for each col1
$a1[]="size".$y;
$r1[] = $res['col3'];
$set2 = mysql_query("SELECT col3 FROM table WHERE col2 ='price' AND col1 ='".$l[$val2]."'",$con); // same like above
$res2= mysql_fetch_array($set2);
$a2[]="price".$y;
$r2[] = $res2['meta_value'];
}
$h=array();
for($z=0;$z<$y;$z++){
$h[]=array($a1[$z] => $r1[$z], $a2[$z] => $r2[$z]); // storing values of size and price in associative array
$check='1';
}
$r=$h[];
if($check==NULL)
{
$r[$num_rows]="Record is not available";
print(json_encode($r));
}
else
{
$r[$num_rows]="success";
print(json_encode($r));
}
and the output while running this php page,
[[{"size0":"14","price0":"300"},{"size1":"18","price1":"350"}],"success"]
and my android activity is,
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
//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();
Log.e("log_tag", result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
try
{
JSONArray jArray = new JSONArray(result);
String re=jArray.getString(jArray.length()-1);
int flag=1;
for(int i=0;i<jArray.length()-1;i++)
{
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag2","title: "+jArray['price0']);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
But i'm getting error as Error parsing data org.json.JSONException: Value of type org.json.JSONArray cannot be converted to JSONObject
i dono how to get value?
for(int i=0;i<jArray.length();i++) {
JSONArray jArrayInner = jArray.optJSONArray(i);
if (jArrayInner != null) {
for(int j=0;j<jArrayInner.length();j++) {
JSONObject json_data = jArrayInner.getJSONObject(j);
Log.i("log_tag2","title: "+json_data.optString("price0"));
Log.i("log_tag2","title: "+json_data.optString("size0"));
}
}
}
}
to retrieve data from the inner json object, that you are correctly retriving from the array, you have to use the optString (opt*Type) method. Also you should have the same key for every inner object inside your array (price and size).
To get data from a JSON Array, for instance :
for(int index = 0; index < jArray.length(); index++)
{
String size0 = jArray.getJSONObject(index).getString("size0");
String price0 = jArray.getJSONObject(index).getString("price0");
}
Related
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
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();
}
I'm making an Android app and I'm trying to retrieve data from a remote database.
My question is how can I check if the query result contains data and is not empty?
I'm using JSON but I'm new to it. Here is my code:
public class MainActivity extends Activity {
private TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
txt.setText("Connexion...");
txt.setText(getServerData(strURL));
}
public static final String strURL = "http://.../marecherche/adresse.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("adresse","adr casa"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
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());
}
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{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","raison sociale: "+json_data.getString("raison_social")+
", Adresse: "+json_data.getString("adresse")
);
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
and the php file:
<?php
mysql_connect("localhost", "root", "passwd");
mysql_select_db("dbname");
$mots = explode(' ', $_REQUEST['adresse']);
$like = array();
foreach ($mots AS $mot) {
$like[] = ' "%' . mysql_real_escape_string($mot) . '%" ';
}
$condition = implode(' OR adresse LIKE ', $like);
$sql = mysql_query("SELECT * FROM entreprise WHERE adresse like " . $condition);
while ($row = mysql_fetch_assoc($sql))
$output[] = $row;
print(json_encode($output));
mysql_close();
?>
You could just create your own return to check for, something like:
PHP file:
if (is_array($output)) {
print(json_encode($output));
} else
echo "empty";
}
Java:
if (result.equals("empty")) {
return;
}
JSONArray jArray = new JSONArray(result);
// etc
My question is how can I check if the query result contains data and
is not empty?
=> Check result string is null or not before creating JSONArray.
I am echoing a json set of results back to android:
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
return json_encode($rows);
} else {
return false;
}
}
But when I try to convert the string to a JSONObject at the other end i get:
11-13 22:18:41.990: E/JSON(5330): "[{\"email\":\"fish\"}]"
11-13 22:18:41.990: E/JSON Parser(5330): Error parsing data org.json.JSONException: Value [{"email":"fish"}] of type java.lang.String cannot be converted to JSONObject
I have tried this with a larger result set and thought that it would be something to do with null values however trying it as above with just one value still returns an error.
Any help greatly appreciated
EDIT:
Android methods...
public JSONObject searchPeople(String tower) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", search_tag));
params.add(new BasicNameValuePair("tower", tower));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
return json;
}
JSON Parser class...
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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();
Log.e("JSON", 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;
}
As #MikeBrant mentioned above, you need to pass through JSONArray first.
Replace this:
//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());
}
With this:
// try parse the string to a JSON object
try {
JSONArray jArray = new JSONArray(json);
for(i=0; i < jArray.length(); i++) {
JSONObject jObj = jArray.getJSONObject(i);
Log.i("jObj", "" + jObj.toString());
// Parsing example
String email = jObj.getString("email");
Log.i("email", email);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
PHP w/ str_replace:
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$json_string = json_encode($rows);
$json_string = str_replace("\\", "", $json_string, $i);
return $json_string;
} else {
return false;
}
}
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
return json_encode($rows);
} else {
return false;
}
I think it's just your braces
What you are passing to JSONObject is in fact an array with a single object in it.
JSONObjectis expecting the syntax to be only representative of a single object containing key-value pairs (i.e. properties).
You need to not pass an array for this to work, or you need to use JSONArray to decode the JSON.
I had similar problem when I needed to pass json data from php to java app, this solved my problem:
$serialliazedParams = addslashes(json_encode($parameters));
You need to escape certain characters added by PHP, as well as substring your json string to cut out the additional characters at the front of the returned string.
One way to do it is like so:
ANDROID/JAVA code
JSONObject response = new JSONObject(responseString.substring(responseString.indexOf('{'),responseString.indexOf('}') +1).replace("\\",""));
You should do it a bit more neatly, but the point is that you have to ensure that the string you're passing in has no hidden characters, and to replace the first """ character with nothing as it can cause the exception.
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);