[Q] How to execute HTML get method in asynctask? - Java for Android App Development

0 down vote favorite
Im trying to pass this method for making a get request and passing the data as a String:
Code:
public String getdata(String url) throws ClientProtocolException,
IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
into an asynctask because i cant run it in the main thread, I tried to do this but "build" cannot be accessed:
Code:
public class getHTTPdata extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
try {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
} catch (IOException e) {
}
return build;
}
}
I'd like to access it as:
getHTTPdata task = new getHTTPdata();
task.execute("myurl");
Thank you.

Make sure you added all required permissions, making an HTTP request requires Internet permission.

Related

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;

What Do This Code Mean?

MainActivity.java
Code:
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
[B]new SigninActivity(this,status,role,1).execute(username,password);[/B]
}
}
Can someone explain to me what does this line do?
Code:
new SigninActivity(this,status,role,1).execute(username,password);
Here is the SigninActivity code.
SigninActivity.java
Code:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
@Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "";
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
@Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
* I intentionally remove all the link from the code because I can't post any outside link yet to this account
clonedaccnt said:
MainActivity.java
Code:
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
[B]new SigninActivity(this,status,role,1).execute(username,password);[/B]
}
}
Can someone explain to me what does this line do?
Code:
new SigninActivity(this,status,role,1).execute(username,password);
Here is the SigninActivity code.
SigninActivity.java
Code:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
@Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "";
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
@Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
* I intentionally remove all the link from the code because I can't post any outside link yet to this account
Click to expand...
Click to collapse
new SigninActivity(this,status,role,1).execute(username,password);
this start a new instance of the class SigninActivity passing:
this(context)
status(textview)
role(TextView )
1(integer)
that are requested in SigninActivity(Context context,TextView statusField,TextView roleField,int flag)
and execute tha asynctask passing the variables username and password for doInBackground method
sorry for my English
Nik
nikita1977 said:
new SigninActivity(this,status,role,1).execute(username,password);
this start a new instance of the class SigninActivity passing:
this(context)
status(textview)
role(TextView )
1(integer)
that are requested in SigninActivity(Context context,TextView statusField,TextView roleField,int flag)
and execute tha asynctask passing the variables username and password for doInBackground method
sorry for my English
Nik
Click to expand...
Click to collapse
Code:
new SigninActivity(this,status,role,1).execute(username,password);
Where in the code defines how many parameters this 2 functions accepts?
clonedaccnt said:
Code:
new SigninActivity(this,status,role,1).execute(username,password);
Where in the code defines how many parameters this 2 functions accepts?
Click to expand...
Click to collapse
This is called varargs. The ... In the doInBackground method say that you can receive any number of arguments of a type. In this case string. Inside the method they are used like arrays.
Gesendet von meinem SM-N9005 mit Tapatalk
Ohh I get it! Thanks.
GalaxyInABox said:
This is called varargs. The ... In the doInBackground method say that you can receive any number of arguments of a type. In this case string. Inside the method they are used like arrays.
Gesendet von meinem SM-N9005 mit Tapatalk
Click to expand...
Click to collapse
yes for doinbackground, while for SigninActivity the requested parameters are inside the bracket:
Code:
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag)

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

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?

( Volley > sending GET Request with parameters ) How to flatten Map<String,String> pa

( Volley > sending GET Request with parameters ) How to flatten Map<String,String> pa
I got this custom volley request class that extends Request with the request parameters in Map<String,String> format, my question is how to flatten Map<String,String> parameters correctly into a query string and receive it with PHP $_GET?
Code:
public class GsonGetRequest_Exp5<T> extends Request<T> {
private Response.Listener<T> listener;
private Map<String, String> params;
private Type type;
private Gson gson;
public GsonGetRequest_Exp5(String url, Map<String, String> params, Type type, Gson gson,
Response.Listener<T> reponseListener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.type = type;
this.gson = gson;
this.listener = reponseListener;
this.params = params;
}
public GsonGetRequest_Exp5(int method, String url, Map<String, String> params, Type type, Gson gson,
Response.Listener<T> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.type = type;
this.gson = gson;
this.listener = reponseListener;
this.params = params;
}
@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return (Response<T>) Response.success
(
gson.fromJson(jsonString, type),
HttpHeaderParser.parseCacheHeaders(response)
);
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException je) {
return Response.error(new ParseError(je));
}
}
}
Code:
public static GsonGetRequest_Exp5<ArrayList<FeedObject>> gsonGetRequest_exp6
(
Response.Listener<ArrayList<FeedObject>> listener,
Response.ErrorListener errorListener,
String str
)
{
//final String url = "example.com/php.php";
final Map<String, String> params = new HashMap<String, String>();
final Gson gson = new GsonBuilder()
.registerTypeAdapter(FeedObject.class, new FeedObjectDeserializer())
.create();
String test_url = "example.com/php.php";
params.put("SearchKey", str);
StringBuilder builder = new StringBuilder();
for (String key : params.keySet())
{
Object value = params.get(key);
if (value != null)
{
try
{
value = URLEncoder.encode(String.valueOf(value), HTTP.UTF_8);
if (builder.length() > 0)
builder.append("&");
builder.append(key).append("=").append(value);
}
catch (UnsupportedEncodingException e)
{
}
}
}
test_url += "?" + builder.toString();
return new GsonGetRequest_Exp5
(
test_url,
params,
new TypeToken<ArrayList<FeedObject>>() {}.getType(),
gson,
listener,
errorListener
);
}
problem with my code is, the "params" I keep getting "null", nothing is added to the end of my example.com url, can anyone point out what I did wrong?

Categories

Resources