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
Related
I have this code to parse a json in Java, but problem is my json looks like this
{"ime":"Alen","prezime":"Osmanagi\u0107","test":[1,2,3,4,5],"test2":{"1":"test","2":"555","test":"888","om":"hasd"}}
And my java code for parsing looks like :
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListView listView =(ListView)findViewById(R.id.jsonList);
if ( true) {
try {
JSONArray mojNiz = response.getJSONArray("");
List<JSON> noviJSON = new ArrayList<>();
//Popuniti podacima
for (int i = 0; i < mojNiz.length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = mojNiz.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
// jsonObj.setPrezime(mojObj.getString(KEY_DOB));
//jsonObj.setPrezime(mojObj.getString(KEY_DESIGNATION));
noviJSON.add(jsonObj);
}
adapter = new Adapter(noviJSON, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,
"Problem u loadiranjuz podataka",
Toast.LENGTH_LONG).show();
}
How can I parse this particular json string ???
First get the JSONObject and then the array inside it
JSONObject jsonObject = new JSONObject(jsonString);
String objectIme = jsonObject.getString("ime");
String prezime = jsonObject.getString("prezime");
The above line will get the whole object and from this object you can get other objects and the array test1 and test2 like below then you can loop through that array like you did
JSONArray jArray1 = new JSONArray(jsonObject.getJSONArray("test1"));
JSONArray jArray2 = new JSONArray(jsonObject.getJSONArray("test2"));
for (int i = 0; i < jArray1 .length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = jArray1.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
}
You are parsing your json wrong. Your json starts with jsonObject instead of jsonArray. So in your case you have to start like this
(assuming that your result variable of onPostExecute method has the json string)
JSONObject mojNiz = new JSONObject(result);
Now from the above mojNiz object you can get your json array
String s = "{\"ime\":\"Alen\",\"prezime\":\"Osmanagi\\u0107\",\"test\":[1,2,3,4,5],\"test2\":{\"1\":\"test\",\"2\":\"555\",\"test\":\"888\",\"om\":\"hasd\"}}";
try {
JSONObject jsonObject = new JSONObject(s);
jsonObject.getString("ime");
jsonObject.getString("prezime");
JSONArray jsonArray = jsonObject.getJSONArray("test");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add((Integer) jsonArray.get(i));
}
JSONObject testObject = jsonObject.getJSONObject("test2");
testObject.getString("1");
testObject.getString("2");
} catch (JSONException e) {
e.printStackTrace();
}
If I clear the list view, the listview will gone.The list view will fetch data from the for loop.
Workarounds:
Putting setdaylist.clear() inside the any loop will clear the all listview and display only one list item.
Setting it at the top of method will erase all the listview, any solution?
Code:
public void onDataGotOnline(JSONObject response) {
DateTime today = new DateTime().withTimeAtStartOfDay();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
try {
JSONArray currentData = response.getJSONArray("list");
// setdaylist.clear();
for (int i = 1; i < 5; i++) {
DateTime tomorow = today.plusDays(i).withTimeAtStartOfDay();
String dtStr = fmt.print(tomorow);
int info = 0;
for(; info<currentData.length();info++ ){
JSONObject managedata = currentData.getJSONObject(info);
String time= managedata.getString("dt_txt");
if(time.equals(dtStr)){
int getResult=info+8;
double[] arrayAverageTemp = new double[8];
double[] arrayMaxTemp = new double[8];
double[] arrayMinTemp = new double[8];
int[] arrayWheaterId = new int[8];
for (int a = info; a < getResult; a++) {
JSONObject datalist = currentData.getJSONObject(i);
JSONArray weatherdata = datalist.getJSONArray("weather");
JSONObject weatherdata2 = weatherdata.getJSONObject(weatherdata.length() - 1);
int id = weatherdata2.getInt("id");
JSONObject weather = datalist.getJSONObject("main");
double avg_temp = weather.getDouble("temp");
double max_temp = weather.getDouble("temp_max");
double min_temp = weather.getDouble("temp_min");
arrayWheaterId[a-info]=id;
arrayAverageTemp[a-info]=avg_temp;
arrayMaxTemp[a-info]=max_temp;
arrayMinTemp[a-info]=min_temp;
}
ManageData manageData = new ManageData();
double max = manageData.findMax(arrayMaxTemp);
double min = manageData.findMin(arrayMinTemp);
WheatherData day = new WheatherData();
day.setDay("sunday");
// int image = convert.covertImage(icon);
day.setImage(R.drawable.ic_image_01d);
day.setDescrption("asdasd");
day.setAvgTemp("14 °c");
day.setMaxTemp(max+ "°c");
day.setMinTemp(min+ "°c");
setdaylist.add(day);
adapter.notifyDataSetChanged();
// findMax(arrayMaxTemp);
//findMin(arrayMinTemp);
//findID(arrayWheaterId);
//findaverage(arrayAverageTemp);
}
}
}
}
catch (JSONException e){
}
}
From the discussion above.
Issue was due to the caching problem in Android studio.
Cleaning Project and Building it removes the existing cache.
By which the setdaylist before the for loop shown below works as expected.
public void onDataGotOnline(JSONObject response) {
...
try {
...
setdaylist.clear();
for (int i = 1; i < 5; i++) {
...
for(; info<currentData.length();info++ ){
...
if(time.equals(dtStr)){
...
setdaylist.add(day);
...
}
}
}
}
catch (JSONException e){}
}
I get data from Json and there's a Json array. I want to convert that Json array into String array, so I can send it into another activity and show it in ListView.
Here's My java code
if (jsonStr != null) {
try {
foodsFilter = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foodsFilter.length(); i++) {
JSONObject c = foodsFilter.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String filter_type = c.getString(TAG_FILTER_TYPE);
//String item_list = c.getString(TAG_ITEM_LIST);
JSONArray itemList = new JSONArray(c.getString("item_list"));
String item_list = itemList.toString();
// tmp hashmap for single contact
HashMap<String, String> filter = new HashMap<String, String>();
// adding each child node to HashMap key => value
filter.put(TAG_CATEGORY_NAME, category_name);
filter.put(TAG_FILTER_TYPE, filter_type);
filter.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodsFilterList.add(filter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I try that code to convert the JSONarray, but I realized that code is for convert the JSONArray into String.
Here's my JSON data
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}]
I want to convert the item_list Array into like this
item_list = {"Ascending", "Descending"}
So I can send it into another activity use Intent and show it in ListView
What you have
String item_list = itemList.toString();
You need to parse items_list which is a JSONArray.
JSONArray itemList = new JSONArray(c.getString("item_list"));
// loop through the array itemList and get the items
for(int i=0;i<itemList.length();i++)
{
String item = itemList.getString(i); // item at index i
}
Now you can add the strings to a list/array and then do what is required.
Please have a look on this tutorial.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Maybe this would help you.
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
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!
Why I am getting duplicate entries in my ArrayList<String[]>?
allStepsJSONStringArray contains an array of single strings in the format of JSON
I loop through and pass each JSON string to a function that writes it to a temporary internal file
I read the file
Then pass it to getStepsArray() which breaks down the JSON string and puts each entry into a String[]
Loop to add to master ArrayList - allStepsArray
for (int i = 0; i < allStepsJSONStringArray.size(); i++) {
writer.writeToInternal(allStepsJSONStringArray.get(i));
reader.readFromInternal(writer.filename);
stepsArray = reader.getStepsArray();
for (int s = 0; s < stepsArray.size(); s++) {
allStepsArray.add(stepsArray.get(s));
}
}
getStepsArray()
public ArrayList<String[]> getStepsArray() {
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("steps");
String stepOrder = null;
String stepName = null;
String stepType = null;
String stepId = null;
String checklistId = null;
String checklistName = null;
for (int i = 0; i < jArray.length(); i++) {
stepOrder = jArray.getJSONObject(i).getString("order");
stepName = jArray.getJSONObject(i).getString("name");
stepType = jArray.getJSONObject(i).getString("type");
stepId = jArray.getJSONObject(i).getString("id");
checklistId = jObject.getString("checklistId");
checklistName = jObject.getString("checklistName");
stepsArray.add(new String[] {stepOrder, stepName, stepType, stepId, checklistName, checklistId});
}
} catch (Exception e) {
e.printStackTrace();
}
return stepsArray;
}
Word for word:
Because you don't seem to ever reset stepsArray. The second time you add elements to it, the previous elements will still be there and will get added to allStepsArray again.