Unable to upload picture when sending as Base64 String - Java for Android App Development

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;

Related

Send an image over HTTP in C#

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();
}

[Q] How to convert extended ASCII character to number in Android?

Hi!
Can you help me, please? I'm working on an Android app. I get some characters from a file on the Internet and put it to a TextView. These characters are ASCII characters. Then I read these characters one by one and convert it to numbers with the following code:
Code:
char my_char2;
char my_char3;
int myNum = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
myNum = my_char2 * 256 + my_char3;
}
}
Then I write it to an another TextView:
Code:
crlNumber.setText("" + myNum);
The problem is that this can only convert standard ASCII characters(from 0 to 127) except of the new line character(character number 10), carriage return character(character number 13) and the cancel character(character number 24).
But I need to convert also the extended ASCII characters(from 128 to 255) and the 3 characters mentioned above.
What should I do?
Thanks for helping.
Do these help?
http://stackoverflow.com/questions/13826781/java-extended-ascii-table-usage
http://stackoverflow.com/questions/5535988/string-to-binary-and-vice-versa-extended-ascii
nikwen said:
Do these help?
http://stackoverflow.com/questions/13826781/java-extended-ascii-table-usage
http://stackoverflow.com/questions/5535988/string-to-binary-and-vice-versa-extended-ascii
Click to expand...
Click to collapse
A little. I have tried the following code below. It didn't show me the number of the extended ascii characters. But I think I should somehow read the text not as a String, but as a byte, and then I think, it should work(maybe I am wrong). If it is right, please, can you tell me, how should I do it?
Code:
final String textSource = "path to my file";
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
String PT = textMsg.getText().toString();
CharSequence c = new String(PT);
String string0 = "";
String string1 = "";
char my_char2;
char my_char3;
String binary = "";
String binary2 = "";
int myNum2 = 0;
int decimalValue1 = 0;
int decimalValue2 = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
char[] buffer = string0.toCharArray();
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
binary = Integer,toBinaryString(b[i] & 0xFF);
decimalValue1 = Integer.parseInt(binary, 2);
}
char[] buffer2 = string1.toCharArray();
byte[] b2 = new byte[buffer2.length];
for (int i = 0; i < b2.length; i++) {
b2[i] = (byte) buffer2[i];
binary2 = Integer.toBinaryString(b2[i] & 0xFF);
decimalValue2 = Integer.parseInt(binary2, 2);
}
myNum2 = decimalValue1 * 256 + decimalValue2;
}
}
crlNumber.setText("" + binary2 + "," + decimalValue1 + "," + decimalValue2 + "," + myNum2);
}
adamhala007 said:
A little. I have tried the following code below. It didn't show me the number of the extended ascii characters. But I think I should somehow read the text not as a String, but as a byte, and then I think, it should work(maybe I am wrong). If it is right, please, can you tell me, how should I do it?
Code:
final String textSource = "path to my file";
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
String PT = textMsg.getText().toString();
CharSequence c = new String(PT);
String string0 = "";
String string1 = "";
char my_char2;
char my_char3;
String binary = "";
String binary2 = "";
int myNum2 = 0;
int decimalValue1 = 0;
int decimalValue2 = 0;
for (int k = 170; k < len; k++) {
if (c.charAt(k) == '0' && c.charAt(k+1) == '.') {
my_char2 = c.charAt(k+13);
my_char3 = c.charAt(k+14);
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
char[] buffer = string0.toCharArray();
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
binary = Integer,toBinaryString(b[i] & 0xFF);
decimalValue1 = Integer.parseInt(binary, 2);
}
char[] buffer2 = string1.toCharArray();
byte[] b2 = new byte[buffer2.length];
for (int i = 0; i < b2.length; i++) {
b2[i] = (byte) buffer2[i];
binary2 = Integer.toBinaryString(b2[i] & 0xFF);
decimalValue2 = Integer.parseInt(binary2, 2);
}
myNum2 = decimalValue1 * 256 + decimalValue2;
}
}
crlNumber.setText("" + binary2 + "," + decimalValue1 + "," + decimalValue2 + "," + myNum2);
}
Click to expand...
Click to collapse
Hm, I don't know. According to this answer, you can change the encoding on the desktop, otherwise you will just see question marks.
But according to the accepted answer here, this should be done automatically on a Linux system. And Android is Linux based. Did you try it on an Android device or just on your computer?
Bytes shouldn't work. In Java they are signed, so their range is -128 ... 127.
nikwen said:
Hm, I don't know. According to this answer, you can change the encoding on the desktop, otherwise you will just see question marks.
But according to the accepted answer here, this should be done automatically on a Linux system. And Android is Linux based. Did you try it on an Android device or just on your computer?
Bytes shouldn't work. In Java they are signed, so their range is -128 ... 127.
Click to expand...
Click to collapse
Yes, I tried it on my Android device. Maybe, the best choice would be then to use that certificate code which you suggested me in one of my previous threads, but the problem is, that I am beginner in Android developing and I read it and I didn't know how to use it in my code. So I thougt, if I got the 2 ASCII characters and converted it to decimal numbers, it would also work. And it also works until I have the standard ASCII characters. When there is an extended ASCII character, it shows me the number 65533.
adamhala007 said:
Yes, I tried it on my Android device. Maybe, the best choice would be then to use that certificate code which you suggested me in one of my previous threads, but the problem is, that I am beginner in Android developing and I read it and I didn't know how to use it in my code. So I thougt, if I got the 2 ASCII characters and converted it to decimal numbers, it would also work. And it also works until I have the standard ASCII characters. When there is an extended ASCII character, it shows me the number 65533.
Click to expand...
Click to collapse
But I think I have found out something.
Code:
string0 = Character.toString(my_char2);
string1 = Character.toString(my_char3);
int one = 0;
int two = 0;
String ascii1="\u001f";
String ascii2="\u0018";
String aa = "";
String bb = "";
if(string0.equals(ascii1)){
one = one + 31;
aa = aa + one;
}else{
one = 1;
}
if(string1.equals(ascii2)){
two = two + 24;
bb = bb + two;
}else{
two = 1;
}
textPrompt.setText("" + aa + bb);
But this needs a little correction, because this way it doesn't show me anything, but if I write
Code:
textPrompt.setText("" + aa);
inside my first if statement it shows me correctly 31. What can be the mistake I have made?
convert ASCII character
I'm a self android learner. I want to convert ascii code to character. Here is the code I used.
String s = "1000001";
int num = Integer.parseInt(s, 2);
TextView textView = new TextView(this);
textView.setText(String.valueOf(num));
setContentView(textView);
Here s is 1000001(65 in decimal) 65 is ascii value of 'A'. I want to get 'A' in my output screen.variable num has the value 65. please help me

[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