Android Data Parsing with php - php

I am fetching data from a php server in its normal format..the columns are details and image..
I want the image in base64 format nd the details in utf8 format..all this data into one array that will be json encoded and will then be parsed at android side..How do i do this..so that i can Json parse in this manner..
String result= convertStreamToString(is);
JSONObject json=new JSONObject(result);
jArray=json.getJSONArray("details");
for(int i=0;i<jArray.length();i++)
{
JSONObject c=jArray.getJSONObject(i);
String detail=c.getString("details");
String image=c.getString("image");
Log.v("topics", topic);
is.close();
}
The php code:
while($out=mysql_fetch_assoc($result))
{
echo $out;
print_r(base64_encode($out[image]));
echo base64_encode($out['image']);
echo utf8_encode($out['details']);
$tempImage = base64_encode($out['image']);
echo $tempImage;
$tempDetails = utf8_encode($out['details']);
$post[] = array("image"=>$tempImage);
$post []= array("details"=>$tempDetails);
}
echo json_encode(array("login"=>$post));

i think that you can use this link to learn about this
Issues-parsing data to the php and jsons
or visit this : http://androidexample.com/JSON_Parsing_-_Android_Example/index.php?view=article_discription&aid=71&aaid=95

Related

PARSE JSON (Encode base 64) STRING in Android

**$sql = 'select * from dish_category';
$results =$conn->query($sql);
$spots = array(); //array to parse jason from
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
foreach($spots as $key=>$value){
$newArrData[$key] = $spots[$key];
$newArrData[$key]['Cat_Image'] = base64_encode($spots[$key]['Cat_Image']);
}
header('Content-type: application/json');
echo json_encode($newArrData);**
Above is the PHP code, it works perfectly fine and return JSON string, now i am confused how to parse image(decode base64) in android?
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
You should do it one by one:
Get the JSON response as string in android.
Parse the JSON and get the base64 string only.
Convert the base64 string to byte array by decoding it.
Create a new ByteArrayInputStream using the byte array.
Use the input stream to create a Bitmap: BitmapFactory.decodeStream(inputStream)

Value <br of type java.lang.String cannot be converted

Am retrieving data from MySQL table using Android HttpURLConnection
And am getting this error:
W/System.err: org.json.JSONException: Value br of type
java.lang.String cannot be converted to JSONObject
Error is at this line:
JSONObject jsonObj = new JSONObject(myJSON);
my code:
try {
JSONObject jsonObj = new JSONObject(myJSON);
Challenges = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < Challenges.length(); i++) {
JSONObject c = Challenges.getJSONObject(i);
String id = c.getString(TAG_ID);
String trackCoordinates = c.getString(TAG_COORDINATES);
HashMap<String, String> challengesFromDB = new HashMap<>();
challengesFromDB.put(TAG_ID, id);
challengesFromDB.put(TAG_COORDINATES, trackCoordinates);
ChallengesList.add(challengesFromDB);
}
.php file:
$sql = "select * FROM Challenges";
$res=mysqli_query($con, $sql);
$result=$array();
while($row = mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'userMail'=>$row[1],'trackCoordinates'=>$row[2]));
}
header('Content-Type: application/json');
print json_encode(array("result"=>$result));
mysqli_close($con);
Maybe error occuring because of my table field:trackCoordinates , am storing here googleMaps latitude, longtitude coordinates array, for example:
[lat/lng: (54.892597770959945,23.87877881526947), lat/lng: (54.89242519582151,23.876227363944054), lat/lng: (54.8917038430203,23.877791762351986)]
You aren't getting JSON, you're getting html. Either something on your server is outputting html, or you're hitting the wrong URL.

How to decode JavaScriptSerializer object in php

My goal is to send request from asp.net's page to php's page, and send email from php page.
my code on asp.net's page is
Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("to", "to#gmail.com");
keyValues.Add("from", "from#gmail.com");
keyValues.Add("message", "Conent of Email");
keyValues.Add("Subject", "Subject of Email");
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData.Add("a", json);
byte[] response = webClient.UploadValues("http://example.com/emailme.php", "POST", formData);
string responsebody = Encoding.UTF8.GetString(response);
the value which i'm passing after Serializing is
and the code written in my php page is
if (isset($_POST['a']))
{
echo "Value Exists";
echo "<br> Value before decoding is ".$_POST['a']."<br>";
$result=json_decode($_POST['a'],true);
echo "the value after decoding is ";
echo $result;
echo "<br> now for print_r <br>";
print_r($result);
} else
{echo "Value Does Not Exists";}
it was the code, now i'm attaching the image of result for my request.
As you can see the it shows the result before decoding for after decoding it shows nothing.
i will proceed for sending email after the result.
$result=json_decode(stripslashes($_POST['a']),true);
will do the trick ;)

How can I send an image from an sql database to an android client?

I'm trying to send an image from an sql database to an android client. I'm doing this by way of a php middleman. The code stops working due to a null returning of the method below.
My php code(works fine to encode image into base64(decoded the encoding and it worked)):
<?php
//get image
function ob_base64_encode($c) {
$a=base64_encode($c);
$arr = array('base64' => $a);
return json_encode($arr);
}
$image=resize(48,80,$image);
// And pass its name as a string
ob_start('ob_base64_encode');
imagepng($image);
ob_end_flush();
?>
My android code:
public static Bitmap getIm(String IP, int height, int width)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//Network queries and gets response(works)
String result = Network.getResponse(IP, nameValuePairs);
//manually decode string since for some reason JSON decode won't work(also works)
String r=result.split(":\"")[1];
r=r.split("\"")[0];
//decode string
byte[] decodedString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
//returns null
}

JSON exception in Android

I am trying to execute query on database in the localhost and send the JSON object to the client in android. I m not been able to know what is the problem in my code. So some one please help me on this regard.
My php code is the one where i m sending the JSON object.
php code
query executed successfully..
$row=mysql_fetch_array($result1);
$email=$row['EM'];
$pass=$row['PASS'];
$post=array("email"=>$email, "pass"=>$pass);
$posts[] = array("post"=>$post);
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode(array("posts"=>$posts));
And in android side i ve this code below;
HttpResponse response = doPost(url, kvPairs);
String responseBody=response.toString();
String temp = EntityUtils.toString(response.getEntity());
if (temp.compareTo("SUCCESS")==0)
{
Toast.makeText(this, "Working", Toast.LENGTH_LONG).show();
}
Above part executes ..
Below code throws a JSON exception
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
no_of_obj=jArray.length();
nemail=new String[no_of_obj];
npass=new String[no_of_obj];
for (int i = 0; i < jArray.length(); i++) {
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
Toast.makeText(context,jObject.getString("email")+":"+jObject.getString("pass") , duration).show();
nemail[i]=jObject.getString("email");
npass[i]=jObject.getString("pass");
}
In the log cat i can see : The json string must begin with "{"....
Probably you cannot do this
String s = e.getString("post");
because there is no "post" key in the array of Strings you have given,...
Try doing this,
String s = e.has("post")?e.getString("post"):null;
and then on next line keep a null check before Creating JSONObject..
Try this
$posts['data'] = $post;
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode($posts);

Categories