Arraylist not getting repopulated after using notifyDataSetChanged() in java andriod - java

I am trying to use arraylist.clear and adapter.notifyDataSetChanged() to clear an arraylist the list is cleared successfully but when i try to reload the list again with some data the list is not showing despite the arraylist.size showing the total number of items which is greater than 0. Here is the method to create the initial list
private void getTH(int ID) {
url = "url";
mainAdapterClasses = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
try {
JSONObject jsonObject0 = new JSONObject(response);
String code = jsonObject0.getString("code");;
if (code.matches("200")) {
JSONArray jsonArray = jsonObject1.getJSONArray("items");
if(jsonArray.length() == 0){
txtEmpty.setText(String.format("%s %s", getString(R.string.no), getString(R.string.empty)));
} else {
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject jsonObject = jsonArray.optJSONObject(k);
String na = jsonObject.optString("na", "NA");
String aT = jsonObject.optString("Type", "NA")
MainAdapterClass mainAdapterClass = new MainAdapterClass();
mainAdapterClass.setName(na);
mainAdapterClass.setType(aT);
mainAdapterClasses.add(mainAdapterClass);
}
mainAdapter = new TAdapter(WalletHome.this, mainAdapterClasses);
listView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged();
txtEmpty.setText("Data Is Here"+mainAdapterClasses.size());
}
}
} catch (JSONException e) {
Toast.makeText(this, ""+getString(R.string.unknown_err), Toast.LENGTH_SHORT).show();
}
})
requestQueue.add(stringRequest);
}
and here is the code that is supposes to reload the list
#Override
public void getRadioButtonListener1(int position) {
WClass wClass = stateClassArrayList.get(position);
wId = wClass.getWId();
if(mainAdapter.getCount() > 0){
mainAdapterClasses.clear();
mainAdapter.notifyDataSetChanged();
getTH(id);
}
}
I tried to log the issue here the method is getting the current total of items everytime i run the method the only issue is that the list is not getting populated with the new data once it is initially cleared.
txtEmpty.setText("Data Is Here"+mainAdapterClasses.size());
Any help will be greatly appreciated thanks

At first glance it looks like you are creating and populating the "MainAdapterClass" with the "na" and "aT" variables but not using them anywhere, so you are not really adding items to mainAdapterClasses array.
Second of all, in the for loop you are recreating and setting the adapter each time. I would advise creating and setting the adapter outside of the foor loop once you have your array (mainAdapterClasses) populated with the requested items.
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject jsonObject = jsonArray.optJSONObject(k);
String na = jsonObject.optString("na", "NA");
String aT = jsonObject.optString("Type", "NA")
MainAdapterClass mainAdapterClass = new MainAdapterClass();
mainAdapterClass.setName(na);
mainAdapterClass.setType(aT);
mainAdapterClasses.add(mainAdapterClass);
} //for
mainAdapter = new TAdapter(WalletHome.this, mainAdapterClasses);
listView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged();
txtEmpty.setText("Data Is Here"+mainAdapterClasses.size());

You forgot to add mainAdapterClass to the ArrayList.
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject jsonObject = jsonArray.optJSONObject(k);
String na = jsonObject.optString("na", "NA");
String aT = jsonObject.optString("Type", "NA")
MainAdapterClass mainAdapterClass = new MainAdapterClass();
mainAdapterClass.setName(na);
mainAdapterClass.setType(aT);
mainAdapterClasses.add(mainAdapterClass); // Add this line.
}
Don't setAdapter inside the loop. Just add items and then set the adapter outside the loop.
Also calling notifyDataSetChanged() after setting adapter doesn't make sence.
for (int i = 0; i < jsonArray.length(); i++) {
// ...
}
listview.setAdapter(mainAdapter);

Related

Java code returns only one object from test method

I want to generate some test data using this Java code:
#GetMapping("/volumes")
public ResponseEntity<List<DashboardDTO>> getProcessingVolumes() {
return ResponseEntity.ok(testDate());
}
public List<DashboardDTO> testDate() {
List<DashboardDTO> list = null;
for (int i = 0; i <= 10; i++) {
list = new ArrayList<>();
DashboardDTO obj = new DashboardDTO();
obj.setAmount(ThreadLocalRandom.current().nextInt(20, 500 + 1));
LocalDate localDate = LocalDate.now().minus(Period.ofDays((new Random().nextInt(365 * 70))));
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
obj.setDate(date);
obj.setNumber_of_transactions(ThreadLocalRandom.current().nextInt(300, 5000 + 1));
list.add(obj);
}
return list;
}
But when the code is run only one object is generated. Do you know where I'm wrong? I want to generate 10 test objects.
Here:
for (int i = 0; i <= 10; i++) {
list = new ArrayList<>();
You create a new result list during each loop. So the last loop creates another list for the last entry!
Simply move that line list = new ArrayList<>(); in front of the loop, so that it gets executed just once.
Your code creates 11 new lists, each one with one entry, and you return that last list object. Instead: create one list and add your 11 elements and then return that single list.
for (int i = 0; i <= 10; i++) {
list = new ArrayList<>(); //(Fix here)--> resetting your list everytime causing only single object to return.
Try to initialize only single time.
List<DashboardDTO> list = new ArrayList<>();
for (int i = 0; i <= 10; i++) {
DashboardDTO obj = new DashboardDTO();
obj.setAmount(ThreadLocalRandom.current().nextInt(20, 500 + 1));
LocalDate localDate = LocalDate.now().minus(Period.ofDays((new Random().nextInt(365 * 70))));
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
obj.setDate(date);
obj.setNumber_of_transactions(ThreadLocalRandom.current().nextInt(300, 5000 + 1));
list.add(obj);
}
return list;

JSONArray weird results

I was trying to get some information from a different class in java using JSONArrays and JSONObjects but for some reason I get very weird results.
My Info.java class I have:
public JSONArray getSpawnedPets() {
JSONArray petsArray = new JSONArray();
JSONObject petO = new JSONObject();
boolean spawned = false;
for (int i = 0; i <= 3; i++) {
spawned = true;
if (spawned) {
petO.put("petID", i);
petO.put("petOwner", "owner"+i);
petO.put("petName", "name");
petO.put("color", "s");
petO.put("particle", "s");
petsArray.add(petO);
}
}
return petsArray;
}
On my Main.java class I have:
public class main {
public static void main(String[] args) {
JSONArray petsArray = new JSONArray();
Info in = new Info();
petsArray = In.getSpawnedPets();
if (petsArray != null) {
for (int i = 0; i < petsArray.size(); i++) {
JSONObject po = (JSONObject) petsArray.get(i);
System.out.println("PetInfo:");
System.out.println(po.get("petID")+":");
System.out.println(""+po.get("petName"));
System.out.println(""+po.get("petOwner"));
}
}
}
}
The results were supposed to be increasing but yet I get this:
PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3
PetInfo:
3:
name
owner3
Did I do something wrong? I can't find my problem, the same code but not using classes works, but I have to use classes for it.
Cheers.
Create jsonobject in every iteration otherwise , there is only one JSONObject JSONObject petO = new JSONObject(); which is being updated in every iteration of loop
JSONArray petsArray = new JSONArray();
JSONObject petO;
//boolean spawned = false; // no need of it
for (int i = 0; i <= 3; i++) {
//spawned = true;
//if (spawned) { // no need of it , has no effect, always true
petO = new JSONObject();
// ^^^^^^^^^^^^^^^^^
petO.put("petID", i);
petO.put("petOwner", "owner"+i);
petO.put("petName", "name");
petO.put("color", "s");
petO.put("particle", "s");
petsArray.add(petO);
//}
}
Note : Since spawned is a local variable and will be set to true in first iteration and has no effect in code so there is no need of if

how to use shared preferences to save array list items?

I use these 2 methods for save and load my array list and I need to save my array list after each item dynamically added to array.
public void addItems(int howMany){
if (howMany > 0) {
int lastInsertedIndex = 11;
for (int i = lastInsertedIndex + 1; i <= lastInsertedIndex + howMany; i++) {
mList.add("Item " + i);
notifyItemInserted(mList.size() - 1);
}
lastInsertedIndex = lastInsertedIndex + howMany;
}
}
and my save and load method:
public boolean saveArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Set<String> set = new HashSet<String>();
set.addAll(mainListAdapter.mList);
editor.putStringSet("list", set);
return editor.commit();
}
public ArrayList<String> getArray() {
SharedPreferences sp = context.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
//NOTE: if shared preference is null, the method return empty Hashset and not null
Set<String> set = sp.getStringSet("list", new HashSet<String>());
return new ArrayList<String>(set);
}
My problem is : when I add a new item with button nothing happen and like the array list is full how to fix this ?
The the following:
Declare myList globally:
ArrayList<String> myList = new ArrayList<String>();
For setting value:
for (int i = 0; i < totalSize; i++) {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString("number" + i, value + "").commit();
}
For getting value:
for (int i = 0; i < totalSize; i++) {
myList.add(PreferenceManager.getDefaultSharedPreferences(this)
.getString("number" + i, "0"));
}
NOTE:- totalSize is the size of your array
enjoy coding.............
I think you should try using TinyDB, it's an implementation of SharedPreferences and is very simple to use.
TinyDB tinydb = new TinyDB(context);
tinydb.putList("identifier", list);
You can even save objects:
tinydb.putObject(key, object);
tinydb.putListObject(key, objectsArray);

Get JSON String by iterating over array inside an object

Im working on an app where Im parsing JSON file and get the strings from it, but there is one String I have no idea why cant I get it into my activity.
the String is Object > Array > String
I have 2 activities and 1 model.
MainActivity: where Im parsing the JSON.
DetailActivity: where I need the String.
PostModel: a model where I have all setter and getter.
JSON:
{
"status":"ok",
"count":10,
"count_total":184,
"pages":19,
"posts":[
{ },
{
"id":2413,
,
"categories":[
{
"id":100,
"slug":"logging",
"title":"logging",
"description":"",
"parent":0,
"post_count":1
}
],
"comments":[
{
"id":3564,
"content":"<p>\u47 <\/p>\n",
"parent":0
}
],
"comment_count":1,
"thumbnail":"http:\/\/www.5.com\/wtent\g",
"custom_fields":{
"dsq_thread_id":[
"2365140"
],
"videoID":[
"--ffwf92jvDFy"
]
},
"thumbnail_images":{
"full":{
"url":"http:\/\/www.5.com\/jpg",
"width":727,
"height":454
},
"thumbnail":{
"url":"http:\/\/www.5.com\/wp-con50.jpg",
"width":150,
"height":150
}
}
}
]
}
PostModel:
private List<VidCast> videoIDList;
private String videoID;
public String getVideoID() {
return videoID;
}
public void setVideoID(String videoID) {
this.videoID = videoID;
}
public List<VidCast> getvideoIDList() { return videoIDList; }
public void setvideoIDList(List<VidCast> videoIDList) {
this.videoIDList = videoIDList;
}
public static class VidCast {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
MainActivity:
List<PostModel.VidCast> vidCasts = JsonPath.parse(URL_TO_HIT).read("$.posts.[*].custom_fields.[*].videoID[*]");
vidCasts = new ArrayList<>();
for (int s = 0 ; s < finalObject.getJSONArray("custom_fields").length() ; s++){
PostModel.VidCast vidCast = new PostModel.VidCast();
vidCast.setName(videoID);
vidCasts.add(vidCast);
}
postModel.setvideoIDList(vidCasts);
// adding the final object in the list
postModelList.add(postModel);
}
return postModelList;
}
}
DetailActivity:
StringBuffer stringBuffer = new StringBuffer();
for(PostModel.CategoryCast categoryCast : postModel.getCategoryCastList()){
stringBuffer.append(categoryCast.getName() + ", ");
}
StringBuffer videoStringBuffer = new StringBuffer();
for(PostModel.VidCast videoIDList : postModel.getvideoIDList()) {
videoStringBuffer.append(videoStringBuffer.toString());
}
At the last file is where I need to get the <> String. I spent a lot of time I just cant figure it out how I can iterate over array inside an object.
Thanks in advance!
__________update________
I managed to parse it that way :
JSONObject customFields = finalObject.getJSONObject("custom_fields");
JSONArray vidCastsJson = customFields.getJSONArray("videoID");
List<PostModel.VidCast> videoIds = new ArrayList<>();
for (int s = 0 ; s < vidCastsJson.length() ; s++){
PostModel.VidCast vidCast = new PostModel.VidCast();
vidCast.setName(vidCastsJson.optString(s));
videoIds.add(vidCast);
String videoID = String.valueOf(vidCastsJson);
vidCast.setName(videoID);
and I use Stringbuffer at DetailActivityStringBuffer
videoStringBuffer = new StringBuffer();
for(PostModel.VidCast vidCast : postModel.getvideoIDList()) {
videoStringBuffer.append(vidCast.getName());
String videoID = vidCast.toString();
}
But now I'm getting the videoID with the array brackets like that ["F3lyzrt"] I want it as a string to be only F3lyzrt, so I can pass it to my youtube player. Any advice will be appropriated.
Thanks,
It would look something like this:
JSONObject root = // however you get your root JSON object
JSONArray posts = root.optJSONArray("posts");
for(int i=0; i < posts.length(); i++){
JSONObject post = posts.optJSONObject(i);
int id = post.optInt("id");
JSONArray categories = post.optJSONArray("categories");
// etc.
}
Though you might want to consider using GSON or Jackson. With those libraries you can define a model to represent the data (jsonschema2pojo.org can help with that) and then it does all the parsing for you.
EDIT
You're not even trying to get the video id. Here's your code:
for (int s = 0; s < finalObject.getJSONArray("videoID").length(); s++){
{
postModel.setVideoID(videoID);
postModelList.add(postModel);
}
You see how you're not retrieving the contents of the json array?
JSONArray videoIds = finalObject.getJSONArray("videoID");
for (int s = 0; s < videoIds.length(); s++){
String videoID = videoIds.optString(s);
postModel.setVideoID(videoID);
postModelList.add(postModel);
}

How to set Checkbox value into a array android

I got an ArrayList:
ArrayList<CheckBox> swmsInfo = new ArrayList<CheckBox>();
and some checkboxes:
checkBoxCompany = createCheckBox(R.id.checkBoxCompany);
checkBoxName = createCheckBox(R.id.checkBoxName);
checkBoxPhone = createCheckBox(R.id.checkBoxPhone);
checkBoxAdress = createCheckBox(R.id.checkBoxAdress);
I want to get their values 0 or 1 if some of the checkboxes are checked or not , and when i got their values i want to put them into a array. My checkboxes are inside a array
ArrayList<CheckBox> boxes = new ArrayList<CheckBox>();
You can loop through the arraylist and get the value. Something like
for (int i = 0; i<boxes.size(); i++){
CheckBox cb = boxes.get(i);
if (cb.isChecked()){
System.out.println("checked");
//from here you can populate you array
}else{
System.out.println("not checked");
//from here you can populate you array
}
}
======= Edit after the comment =======
public class CheckBoxStatus{
CheckBox cb;
boolean blnIsChecked;
public CheckBoxStatus(CheckBox cb, boolean blnIsChecked){
this.cb = cb;
this.blnIsChecked = blnIsChecked;
}
public CheckBox getCheckbox(){
return this.cb;
}
public boolean getStatus(){
return this.blnIsChecked;
}
public boolean setStatus(boolean blnIsChecked){
this.blnIsChecked = blnIsChecked;
}
}
//Now in your code instead of ArrayList<CheckBox>, use ArrayList<CheckBoxStatus>
ArrayList<CheckBoxStatus> alCBS = new ArrayList<CheckBoxStatus>();
CheckBoxStatus cbs = new CheckBoxStatus(<checkbox instance>, false); //pass false as default value;
alCBS.add(cbs);
//Modified loop
for (int i = 0; i<boxes.size(); i++){
CheckBox cb = boxes.get(i);
CheckBoxStatus cbs = new CheckBoxStatus(cb, cb.isChecked());
boxes.set(i, cbs);
}

Categories