I am new in android.I need to take values from web service.Here i used json parsing.The out put Json format is { "flag": 0 }. Here i need to take the value of flag and using that value i want to start another method. How do i take the value of flag. please help me. I used in this way.
public String objectvalue(String result){
try {
JSONObject obj=new JSONObject(result);
String flag=obj.getString("flag");
mString=flag;
System.out.println(mString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mString;
}
But i didnot get the value of flag.Here argument result is output from the server.ie,result={ "flag": 0 }
First of all, where is the declaration of mString variable? I assume it is declared as instance variable in your java class having this method, if not please check.
You have a well formed JSON in the form of
{ "flag": 0 }
so converting it to a JSONObject should work perfectly.
For extracting value of flag key
There is key named flag in this JSONObject which has an Integer value and you are trying to extract it using getString() method.
You should be using either of the following methods calls
optInt(String key)
Get an optional int value associated with a key, or zero if there is no such key or if th value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.
int flag = optInt("flag");
OR
optInt(String key, int defaultValue)
Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.
int flag = optInt("flag", 0);
Your code with changes
public int objectValue(String result){
int flag = 0;
try {
JSONObject obj=new JSONObject(result);
flag = obj.optInt("flag");
} catch (JSONException e) {
e.printStackTrace();
}
return flag;
}
Edit: Answer to question in comment.
public String objectValue(String result){
int flag = 0;
try {
JSONObject obj=new JSONObject(result);
flag = obj.optInt("flag");
} catch (JSONException e) {
e.printStackTrace();
}
return String.valueOf(flag);
}
Hope this helps.
You may try using AsyncTask for your concern. It's best and preffered way to fetch JSON data
Define AsyncTask like this ..
new BussinessOwnerHttpAsyncTask().execute();
and your AsyncTask class ..
class BussinessOwnerHttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// Progress dialog code goes over here ..
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Maintaining Shared preferences class for further...
HttpClient httpclient = new DefaultHttpClient();
String myUrl = Your_url_goes_over_here;
String encodedURL = "";
try {
encodedURL = URLEncoder.encode(myUrl, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URL url = new URL(encodedURL);
Log.d("asca", ""+url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("url", city_name + "~" + country_name);
Log.d("location", request_url+encodedURL);
HttpGet httpget = new HttpGet(request_url+encodedURL);
try {
httpresponse = httpclient.execute(httpget);
System.out.println("httpresponse" + httpresponse);
Log.i("response", "Response" + httpresponse);
InputStream is = httpresponse.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String recievingDataFromServer = null;
while ((recievingDataFromServer = br.readLine()) != null) {
Log.i("CHECK WHILE", "CHECK WHILE");
sb.append(recievingDataFromServer);
}
myJsonString = sb.toString();
Log.d("manish", myJsonString);
serverSearchData = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
if (myJsonString.length() > 0) {
try {
myJsonObject = new JSONObject(myJsonString);
String your_flag = myJsonObject.getString("flag");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Now you are good to go with your queries..
{ // JSONObject
"flag": 0
}
Use
JSONObject obj=new JSONObject(result);
int flag=obj.getInt("flag");
http://developer.android.com/reference/org/json/JSONObject.html
public int getInt (String name)
Added in API level 1
Returns the value mapped by name if it exists and is an int or can be coerced to an int.
Throws
JSONException if the mapping doesn't exist or cannot be coerced to an int.
If this does not work you need to post more info.
the "flag" values format at interger, not string, this is simple code to do that :
int flagValues = jsonObject.getInt("flag");
Log.w("values ",String.valuesOf(flagValues));
Related
I`m trying to get a String from URL and create an objects by Gson. I am getting to string from this url: http://gotachles.co.il/data.php and then I have to convert it to html before sending it to Gson. The problem is that my string is probably too long (1.5 million letters) and the app freeze when calling fromHTML. (tried and it works fine with smaller strings).
TachlesStringGetter:
class TachlesStringGetter extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String myJSONString = null;
try {
myJSONString = new Scanner(new URL(
"http://gotachles.co.il/data.php").openStream(), "UTF-8")
.useDelimiter("\\A").next();
Log.i("TACHLESSTRINGGETTER", "got sucessfuly");
Log.i("TACHLESSTRINGGETTER", "" + myJSONString.length());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("TACHLESSTRINGGETTER", "RETURN");
return myJSONString;
}
}
The HTML asynctask:
public class FromHTML extends AsyncTask<String, String, String> {
private Spanned spanned;
private String result;
#Override
protected String doInBackground(String... html) {
Log.i("FROMHTML", "STARTING");
spanned = Html.fromHtml(html[0]);
result = spanned.toString();
Log.i("FROMHTML", "Returning");
return result;
}
}
Calling it like that:
public void Jsonnn() {
// sending to anynctask
try {
myJSONString2 = new TachlesStringGetter().execute(myJSONString2)
.get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
// // from html
if (myJSONString2 != null) {
Log.i("WEBVIEWCLASS", "DOING HTML STUFF");
try {
afterHTML = new FromHTML().execute(myJSONString2).get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
Log.i("FINALLY", "STARTING SEOND FINALLY");
try {
Gson gson = new Gson();
JsonObj obj = gson.fromJson(afterHTML, JsonObj.class);
Toast.makeText(getApplicationContext(), obj + "", 2000)
.show();
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "oops jsno!",
1000).show();
}
}
}// first finnaly
}// second finnaly
}
Sorry for the shitty code :D
StringBuilder consume less memory than using String addition (str = str1 + str2). An example use of a StringBuilder:
StringBuilder builder = new StringBuilder();
builder.append("This is my string");
To get your long string from your builder (when you are trying to convert it to Gson object) you can simply call builder.toString();
So you should edit your Asynctask class "TachlesStringGetter" which should use a StringBuilder, you should also change other aspects of your code whenever you use something to append to String. The + operator uses public String concat(String str) internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent. Hope this helps!
I am looking to pull data from my websites JSON url and display only one object in the textview. I was able to parse the entire JSON array, but not the specific object.
Here's the JSON on the site:
{"id":3,"day":" an A","created_at":"2013-11-06T12:30:59.023Z","updated_at":"2013-11-06T12:30:59.023Z"}
As you can see, it's pretty simple, but basically all I want to pull is the
"day":" an A"
and display it in my textview as "an A". Until now, I've only been able to pull the entire array.
A reference to this or any solution would be greatly appreciated!
Thanks in advance!
MainActivity Class:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parseDay);
TextView textView1 = null;
try {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
JSONObject json=new JSONObject("day");
try {
String day =json.getString("day");
textView1.setText(day);
} catch (JSONException e) {
e.printStackTrace();
}
}
//catch (JSONException e) {
// e.printStackTrace();
//}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and My GetMethod:
public class GetMethod {
public String getInternetData() throws Exception {
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.xelatechnologies.com/hfdays/show.json");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}
finally {
if (in !=null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
I'm extremely new to JSON parsing so I'm sure it is not right at all. But it's worth a try!
The JSON you posted is a JSONObject. In java you can put that object into an JSONObject like this (You can use any serialize/deserializer you would like, many exist, for this example try org.json):
String json = "{\"id\":3,\"day\":\" an A\",\"created_at\":\"2013-11-06T12:30:59.023Z\",\"updated_at\":\"2013-11-06T12:30:59.023Z\"}";
JSONObject jsonObject = new JSONObject(json);
Now you have created a json object. Next you want to set the text on the text view. The key to get your value in this case is "day". So now all you have to do is use the provided getString(String value) method on the json object.
final String DAY = "day";
String dayValue= "";
try {
value = jsonObject.getString(DAY);
} catch (JSONException e) {
e.printStackTrace();
}
TextView textView = findViewById(R.id.text_view);
textView.setText(dayValue);
{"id":3,"day":" an A","created_at":"2013-11-06T12:30:59.023Z","updated_at":"2013-11-06T12:30:59.023Z"}
As its starts from '{' so it is an Object not Array
JSONObject json=new JSONObject("YOUR_JSON_STRING");
try {
String days=json.getString("day");
textview.setText(days);
} catch (JSONException e) {
e.printStackTrace();
}
Edited:
TextView textView1;
String response;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parseDay);
textView1 = (TextView)findViewById(R.id.your_textview_id);//First Initialise TextView
GetMethod method=new GetMethod();
response=method. getInternetData();// Then get the Json response
try{
JSONObject json=new JSONObject(response);
try {
String day =json.getString("day");
textView1.setText(day);
} catch (JSONException e) {
e.printStackTrace();
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And dont forget to add Internet Permission in Manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Try like this.
I am using httppost method in doinbackground and I am also getting the the response. Now when I pass the data to webservice I get a Jsonobject which I have to parse. and that jsonobject is stored in responsebody below. I have putted the return statement as "res". but in onpost execute I get a nullpointer exception.
I want to use the String responseBody in onpostexecute method?
class Thread extends AsyncTask<String, Void , String>{
private String responseBody;
private String res;
#Override
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpResponse response;
JSONObject json=new JSONObject();
HttpPost post = new HttpPost(url1);
try {
json.put("URL",getqrcode());
json.put("EmailID", getuseremail());
StringEntity stringEntity = new StringEntity(json.toString());
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
response = client.execute(post);
Log.e("RESPONSE", response.toString());
String responseBody = EntityUtils
.toString(response.getEntity());
String res= responseBody.toString();
Log.e("RESPONSE BODY", responseBody);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return res;
}
#Override
protected void onPostExecute(String res) {
Log.e("response is", res);
// TODO Auto-generated method stub
super.onPostExecute(res);
}
Make a Global variable of response
String res;
and use in onpostExecute() method:
and just replace
String res= responseBody.toString();
with
res= responseBody.toString();
only
Your global res is masking the local res defined in the try block.
Since the res variable you populate is local to the scope of the try block, it cannot be seen outside, and your compiler doesn't complain because of the global res.
You can simply affect the res member without re-declaring it:
res = responseBody;
Technically, it is not useful to declare the res variable globally, you can simply declare it in the method, but in the same scope as the return, that is, outside the try block (before it).
(also, the toString is not useful, as it will only return itself in the case of a String)
(the same goes for responseBody, the local scope hide the global scope. In this case, the global scope is useless)
Just insert this statement in the end of your doInBackground method :
return res;
This will return response to onPostExecute(String oString) wrap-up in oString
I've been trying to implement asynctask to make about 30 http requests to find the distance between two locations using a JSON object and the distance matrix api. The code I've written works when called from the main UI thread, but when I try to run it from the Async Task and save the distances to an array I just end up with an array full of null values. Any advice? (Note: This code was initially written by someone else at my work, and I've merely copy pasted it and changed a few lines to work with my app. So, there may be some unnecessary bits that I'm unaware of. Feel free to point them out)
class DistanceFinder extends AsyncTask<String[], Void, String[]>
{
#Override
protected String[] doInBackground(String[]... locations)
{
String baseURL="https://maps.googleapis.com/maps/api/distancematrix/json?origins=";
String[] distances = new String[locations[1].length];
for(int i = 1;i<locations.length;i++)
{
String url = baseURL + locations[0][0].replace(" ","+") + "&destinations=" + locations[1][i].replace(' ', '+') + "&sensor=true&units=imperial";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = "";
boolean internet;
try
{
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
internet=true;
}
else
{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
internet=false;
Toast.makeText(getApplicationContext(), "Please connect to internet", Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
internet=false;
Toast.makeText(getApplicationContext(),"Please connect to internet", Toast.LENGTH_LONG).show();
}
if(internet){
try
{
JSONObject jsonObj = new JSONObject(responseString);
JSONArray rows = jsonObj.getJSONArray("rows");
JSONObject inRows=rows.getJSONObject(0);
JSONArray elements = inRows.getJSONArray("elements");
JSONObject inElements=elements.getJSONObject(0);
JSONObject distance= inElements.getJSONObject("distance");
distances[i] = distance.getString("text");
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return distances;
}
#Override
protected void onPostExecute(String[] result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
distancesList = result;
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
}
Your problem is with you for loop
for(int i = 1;i<locations.length;i++)
First, you should start from 0, unless your first cell doesn't store a String you wish you check the distance to.
Second, your for loop should be
for(int i = 0;i<locations[0].length;i++)
Right now you're checking cells [1][0] and that's it, because the loop ends.
I tested it with manually entered locations and it works.
Also, just to make things easier for you to debug, You should really get used to using Log.d(). It really helps figuring out errors. I used it in your code and saw that the loop only gets executed once.
Good luck
P.s, as mentioned in one of the comments, remove the onPreExecute(). You don't use it.
Here is the class where i get JSON objects. In this code I get only one object and I don't really know how to return from the method, there is a Protected Void method where it is a settext method called and there is where the only JSON object goes.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://79.114.48.119/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("latitude");
}
public JSONObject lastTweet(String username) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet("");
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
}
}
What I want to do is to have an array where i could store three kind of objects (exemple Latitude[1], Longitude [1], Description[1]; Latitude[2] etc... I would like the latitude and longitude to be as integers ). After this I will use a for loop to call a function with this 3 parameters. Could anyone help me or could give me some tips ?
Thank you!
Dont use AsyncTask, as it executes in background, and this is why it causes some problems for you.
And when you have your twitter arser working, integrate it in a AsyncTask. Code below is not tested.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
int i;
JSONObject json;
final static String URL = "http://localhost/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
for(i=0;i<2;i++){
new Read().execute("latitude");
try {
json = lastTweet("",i);
String result = json.getString(params[i]);
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public JSONObject lastTweet(String username,int i) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(i);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
}