After following a tutorial online I was able to retrieve some data from twitter for my android application. The following code works. I just basically want to build an application which can retrieve data such as Diablo 3 character level. How do I go about doing this? I think I have to use this URL to retrieve the data http://us.battle.net/api/d3/profile/Fauntleroy-1134/ however I am having no luck.
public class HttpExample extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("created_at");
}
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);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(HttpExample.this, "error", Toast.LENGTH_SHORT);
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) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
The data your are retrieving from here are stored in an Array, so when you parse the data with
JSONArray timeline = new JSONArray(data);
you will get your JSONArray. Every element of the Array is an Object, so you get it with JSONObject last = timeline.getJSONObject(0); If you read the json string here you'll notice that the string starts with "{", so the root element is not an Array but an Object.
You need to change your parsing code, try something like this:
// test json string
String data = "{\"heroes\" : [ {\"name\" : \"UUUGUUUUUUUU\",\"id\" : 92352,\"level\" : 60,\"hardcore\" : false,\"paragonLevel\" : 0,\"gender\" : 0,\"dead\" : false,\"class\" : \"demon-hunter\",\"last-updated\" : 1340492305}, {\"name\" : \"RhubarbVole\",\"id\" : 7531555,\"level\" : 50,\"hardcore\" : false,\"paragonLevel\" : 0,\"gender\" : 1,\"dead\" : false,\"class\" : \"monk\",\"last-updated\" : 1339377909}, {\"name\" : \"VoodooFrodo\",\"id\" : 7698952,\"level\" : 32,\"hardcore\" : false,\"paragonLevel\" : 0,\"gender\" : 0,\"dead\" : false,\"class\" : \"witch-doctor\",\"last-updated\" : 1339376344}, {\"name\" : \"CheeseBird\",\"id\" : 13139301,\"level\" : 7,\"hardcore\" : false,\"paragonLevel\" : 0,\"gender\" : 1,\"dead\" : false,\"class\" : \"wizard\",\"last-updated\" : 1338098485} ]}";
root = new JSONObject(data);
JSONArray heroes = root.getJSONArray("heroes");
List<JSONObject> heroesList = new ArrayList<JSONObject>();
for(int i=0;i<heroes.length();i++){
JSONObject hero = heroes.getJSONObject(i);
heroesList.add(hero);
}
//...
JSONObject hero = heroesList.get(x);
int level = hero.getInt("level");
Related
Hi friends i like to parse the json from url and also like to elimate the null values field and only show the object which has value if anyone known syntax for that means please guide me thanks in advance.
JSON Structure
{
"daftar_rs": [
{
"Name": "exe1",
"URL": "http://samir-mangroliya.blogspot.in/p/android-json-parsing-tutorial.html"
},
{
"Name": "exe2",
"URL": "https://code.google.com/p/json-io/"
},
{
"Name": "exe3",
"URL": ""
},
{
"Name": "exe4",
"URL": "http://stackoverflow.com/questions/10964203/android-removing-jsonobject"
},
{
"Name": "exe5",
"URL": ""
},
{
"Name": "exe6",
"URL": ""
}
],
"success": 1
}
MainActivity
public class MainActivity extends Activity {
ListView lv;
List<String> titleCollection = new ArrayList<String>();
List<String> urlCollection = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String linkUrl = urlCollection.get(arg2);
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
});
}
public void loadContents()
{
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,titleCollection);
lv.setAdapter(adapter);
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://192.168.1.167/vinandrophp/vinex.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
loadContents();
}
}
}
JsonParser.java
public class JsonParser {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Just check it inside your code.
String linkUrl = urlCollection.get(arg2);
if (linkUrl== null || linkUrl.equals("")){
// null
}
else{
// not null so put to extras and start intent
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
try below code
for (int i = 0; i < dataJsonArr.length(); i++)
{
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String Name = c.getString("Name");
String Url = c.getString("URL")
if(!TextUtils.isEmpty(Name) && !TextUtil.isEmpty(Url))
{
titleCollection.add(Name);
urlCollection.add(Url));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection + ", URL: " + urlCollection);
}
try below code:-
if(c.getString("URL").equals("") || c.isNULL("URL"))
{
// do nothing
}
else
{
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
Change for loop as
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String name = c.getString("Name");
String url = c.getString("URL");
if(name != null && !(name.equals(""))
&& url != null && !(url.equals(""){
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
Try replace keys and values with regular expression if the key is empty in the JsonParser class.
json=json.replaceAll("\\n",""); //you should do not have any new lines after commas
json=json.replaceAll(",\\W*\"\\w+\":\\W?(\"\"|null)","");
i m getting this response in a result of GET request to server
{"LL": { "control": "dev/sys/getkey", "value": "4545453030304138303046392035343733373432363020323031332D30322D31312031383A30313A3135", "Code": "200"}}
i just want to extract the value of "value" from the above json response.
I m using this code to get this response
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.14.247/jdev/sys/getkey"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("Parse Exception", e + "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("IO Exception 2", e + "");
}
Log.i("responseText", responseText);
Toast.makeText(MainActivity.this, responseText + "",
Toast.LENGTH_SHORT).show();
}
});
my question is that how can i parse this and get the value of only "value" tag.
thanks
you can parse current json String to get value from it as :
// Convert String to json object
JSONObject json = new JSONObject(responseText);
// get LL json object
JSONObject json_LL = json.getJSONObject("LL");
// get value from LL Json Object
String str_value=json_LL.getString("value"); //<< get value here
try this
JSONObject json = (JSONObject) JSONSerializer.toJSON(responseText);
String value = json.getJSONObject("LL").getString("value");
Try this:
JSONObject json= json1.getJSONObject("LL");
String value= json.getString("value");
Try this,
JSONObject ResponseObject = new JSONObject(Response);
String str = ResponseObject.getJSONObject("LL").getString(value);
You can parse your response and get value try this:
try {
JSONObject jsonObject = new JSONObject(response);// Convert response string in to json object.
JSONObject jsonLL = jsonObject.getJSONObject("LL");// Get LL json object from jsonObject.
String strValue = jsonLL.getString("value");// Get value from jsonLL Object.
} catch (Exception e) {
e.printStackTrace();
}
Simple and Efficient solution : Use Googlle's Gson library
Put this in build.gradle file : implementation 'com.google.code.gson:gson:2.6.2'
Now convert the JSON String to a convenient datastrucutre like HashMap in 2 lines like this.
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(JsonString , type);
or you can use this below class :
To convert your JSON string to hashmap use this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
Thank me later :)
I am trying to pass a string array to my adapter. My problem is i initialized globally and try to create string array in my asynchronous task below. But i am getting as null. Below is my code. Actually in this example they taking it from resource folders bu i want it from my json response. Any help is appreciated.
String[] mString;
public ActionsAdapter(Context context) {
mInflater = LayoutInflater.from(context);
session = new SessionManager(context);
final Resources res = context.getResources();
new ConnectAppMenu(context).execute();
// mTitles = res.getStringArray(R.array.actions_names);
// mUrls = res.getStringArray(R.array.actions_links);
// mIcons = res.obtainTypedArray(R.array.actions_icons);
System.out.println("Menus"+ mString);
}
public class ConnectAppMenu extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
private final Context context;
public ConnectAppMenu(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// UI work allowed here
dialog = new ProgressDialog(context);
// setup your dialog here
dialog.setMessage("Connecting....");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
String returnConnect = doConnectAppMenu();
return returnConnect;
}
public String doConnectAppMenu() {
HashMap<String, String> user = session.getUserDetails();
String client_url = user.get(SessionManager.KEY_CLIENT);
// if(connection) {
HttpParams connectionParameters = new BasicHttpParams();
int timeoutConnection = 8000;
HttpConnectionParams.setConnectionTimeout(connectionParameters, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(connectionParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(connectionParameters);
HttpPost httpPost = new HttpPost(client_url+"/api/common/app_menu");
JSONObject json = new JSONObject();
try{
json.put("data", 1);
json.put("versionid", 1);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
//Execute HTTP post request
appmenu_res = httpClient.execute(httpPost);
appmenu_obj = new org.json.JSONObject(org.apache.http.util.EntityUtils.toString(appmenu_res.getEntity()));
appmenu_result = appmenu_obj.toString();
}
catch(JSONException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
return appmenu_result;
}
#Override
public void onPostExecute(String result) {
int status_code = appmenu_res.getStatusLine().getStatusCode();
if (status_code == 200) {
dialog.dismiss();
try {
menuObject = new JSONObject(result);
JSONArray names= menuObject.names();
JSONArray values = menuObject.toJSONArray(names);
for (int i = 0; i< values.length(); i++) {
JSONObject json2 = (JSONObject) values.get(i);
int menu_id = json2.getInt("menu_id");
if (menu_id > 0) {
if (json2.has("menu_name")) {
menu_list = json2.get("menu_name").toString();
mString = new String[] { menu_list };
//mUrls = menu_list.length();
}
}
}
System.out.println("Json Menu" + Arrays.toString(mString));
/*Iterator<String> iter = menuObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = menuObject.get(key);
//System.out.println("Hai" +value);
System.out.println("Post Execute" + value);
} catch (JSONException e) {
// Something went wrong!
}
}*/
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//dialog.dismiss();
}
}
}
well first of all if you're looking for the JSON object as a String don't do what you did here:
appmenu_obj = new org.json.JSONObject(org.apache.http.util.EntityUtils.toString(appmenu_res.getEntity()));
I'd suggest doing the following:
String Json = EntityUtils.toString(appmenu_res.getEntity());
return Json;
Now if you want to do the processing of your JSON on the UI thread (as you seem to want to based on the return type being a string) this should work. However this method is not recommended since the Json will need to be processed into objects which will take time and clog the UI thread.
A better solution would be to serialize your Json on the background thread and then pass the serialized object back to the main thread to update the UI.
If you have many types I would suggest using generics. I've already built a Loader which can do what you want if you want here. You will need touse the GSON library and build appropriate seralizers. Also working with the loader class is different to working with the AsyncTaskClass so please read the documentation here
Edit
Ok so what you want to do if you want get the Activity to have a callback from the AsyncTask is to do something along the lines of:
public class MyActivity extends Activity implements AsyncTaskCallback
where AsyncTaskCallback looks something like :
public interface AsyncTaskCallback
{
public processData(Object responseObject);
}
now in your onPostExecute code you'll need to do somehting like:
#Override
protected void onPostExecute(Object r){
if (r != null) {
l.processData(data);
}
}
and add the following function to your async task
public void addAsyncTaskListener (final AsyncTaskListener l){
mCallback = l;
}
and then finally add the listner and process the data as required in the Activity in the function processData function that the interface forces your activity to implement.
Instead of using String[] you can use ArrayList for Setting list in adaptor.
I would like to thank all the users in this community for helping me get as far as I am in my project today.
I now need your help once again. So far, I am able to establish a connection in my project from this JSON link (REMOVED FOR PRIVACY CONCERNS)
The problem is I am only able to parse one string, (firstName)
Here is my code:
public class JSONActivity extends Activity {
static TextView http;
HttpClient client;
JSONObject json;
final static String URL = "REMOVED FOR PRIVACY CONCERNS
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
http = (TextView) findViewById(R.id.http);
client = new DefaultHttpClient();
new Read().execute("firstName");
}
public JSONObject getpw(String password) throws ClientProtocolException,
IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(password);
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);
JSONObject getname = new JSONObject(data);
return getname;
} else {
Toast.makeText(JSONActivity.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = getpw("trustme");
return json.getString("firstName");
} 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
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
http.setText(result);
}
}
}
My question is, how can I parse multiple strings rather than just "firstName"?
You can get it all by doing the following:
String firstname = json.getString("firstName");
String lastname = json.getString("lastName");
int checkedIn = json.getInt("checkedIn");
int updated = json.getInt("checkedindatetime");
JSONObject address = json.getJSONObject("address");
String streetaddress = address.getString("streetAddress");
String city = address.getString("city");
etc...
JSONArray phoneNumbers = json.getJSONArray("phoneNumber");
String type = phoneNumbers.getJSONObject(0).getString("type");
etc...
Hope this helps.
A good resource for looking at json, is this validator.
After a few weeks of trying numerous examples found here and it seems throughout the web, I'm stumped. I can retrieve the desired search results from Google Shopping just fine:
{ "items": [ { "product": {
"title": "The Doctor's BrushPicks Toothpicks 250 Pack",
"brand": "The Doctor's" } } ] }
My problem is that I have the data sitting in a string, how do I extract the two values (title,brand) in order to use them elsewhere in the program?
Here is the class in question:
public class HttpExample extends Activity {
TextView httpStuff;
DefaultHttpClient client;
JSONObject json;
final static String URL = "https://www.googleapis.com/shopping/search...";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("items");
}
public JSONObject products(String upc) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(upc);
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);
JSONObject timeline = new JSONObject(data);
return timeline;
} else {
Toast.makeText(HttpExample.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
String upc = ExportMenuActivity.upc;
json = products(upc);
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
protected void onPostExecute(String result){
httpStuff.setText(result);
}
}
}
The output of httpStuff.setText(result):
[{"product":{"brand":"The Doctor's, "title":"The Doctor's..."}}]
A solution that'd work on all versions of Android would look something like this:
JSONObject products = products(jsonStr);
JSONArray itemArray = products.getJSONArray("items");
for(int i=0; i<itemArray.length(); i++) {
if(itemArray.isNull(i) == false) {
JSONObject item = itemArray.getJSONObject(i);
String title = item.getString("title");
String brand = item.getString("brand");
}
}
JsonReader is nice, but is only available in API 10 and up. So it might or might not work for you.
You should use a JsonReader for reading the json string. Its very easy and well documented with very good sample.. here