Send an image over HTTP in C# - Windows Mobile Development and Hacking General

Hey all
I have the following function to generate the http headers for a GET request on an image file:
Code:
byte [] headersAndImage()
{
StringBuilder s = new StringBuilder();
s.Append("HTTP/1.1 200 OK\r\n");
s.Append("Date: Tue, 17 Aug 2010 11:40:00 GMT\r\n");
s.Append("Vary: *\r\n");
s.Append("Server: Custommade\r\n");
s.Append("Content-Type: image/jpeg\r\n");
Bitmap b = new Bitmap("\\dog.jpg");
MemoryStream ms = new MemoryStream();
b.Save(ms, ImageFormat.Jpeg );
byte[] bitmapData = ms.ToArray();
ms.Close();
s.Append("Content-Length: " + bitmapData.Length + "\r\n\r\n");
byte[] headers = Encoding.ASCII.GetBytes(s.ToString());
return join(headers,bitmapData);
}
however when a browser receives this http packet the image is never displayed, usually just see the red X.
Any ideas why this won't work?

Here is the code that works for me:
Code:
public void TransmitFile(byte[] file, string fileName)
{
MemoryStream fileStream = new MemoryStream();
fileStream.Write(file, 0, file.Length);
fileStream.Position = 0;
var response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.ContentType = @"application/force-download\n";
response.AppendHeader(@"Content-Disposition",
String.Format(@"attachment;filename=""{0}""", fileName));
long bytesToGo;
int bytesRead;
Byte[] buffer = new byte[1048576]; //1 MB buffer, you may want to use whatever fits your environment
bytesToGo = fileStream.Length;
while (bytesToGo > 0)
{
if (response.IsClientConnected)
{
bytesRead = fileStream.Read(buffer, 0, 1048576);
response.OutputStream.Write(buffer, 0, bytesRead);
response.Flush();
bytesToGo -= bytesRead;
if (bytesRead == 0)
{
break; ;
}
}
else
{
bytesToGo = -1;
}
}
fileStream.Close();
response.Flush();
response.End();
}

Related

Bluetooth Programming...

This is for the C/C++ developers out here...
i need to connect a PocketPC to a PC via Bluetooth. Looking at various samples from the Windows Platform SDK and the Windows Mobile SDKs, i came up with the following server (PC) and client (PDA) codes:
Server Code (WinXP):
Code:
WSAData wsaData;
SOCKADDR_BTH sa;
int namelen;
SOCKET sock;
SOCKADDR_BTH sockaddr;
int size = sizeof(sockaddr);
if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR)
return false;
BluetoothHost_Socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (BluetoothHost_Socket == INVALID_SOCKET)
return false;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
sa.port = 0;
if (bind(BluetoothHost_Socket, (SOCKADDR *) &sa, sizeof(sa)))
{
closesocket(BluetoothHost_Socket);
return false;
namelen = sizeof(sa);
if (getsockname(BluetoothHost_Socket, (SOCKADDR *)&sa, &namelen))
{
closesocket (BluetoothHost_Socket);
return false;
}
BluetoothHost_ClientListCount = 0;
if (listen(BluetoothHost_Socket, 5))
return false;
sock = accept(BluetoothHost_Socket, (SOCKADDR *) &sockaddr, &size);
}
Client Code (WinCE):
Code:
WSAQUERYSET querySet;
HANDLE hLookup;
char buffer[1000];
DWORD bufferlength;
WSAQUERYSET *results;
SOCKADDR_BTH *btaddr;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR)
return false;
memset(&querySet, 0, sizeof(querySet));
querySet.dwSize = sizeof(querySet);
querySet.dwNameSpace = NS_BTH;
BluetoothQuery_DeviceCount = 0;
if (WSALookupServiceBegin(&querySet, LUP_CONTAINERS, &hLookup) == SOCKET_ERROR)
return false;
while (BluetoothQuery_DeviceCount < BLUETOOTHQUERY_MAXDEVICES && !BluetoothQuery_Cancel)
{
bufferlength = sizeof(buffer);
memset(buffer, 0, sizeof(buffer));
results = (WSAQUERYSET *) &buffer;
if (WSALookupServiceNext(hLookup, LUP_RETURN_NAME|LUP_RETURN_ADDR, &bufferlength, results) == SOCKET_ERROR)
{
int result = WSAGetLastError();
break;
}
btaddr = (SOCKADDR_BTH*)results->lpcsaBuffer->RemoteAddr.lpSockaddr;
BluetoothQuery_DeviceAddrList[BluetoothQuery_DeviceCount]=btaddr->btAddr;
if (results->lpszServiceInstanceName != NULL)
wcscpy((TCHAR *)BluetoothQuery_DeviceNameList[BluetoothQuery_DeviceCount],results->lpszServiceInstanceName);
else
wcscpy((TCHAR *)BluetoothQuery_DeviceNameList[BluetoothQuery_DeviceCount],L"<unnamed>");
BluetoothQuery_DeviceCount++;
}
WSALookupServiceEnd(hLookup);
BluetoothClient_Socket = socket (AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM);
if (BluetoothClient_Socket == INVALID_SOCKET)
return false;
SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BT;
sa.btAddr = *btaddr;
for (i = 0; i < 30; i++)
{
sa.port = i; //channel & 0xff;
if (connect(BluetoothClient_Socket, (SOCKADDR *) &sa, sizeof(sa)) == 0)
break;
}
if (i >= 30)
{
closesocket(BluetoothClient_Socket);
return false;
}
All calls seems to work out. Sockets are created, all return values look ok. Yet, the client does not connect to the server, so the server never goes beyong that accept() call.
Any comments would be greatly appreciated!
thanks,
Daniel

Unable to upload picture when sending as Base64 String

I am trying to send an image to our asp.net webservice from android.Here is my sample code :
// Getting image from Gallery
Code:
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
/* BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;*/
thumbnail = (BitmapFactory.decodeFile(picturePath));
img_photo.setImageBitmap(thumbnail);
// converting imag into base64 string
Code:
img_photo.buildDrawingCache();
Bitmap bm = img_photo.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap
byte[] photo = baos.toByteArray();
System.out.println("this is byte array" + bytearray);
String temp_base =Base64.encodeToString(photo,Base64.NO_WRAP);
// calling webservice
Code:
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("CarID", SellCarDetailView.sellcardetails_carid);
request.addProperty("pic",temp_base);
System.out.println("this is piccontent" +temp_base);
try {
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
soapEnvelope.encodingStyle = SoapEnvelope.ENC;
// new MarshalBase64().register(soapEnvelope);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(request);
HttpTransportSE aht = new HttpTransportSE(URL);
//AndroidHttpTransport aht = new AndroidHttpTransport(URL);
aht.call(SOAP_ACTION, soapEnvelope);
// SoapObject response = (SoapObject)envelope.getResponse();
SoapPrimitive response = (SoapPrimitive) soapEnvelope.getResponse();
String temp3 = response.toString();
Log.v("TAG", temp3);
} catch (Exception e) {
e.printStackTrace();
}
How ever i am getting "invalid parameter" at web service end.
// Asp.net code
Code:
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Xml)]
[WebMethod(EnableSession = true)]
public string UploadPictureByCarIDFromAndroid(string CarID, string make, string model, string year, string UserID, string pic, string AuthenticationID, string CustomerID, string SessionID)
{
string bStatus = "Failed";
MobileBL objMobile = new MobileBL();
UsedCarsInfo objCarPicInfo = new UsedCarsInfo();
try
{
try
{
if (AuthenticationID == ConfigurationManager.AppSettings["AppleID"].ToString())
{
objCarPicInfo.Carid = Convert.ToInt32(CarID);
byte[] picContent = Convert.FromBase64String(pic);
// byte[] picContent = Base64.decode(pic);
MemoryStream ms = new MemoryStream(picContent, 0,picContent.Length); // getting "invalid length"
ms.Write(picContent, 0, picContent.Length);
Bitmap oBitmap1 = new Bitmap(ms);// getting "invalid length" error here
// System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
}
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
return bStatus;
}
I am getting "invalid length" error when sending the image.Any help is highly appreciated.
i think a better approach is with stream rather file path
for example you can try
Get image from gallery
Code:
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
//your options
Bitmap img_photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, options);
convert to base64
Code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
img_photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String temp_base =Base64.encodeToString(byteArray,Base64.DEFAULT);
i cant see anything wrong in the web services call but shouldn't you send all the parameters the function needs?
also, try to change this
Code:
// SoapObject response = (SoapObject)envelope.getResponse();
SoapPrimitive response = (SoapPrimitive) soapEnvelope.getResponse();
String temp3 = response.toString();
to this
Code:
SoapObject response = (SoapObject)envelope.getResponse();
String temp3 = response.getProperty(0).toString();
warlock9_0 said:
i think a better approach is with stream rather file path
for example you can try
Get image from gallery
Code:
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
//your options
Bitmap img_photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, options);
convert to base64
Code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
img_photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String temp_base =Base64.encodeToString(byteArray,Base64.DEFAULT);
i cant see anything wrong in the web services call but shouldn't you send all the parameters the function needs?
also, try to change this
Code:
// SoapObject response = (SoapObject)envelope.getResponse();
SoapPrimitive response = (SoapPrimitive) soapEnvelope.getResponse();
String temp3 = response.toString();
to this
Code:
SoapObject response = (SoapObject)envelope.getResponse();
String temp3 = response.getProperty(0).toString();
Click to expand...
Click to collapse
Thanks for giving reply, i tried your code but getting the same problem.
sending to web service is ok?
trying this in the web service end?
Code:
Bitmap bmpReturn = null;
byte[] byteBuffer = Convert.FromBase64String(base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
memoryStream.Close();
memoryStream = null;
byteBuffer = null;

[Q] Populate database in android 4.4 using phonegap?

I can't populate database in android 4.4 using phonegap when I run my app the first time, but if I close the app and open it again this task works fine.
I have a 0000000000000001.db in assets and I want put this in Android 4.4 memory.
How can I deal with such Issue?
I'm using this code to populate the database in Android 4.4 memory
Code:
public void copyDatabase(){
// DB_NAME2 = "Databases.db";
//ASSETS = "0000000000000001.db";
//DB_PATH2 = "/data/data/com.example.testapp/app_webview/databases/";
//DB_PATH3 = "/data/data/com.example.testapp/app_webview/databases/file__0/";
//DB_NAME3 = "1";
String path = DB_PATH2 + DB_NAME2;
String path2 = DB_PATH3 + DB_NAME3;
File checkDatabase = new File(DB_PATH2);
File checkDatabase2 = new File(DB_PATH3);
if (!checkDatabase.exists())
{
checkDatabase.mkdir();
}
if (!checkDatabase2.exists())
{
checkDatabase2.mkdir();
}
try{
InputStream is = context.getAssets().open(DB_NAME2);
OutputStream os = new FileOutputStream(path);
InputStream is2 = context.getAssets().open(ASSETS);
OutputStream os2 = new FileOutputStream(path2);
byte[] buffer = new byte[10240];
int line;
while ((line = is.read(buffer))>0)
{
os.write(buffer, 0, line);
}
os.flush();
os.close();
is.close();
buffer = new byte[10240];
line = 0;
while ((line = is2.read(buffer))>0)
{
os2.write(buffer, 0, line);
}
os2.flush();
os2.close();
is2.close();
}catch(IOException e){
System.out.println("Problem "+e);
}
}

My JSONArray keeps appending the last object on loop

Here is my code:
Code:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jObject = new JSONObject(jsonObj.toString().trim());
Iterator<?> keys = jObject.keys();
JSONArray temp_json_arr = null;
JSONObject temp_json_obj = null;
String temp_string = "";
int index_count = 0;
LinearLayout ll = (LinearLayout)findViewById(R.id.test_layout);
//temp_json_obj = jsonObj.getJSONObject("identification");
//Log.d("TEST: ", "ARRAY LENGTH> "+temp_json_arr.length());
while( keys.hasNext() ){
String key = (String)keys.next();
Log.d("TEST: ", "KEYS> " + key);
// Getting JSON Array node
temp_json_arr = jsonObj.getJSONArray(key);
// looping through All Questions
for (int i = 0; i < temp_json_arr.length(); i++) {
JSONObject q = temp_json_arr.getJSONObject(i);
if( key.equals("identification") ) {
tv[tv_ctr] = new TextView(getApplicationContext());
tv[tv_ctr] = (TextView)findViewById(id);
id++;
et[identification_question] = new EditText(getApplicationContext());
et[identification_question] = (EditText)findViewById(id);
id++;
//json manipulation
try {
jsonOb.put("question-id", tv[tv_ctr].getText().toString());
jsonOb.put("answer", et[identification_question].getText().toString());
} catch(Exception e) {
}
Log.d("TEST: ", "jsonOb> " + jsonOb.toString());
//answer += et[identification_question].getText().toString() + "-" + tv[tv_ctr].getText().toString() + "/";
tv_ctr++;
identification_question++;
jsonArr.put(test,jsonOb);
test++;
Log.d("TEST: ", "jsonArr> " + jsonArr.toString());
}
Everytime I use .put of the JSONArray, it appends the last object on all indexes for example:
I have 3 input namely answer 1 , answer 2 and answer 3
The expected json data will be this:
Code:
[{"answer":"answer1","question-id":"question1"},{"answer":"answer2","question-id":"question2"},{"answer":"answer3","question-id":"question3"}]
But this is the current output:
Code:
[{"answer":"answer3","question-id":"question3"},{"answer":"answer3","question-id":"question3"},{"answer":"answer3","question-id":"question3"}]
As you can see the last index get appended multiple times.
Nevermind I've already solved my own problem.

How can I loop through my JSON object?

I am new to Java and I am getting kind of stuck by trying to loop through my JSON. I am retrieving a JSON object where I want to loop through.
My JSON looks as follow:
Code:
{"message":{"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","success":1,"created_at":null,"updated_at":null}]}}
I tried a loop like this:
Code:
for(int i = 0; i<json.names().length(); i++){
try {
Log.v("TEST", "key = " + json.names().getString(i) + " value = " + json.get(json.names().getString(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
But this will only target "message" which includes the whole JSON "string". I want to loop through each message and retrieving the value of uid 1, uid 2 etc. How can I achieve this?
Thanks in advance.
Here is how I'm doing it:
Code:
private static final String AllNewsItemsURL = "some_url_here.php";
private static final String TAG_SUCCESS = "success";
private static final String NEWS = "news";
private static final String TITLE = "title";
private static final String STORY = "story";
private final JSONParser jParser = new JSONParser();
private JSONArray newsItems = null;
..... / code snipped / ....
try {
JSONObject json = jParser.makeHttpRequest(AllNewsItemsURL, params);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
newsItems = json.getJSONArray(NEWS);
for (int i = 0; i < newsItems.length(); i++) {
JSONObject obj = newsItems.getJSONObject(i);
Integer id = i + 1;
String title = obj.getString(TITLE);
String story = obj.getString(STORY);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
Thanks for your reply. I tried it but getting this exception:
Code:
org.json.JSONException: Value {"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3","success":1,"created_at":null,"updated_at":null}]} at messages of type org.json.JSONObject cannot be converted to JSONArray
CodeMonkeyy said:
Thanks for your reply. I tried it but getting this exception:
Code:
org.json.JSONException: Value {"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3","success":1,"created_at":null,"updated_at":null}]} at messages of type org.json.JSONObject cannot be converted to JSONArray
Click to expand...
Click to collapse
You might want to try the matching JSONParser I have for it, sorry forgot to include it:
https://github.com/JonnyXDA/WGSB/bl...om/jonny/wgsb/material/parser/JSONParser.java
Also noting that your entire JSON Array is called "message" but you also have a parameter called "message" - maybe rename the Array to "messages"?
As for the code you should have something like:
Code:
private static final String AllNewsItemsURL = "some_url_here.php";
private static final String TAG_SUCCESS = "success";
private static final String MESSAGES = "messages";
private static final String TITLE = "title";
private static final String MESSAGE = "message";
private final JSONParser jParser = new JSONParser();
private JSONArray messageItems = null;
..... / code snipped / ....
try {
JSONObject json = jParser.makeHttpRequest(AllNewsItemsURL, params);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
My code looks like the this:
Code:
//Message task
MessageTask task = new MessageTask(DashboardActivity.class);
task.execute();
try {
json = task.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
I am using Async Task to retrieve my JSON.
And my JSON parser looks like this:
Code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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;
}
}
But it doesn't get through the if statement, because it can't find the value success. ( org.json.JSONException: No value for success ). Don't really know what I am doing wrong here. Is it because I am using AsyncTask and retrieving my JSON the wrong way?
I also renamed my Array to "messages", stupid mistake thanks!
CodeMonkeyy said:
But it doesn't get through the if statement, because it can't find the value success. ( org.json.JSONException: No value for success ). Don't really know what I am doing wrong here. Is it because I am using AsyncTask and retrieving my JSON the wrong way?
I also renamed my Array to "messages", stupid mistake thanks!
Click to expand...
Click to collapse
We're getting closer! With regards to using AsyncTask - thats fine and the recommended way to do service side sync/download operations (doesn't block the UI thread) so no need to change that.
I just took a look at my reference JSON and I have the success tag outside of an item eg:
Code:
{"topical":[{"tid":"5","title":"Exam countdown... just 12 weeks left!","story":"some_story_text_here","staff":"0","red":"0","show":"1"}],[COLOR="red"]"success":1[/COLOR]}
Whereas your success tag is put in each item:
Code:
{"message":{"2":[{"uid":"2","title":"","message":"Test1","[COLOR="red"]success":1,[/COLOR]"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !",[COLOR="red"]"success":1[/COLOR],"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","[COLOR="Red"]success":1[/COLOR],"created_at":null,"updated_at":null}]}}
I'm guessing that your php line for:
PHP:
$response["success"] = 1;
is inside of the while loop:
PHP:
while ($row = mysql_fetch_array($result)) {
Taking it out of the while loop should fix that
That makes sense, because I am trying to get a success code for my whole JSON response. I changed my PHP code to:
Code:
while($row = mysqli_fetch_array( $messages )) {
// create rowArr
$rowArr = array(
'uid' => $row['id'],
'title' => $row['title'],
'message' => $row["message"],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
);
// store rowArr in $return_arr
$return_arr[$row['id']][] = $rowArr;
}
$return_arr['success'] = 1;
// Json encode
echo json_encode(array("messages" => $return_arr));
}
Retrieving the following JSON:
Code:
{"messages":{"2":[{"uid":"2","title":"","message":"Test1","created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !","created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","created_at":null,"updated_at":null}],"success":1}}
But I am still getting the following exception:
Code:
org.json.JSONException: No value for success
The success tag is still being encoded as part of an inner array, not the first array - try this:
PHP:
if (mysql_num_rows($messages) > 0) {
$response["messages"] = array();
while ($row = mysql_fetch_array($messages)) {
$messagesArray= array(
'uid' => $row['id'],
'title' => $row['title'],
'message' => $row['message'],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
);
array_push($response["messages"], $messagesArray);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No messages found";
echo json_encode($response);
}
And it's finally working!
Getting the following JSON result:
Code:
{"tag":"message","success":1,"error":0,"messages":[{"uid":"2","title":"","message":"Test1","created_at":null,"updated_at":null},{"uid":"3","title":"","message":"Test2!","created_at":null,"updated_at":null},{"uid":"4","title":"Bla","message":"Test3!","created_at":null,"updated_at":null}]}
And I can successfully loop through my JSON with the following code:
Code:
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
Log.e("TITLE :", title);
Log.e("MESSAGE :", message);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
Thank you very much! So the problem was that I placed the "success" tag outside my Array?

Categories

Resources