Parsing issue with json - java

I'm trying to parse the json data that I get back from lastfm.
The method I'm interested in is album.search
The documentation requires there to be a search term for the album name, and an api key, which I've done here:
String api_key = "x";
String url = "http://ws.audioscrobbler.com/2.0/?method=album.search" +
"&album="
+ query
+ "&apikey="
+ api_key
+ "&format=json";
Then my issue was trying to iterate through the json data so I can get to the value that I wanted, in my case, name, so I made an array to loop through the json file.
boolean error = false;
HttpClient httpclient = null;
try {
httpclient = new DefaultHttpClient();
HttpResponse data = httpclient.execute(new HttpGet(url));
HttpEntity entity = data.getEntity();
String result = EntityUtils.toString(entity, "UTF8");
for ( int i = 0; i < results.length(); i++) {
JSONObject row = new JSONObject(result);
albummatches = row.getString("albummatches");
album = row.getString("album");
name = row.getString("name");
results.getJSONObject(i).get("album");
I have this method which returns results.
public JSONArray getResults() {
return results;
}
Now in my other class, I'm trying to attach the name of the album to my adapter list view through this method.
public void ServiceComplete(AbstractService service) {
if (!service.hasError()) {
AlbumSearchService albumService = (AlbumSearchService)service;
String[] result = new String[albumService.getResults().length()];
for (int i = 0; i < albumService.getResults().length(); i++) {
try{
result[i] = albumService.getResults().getJSONObject(i).getString("name");
} catch (JSONException ex) {
result[i] = "Error";
}
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.album_list_cell, R.id.text, result));
}
But unfortunately, when I try to run the app, and search for an album, it just stays stuck on 'searching...', and doesn't display any results in my list view.
I don't know where I'm going wrong :( Help someone!

Related

Filtering in Android - issue that the code works but it doesn't return to the screen as expected

I've created an app in Android to retrieve restaurants in the local area and return them in list view. I've created individual arrays for each of the details in question (name / address / postcode & hygiene rating). Some of the venues are exempt and the array will return the information as -1, so I want to alter this using a filter, which I think I have done.
This is my Async Task which returns the JSON array.
// lets things run in the background, JSON Array to retrieve the list
class RetrieveNearestRestaurantsTask extends AsyncTask<Void, Void, JSONArray> {
private Exception exception;
// performs the search in the background / populates the arraylist
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected JSONArray doInBackground(Void... voids) {
// if the searchUrl conversion is empty
if (!searchUrl.toString().isEmpty()) {
// do this instead
try {
URL url = new URL(searchUrl.toString());
URLConnection tc = url.openConnection();
InputStreamReader isr = new InputStreamReader(tc.getInputStream());
BufferedReader in = new BufferedReader(isr);
String line; // variable
// while line in (read in) is not equal to null
// create a new object and output as line in JSON
while ((line = in.readLine()) != null) {
ja = new JSONArray(line);
// run through the length of the array
for (int i = 0; i < ja.length(); i++) {
JSONObject JO = (JSONObject) ja.get(i);
// output to meet Basic Functionality requirement
businessNames.add(JO.getString("BusinessName"));
postCodes.add(JO.getString("PostCode"));
addressList1.add(JO.getString("AddressLine1"));
addressList2.add(JO.getString("AddressLine2"));
addressList3.add(JO.getString("AddressLine3"));
// if the rating of the restaurant is -1, exempt
// should be displayed
ratingValue.add(JO.getString("RatingValue"));
ratingValue.stream()
.filter(x -> x.equals("-1"))
.findFirst()
.ifPresent(v -> System.out.println("Exempt"));
calcDistance.add(JO.getString("DistanceKM"));
// output everything together
ConcatenateSearchResults();
}
}
isr.close();
in.close();
//return ja;
} catch (Exception e) {
this.exception = e;
return ja;
} finally {
//is.close();
}
}
return ja;
}
Loads the search results.
protected void onPostExecute(JSONArray jsonArray) {
LoadSearchResults();
}
}
Concatenates the search results
private ArrayList<String> ConcatenateSearchResults()
{
int length = businessNames.size();
ArrayList<String> concatenatedResults = new ArrayList<>();
if(!businessNames.isEmpty() && !calcDistance.isEmpty() && !ratingValue.isEmpty()
&& !addressList1.isEmpty() && !addressList2.isEmpty() && !addressList3.isEmpty()
&& !postCodes.isEmpty())
{
for(int i=0; i < length; i++)
{
concatenatedResults.add("\n"+businessNames.get(i) +
"\nDistance (in Km) :"+ calcDistance.get(i) +
"\n\nRating: "+ ratingValue.get(i) +
"\nAddress Line 1: "+ addressList1.get(i) +
"\nAddress Line 2: "+ addressList2.get(i)+
"\nAddress Line 3: "+ addressList3.get(i) +
"\nPostcode: "+ postCodes.get(i));
}
}
return concatenatedResults;
}
}
However, I think somewhere I haven't enabled the proper ratingValue variable (?) to return the correct information (exempt instead of -1, where applicable, but I haven't worked out what I might have done wrong. Thank you for any help, I am slooowly getting better at explaining what I don't know.

How to send an JSON array to another method

I am fetching an JSON response from an API.
I should return those JSON response to another method with selected fields
Here I am fetching all the JSON response and putting it to an JSONArray which I should return to another method.
How to fetch both String and Long returning fields and put it into an JSON array and return it to another method
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("/2.0/clusters/list");
request.addHeader("Authorization", "bearerToken");
request.addHeader("cache-control", "no-cache");
HttpResponse response = client.execute(request);
System.out.println("Response Code:" +
response.getStatusLine().getStatusCode());
String json = EntityUtils.toString(response.getEntity());
System.out.println("Gather Details\n");
JSONObject cluster = new JSONObject(json);
JSONArray clusterJsonArray = cluster.getJSONArray("clusters");
for (int i = 0; i < clusterJsonArray.length(); i++) {
JSONObject iteratingObj = array.getJSONObject(i);
String id = iteratingObj.get("id").toString();
String time = iteratingObj.get("time").toString();
System.out.println("Id:" + id + "time:" + time + "\n");
List<String> strList = new ArrayList<>();
for (int p = 0; p < clusterJsonArray.length(); p++) {
strList.add(clusterJsonArray.getJSONObject(p).getString("id"));
strList.add(clusterJsonArray.getJSONObject(p).getString("time"));
}
System.out.println("Arr:" + strList);
if (response.getStatusLine().getStatusCode() != 200) {
System.out.println("Failed HTTPresponse" + response.getStatusLine().getStatusCode() + "" + json);
}
}
Help me out to send the response with selected fields to other method in which that JSONarray should take both String and Long values and store it in one varible of JSONArray.
Here is the incoming JSON:
"clusters": [
{ "id": "0411-0089ki", "driver": { }, "start_timestamp": 1568952332573, },
Here JSONObject["time"] not a string is the error i am facing when i am putting it to JSONArray
The intention of the above code you mentioned is not clear. But,
Here JSONObject["time"] not a string is the error i am facing when i
am putting it to JSONArray
You can use:
long time = iteratingObj.getLong("start_timestamp");
But you do not use the local variables of id and time in anywhere.
I think the logic is incorrect in the code that you put in the question. Please double check the logic for these 2 loops.
for (int i = 0; i < clusterJsonArray.length(); i++) {
for (int p = 0; p < clusterJsonArray.length(); p++) {

android recyclerview json load more items

I'm having this problem a little while, I need to load 25+ items from a database in json. When I load all of the including images etc. the app takes ages to load all of them. So I thought could I load the first five and when I scroll to the bottom the second five and so on. But it does not work. Here is my code:
Scroll listener:
rec.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visible = lin.getChildCount();
total = lin.getItemCount();
past = lin.findFirstVisibleItemPosition();
if ((visible + past) >= total){
new HttpAsyncTask().loadMore();
}
}
});
AsyncTask:
private class HttpAsyncTask extends AsyncTask<String, Void, List<PostsData>> {
int next;
#Override
protected List<PostsData> doInBackground(String... params) {
try {
//get json from url
JSONObject object = new JSONObject("{'posts':"+GET("http://www.website.com/json")+"}");
//get json array
JSONArray array = object.getJSONArray("posts");
for (int i = 0; i < 5; i++) {
next = i;
PostsData data = new PostsData();
//get object from array
JSONObject jsonObject = array.getJSONObject(i);
//title
data.setTitle(jsonObject.getString("name"));
//id
data.setId(jsonObject.getInt("id"));
JSONObject cat = jsonObject.getJSONObject("category");
//category name
data.setCatagorie(cat.getString("name"));
JSONObject img = jsonObject.getJSONObject("thumbnails");
//image url
String imgUrl = img.getString("preview_url");
//convert url into bitmap
data.setImage(getBitmap(imgUrl));
//get the post submitter name from array 'makers'
String makerFullname = "";
JSONArray userArray = jsonObject.getJSONArray("makers");
for (int j = 0; j < userArray.length(); j++) {
JSONObject user = userArray.getJSONObject(j);
//submitter full name
makerFullname = user.getString("full_name");
data.setUser(makerFullname);
}
data.setSubmitUser(jsonObject.getJSONObject("submitter").getString("full_name"));
//get the like count of the post
data.setLikeCount(jsonObject.getString("upvotes_count"));
list.add(data);
}
}catch (JSONException e){
e.printStackTrace();
}
return list;
}
// onPostExecute displays th
// results of the AsyncTask.
#Override
protected void onPostExecute(List<PostsData> result) {
adapter = new PostsAdapter(result, getContext());
rec.setAdapter(adapter);
}
public void loadMore(){
try {
//get json from url
JSONObject object = new JSONObject("{'posts':" + GET("http://www.materialup.com/api/v1/posts") + "}");
//get json array
JSONArray array = object.getJSONArray("posts");
if (array.length() <= next) {
for (int i = 0; i < next + 5; i++) {
next = i;
PostsData data = new PostsData();
//get object from array
JSONObject jsonObject = array.getJSONObject(i);
//title
data.setTitle(jsonObject.getString("name"));
//id
data.setId(jsonObject.getInt("id"));
JSONObject cat = jsonObject.getJSONObject("category");
//category name
data.setCatagorie(cat.getString("name"));
JSONObject img = jsonObject.getJSONObject("thumbnails");
//image url
String imgUrl = img.getString("preview_url");
//convert url into bitmap
data.setImage(getBitmap(imgUrl));
//get the post submitter name from array 'makers'
String makerFullname = "";
JSONArray userArray = jsonObject.getJSONArray("makers");
for (int j = 0; j < userArray.length(); j++) {
JSONObject user = userArray.getJSONObject(j);
//submitter full name
makerFullname = user.getString("full_name");
data.setUser(makerFullname);
}
data.setSubmitUser(jsonObject.getJSONObject("submitter").getString("full_name"));
//get the like count of the post
data.setLikeCount(jsonObject.getString("upvotes_count"));
list.add(data);
adapter.notifyDataSetChanged();
}
}
}catch(JSONException e){
e.printStackTrace();
}
}.....
It just won't load the next 5 items in the recyclerview. I searched on google but I did not really understand how load more works.
Thanks in advance, Sven.
This is the tutorial I followed: here
Make the next variable a static variable and start the loadMore method for statement with i=next+1,i <next+6 to avoid loading the same data again

Parse multiple of the same key JSON simple java

I'm not an expert at JSON so I'm not sure if I'm missing something obviously. But, what I'm trying to do is to parse this:
[{"name":"Djinnibone"},{"name":"Djinnibutt","changedToAt":1413217187000},{"name":"Djinnibone","changedToAt":1413217202000},{"name":"TEsty123","changedToAt":1423048173000},{"name":"Djinnibone","changedToAt":1423048202000}]
I don't want to get Djinnibone only the rest of the names following it. What I've managed to create is this. It give the right number of names. but they are all null. In this case null,null,null,null .
public String getHistory(UUID uuid) throws Exception {
String history = "";
HttpURLConnection connection = (HttpURLConnection) new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names").openConnection();
JSONArray response = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = new JSONObject();
for(int index = 1; index < response.size(); index++) {
jsonObject.get(response.get(index));
String name = (String) jsonObject.get("name");
if(index < response.size()) {
history = history + name + ",";
} else {
history = history + name + ".";
}
}
return history == "" ? history = "none." : history;
}
Thanks for any help!
You're almost there, you're getting each JSONObject from the array but you're not using it correctly. You simply need to change your code like this in order to extract each object and use it directly, no need for an intermediate JSONObject creation:
public String getHistory(UUID uuid) throws Exception {
String history = "";
HttpURLConnection connection = (HttpURLConnection) new URL("https://api.mojang.com/user/profiles/"+uuid.toString().replace("-", "")+"/names").openConnection();
JSONArray response = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for(int index = 1; index < response.size(); index++) {
JSONObject jsonObject = response.get(index);
String name = (String) jsonObject.get("name");
if(index < response.size()) {
history = history + name + ",";
} else {
history = history + name + ".";
}
}
return history == "" ? history = "none." : history;
}

Android parsing how to get value from this XML

just a simple question here. How can I get the return value on this kind of xml
Art C. Cauyao<$#FBID#$>501912568<$#ENDFBID#$>Tessa Rose
Brainard<$#FBID#$>510831686<$#ENDFBID#$>
Dan Gangan<$#FBID#$>513545777<$#ENDFBID#$>
C Jhec DawAko<$#FBID#$>523059320<$#ENDFBID#$>Jeremy
Please see that I am getting Facebook name and Facebook ID
Is there any way about that?
EDIT
I found out that it is not an xml but rather A JSON (sorry) now my question really is how can I incorporate that returned value?
EDIT SECOND
Sir this what I am doing
Parsing it through this
static final String URL_FBFRIEND ="Some URL"+ "getFBFriends.php";
Now using that I can now parse some data by using my input values. Here is the code
XMLparser parser2 = new XMLparser();
parser2.getXmlFromUrl(URL_FBFRIEND);
//HTTP POST
String url_Getmembermob= URL_FBFRIEND ;
String xml_getMembermob=null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_Getmembermob);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("...", "...."));
nameValuePairs.add(new BasicNameValuePair("fbID", modGen.facebookID ));
nameValuePairs.add(new BasicNameValuePair("accToken", modGen.tokenID));
nameValuePairs.add(new BasicNameValuePair("reqType", "0"));
Log.i("nameValuePairs", "nameValuePairs=" + nameValuePairs);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
xml_getMembermob = EntityUtils.toString(httpEntity);
Log.i("xml-return",""+ xml_getMembermob);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
See that I am logging the returned xml Log.i("xml-return",""+ xml_getMembermob); And thats the output
Sir Ive altered your code`
public static List parseUserList(String userData)
{
List ret = new ArrayList();
int index = 0;
while (index < userData.length())
{
int startFbTag = userData.indexOf(FB_NAME, index);
if (index == -1)
{
return ret;
}
String name = userData.substring(index, startFbTag - index);
startFbTag += FB_NAME.length(); // Start of the actual data
int endFbTag = userData.indexOf(FB_ID, startFbTag);
if (endFbTag == -1)
{
throw new IllegalArgumentException("Unterminated start tag");
}
fbTagValue = userData.substring(startFbTag, endFbTag - startFbTag);
Log.i("UserName",fbTagValue);
//fbId = Long.parseLong(fbTagValue);
//ret.add(new User(name, fbId));
index = endFbTag + FB_ID.length();
}
return ret;
}
I am getting an error here ** fbTagValue = userData.substring(startFbTag, endFbTag - startFbTag);**
what seems to be the problem
This is pretty horrible format. It's not XML. It's not JSON. Assuming you've already got some sort of User class, and that all the data is in a single String, you could write something like this (completely untested):
private static final String FB_START = "<$#FBID#$>";
private static final String FB_END = "<$#ENDFBID#$>";
public static List<User> parseUserList(String userData)
{
List<User> ret = new ArrayList<User>();
int index = 0;
while (index < userData.length())
{
int startFbTag = userData.indexOf(FB_START, index);
if (index == -1)
{
// No tags left. You should check whether you've actually got
// some data left, and potentially throw an exception. It's not
// clear what your data format does here.
return ret;
}
String name = userData.substring(index, startFbTag - index);
startFbTag += FB_START.length(); // Start of the actual data
int endFbTag = userData.indexOf(FB_END, startFbTag);
if (endFbTag == -1)
{
throw new IllegalArgumentException("Unterminated start tag");
}
String fbTagValue = userData.substring(startFbTag, endFbTag - startFbTag);
long fbId = Long.parseLong(fbTagValue);
ret.add(new User(name, fbId));
index = endFbTag + FB_END.length();
}
return ret;
}

Categories