I connect a database on my server from the Android application and I want to use the info the server send back to me. Here is the response I get from the server :
[{"id":"1","userid":"1159448580","address":"Kishinev 3"}]
Here is my function that is realizing the connection to the server and trying to parse the response :
String checkForUserIdGetBookmarks (String returnString) {
InputStream is = null;
String result = "";
//the userId data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", userId));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PHP_URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch(Exce开发者_开发技巧ption e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", userid: "+json_data.getString("userid")+
", address: "+json_data.getInt("address")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
But when I try to show the already converted string it shows an empty string.
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String returnString = "";
checkForUserIdGetBookmarks(returnString);
Toast useridToast = Toast.makeText(getApplicationContext(), returnString, Toast.LENGTH_LONG);
useridToast.show();
Where would you suggest is my mistake and do you know other way of getting the response from the server into a string which I can use afterwards?
Use:
String returnString = checkForUserIdGetBookmarks(); // and declare returnString inside the method
Instead of:
String returnString = "";
checkForUserIdGetBookmarks(returnString);
精彩评论