Android parse json array(parse data from string) - java

Below is the response i am getting from the server,
{
"section_id": "[24,1,5,2]"
}
and I am using GSON library
public class SectionModel {
#SerializedName("section_id")
private String mSectionId;
public String getmSectionId() {
return mSectionId;
}
public void setmProgramName(String mSectionId) {
this.mSectionId = mSectionId;
}
}
I am able to get the value "[2,18,25,26]" and store it in a String.
Now how am I supposed to get those values from String and store in an Integer arraylist.

Try this method in your code:
public ArrayList<Integer> returnArrayList(String parsetest){
ArrayList<Integer> integerArrayList= new ArrayList<>();
parsetest=parsetest.replace("[", "");
parsetest=parsetest.replace("]", "");
String[] list = parsetest.split(",");
for (String item : list) {
integerArrayList.add(Integer.valueOf(item));
}
return integerArrayList;
}
Feel free to ask any doubt in the method.

Related

How to read MultiValue ArrayList in Java

I've defined a arrayList as following
List<List<RiskyPersons>> dataArray = new ArrayList<>();
Here is RiskyPersons Class
public class RiskyPersons {
private SA3Tenant sa3tenant;
private int NumberofPersonInCategory;
public RiskyPersons(){
}
public RiskyPersons(SA3Tenant sa3tenant, int NumberofPersonInCategory) {
this.sa3tenant = sa3tenant;
this.NumberofPersonInCategory = NumberofPersonInCategory;
}
}
Then I've successfully added data and saved in dataArray ArrayList.
Following output is showing the saved ArrayList using SOP(dataArray);
[[RiskyPersons{sa3tenant=Homeless.SA3Tenant#3a7cc6b0, NumberofPersonInCategory=99}]]
I want to read this dataArray ArrayList and display values separately. How do I access "NumberofPersonInCategory" value?
From Java-8 and above one can use stream:
dataArray.stream()
.flatMap(List::stream)
.map(RiskyPersons::NumberofPersonInCategory)
.forEach(System.out::println)
I hope this will help you !
public class RiskyPersons {
private SA3Tenant sa3tenant;
private int NumberofPersonInCategory;
public int getNumberofPersonInCategory() {
return NumberofPersonInCategory;
}
public RiskyPersons(){
}
public RiskyPersons(SA3Tenant sa3tenant, int NumberofPersonInCategory) {
this.sa3tenant = sa3tenant;
this.NumberofPersonInCategory = NumberofPersonInCategory;
}
}
List<Integer> values = dataArray.parallelStream().flatMap(Collection::stream).map(RiskyPersons::getNumberofPersonInCategory)
.collect(Collectors.toCollection(ArrayList::new));
You'll need to iterate it twice as
for (List<RiskyPersons> rp : dataArray) {
for (RiskyPersons o : rp) {
System.out.println(o.NumberofPersonInCategory); // unrelated : but its bad naming convention
}
}

Printing all data from HashMap

The code looks like this.
public class Album {
public String currentTitle;
public HashMap<String, List<Music>> albumList = new HashMap<String, List<Music>>();
//setting the album's title
public Album(String albumTitle) {
this.currentTitle = albumTitle; //represents object's name
albumList.put(currentTitle, null);
}
//add music to album
public void addMusicToThis(Music music) {
//only if value is empty
if(albumList.get(currentTitle) == null) {
albumList.put(currentTitle, new ArrayList<Music>());
}
albumList.get(currentTitle).add(music);
}
public void printMusicList() {
}
}
and I want to print all values for the specific album, like
Album album = new Album("Test1");
Album album2 = new Album("Test2");
album.addMusicToThis(something); //this code works fine
album2.addMusicToThis(something2);
album.printMusicList(); //maybe "something"
album2.printMusicList(); //maybe "something2"
but the hashMap's values are all set to List, and I can't find the way to print the musics out.
And assume that music's name is all set.
You just get the list for a particular string, and iterate it
for(Music m : albumList.get(this.currentTitle)) {
System.out.println(m.getName());
}
It's not really clear why you're using a Hashmap, though. Your key can never change.
You must iterate over the obtained list and print the individual entries
In Java 8 you can,
albumList.get(currentTitle).forEach((music) -> System.out.println(musice.getRequiredDetails)})
You can call albumList.entrySet() which is actually iterable, traverse it and print it however you like
I think you should add the albumTitle as an argument of the printMusicList function.
For example
public void printMusicList(String albumTitle) {
List<Music> musics = albumList.get(albumTitle);
for (Music music : musics) {
System.out.println(music);
}
}
or if you want to print it all
public void printMusicList() {
Set<String> keys = albumList.keySet();
for (String key : keys) {
List<Music> musics = albumList.get(key);
for (Music music : musics) {
System.out.println(music);
}
}
}

How to add Array in a class to JLIST JAVA?

I want to add the name of array in the class to jList as below.
How can it be?
this is the method in display class
public void dataToLocal(List<XDataObject> data, XServiceType xst, XServiceOperation operation) {
if(operation.getName().equals(SNOWTAMSubscriberServiceInterface.OP_PUBLISSNOWTAM)) {
SNOWTAMPublication snowtamPublication =
(SNOWTAMPublication)data.get(0).getValue(); //This read an array with 5 values.
SNOWTAM snowtam = snowtamPublication.getSNOWTAM()[0]; //This read read the array and its contents.
jList1.add((Component) Arrays.asList((snowtamPublication.getSNOWTAM()[0]).toString())); //Here I want to add the name of Array to be as below
}
}
This is SNOWTAMPublication which is only get and set methods for array.
protected SNOWTAM[] snowtam;
public SNOWTAM[] getSNOWTAM() {
if(snowtam == null)
{
snowtam = new SNOWTAM[0];
}
return snowtam;
}
public void setSNOWTAM(SNOWTAM[] _value) {
this.snowtam = _value;
}
The picture
You could try:
<instance>.getClass().getSimpleName()

How can I add a value to an ArrayList from an inner method?

I am currently trying to add a value to an ArrayList object from a method inside of another class.
Here is the class I have created for the ArrayList Object:
public class ArrayClass {
public static ArrayList<String> array = new ArrayList<>();
public static void add_val(String s){
array.add(s);
}
public static int get_size(){
return array.size();
}
public static String get_val(int i){
return array.get(i);
}
}
And the other class where I attempt to edit the ArrayList object:
ArrayClass fill = new ArrayClass();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore);
Response.Listener<String> responseListener4 = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse4 = new JSONObject(response);
boolean success = jsonResponse4.getBoolean("success");
if (success){
int l;
String filled;
int length4 = jsonResponse4.length();
for (l=0;l<length4;l++){
filled = jsonResponse4.getString(l+"");
fill.add_val(filled);
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(ExploreActivity.this);
builder.setMessage("Could not retrieve restaurant tables filled")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
FilledRequest filledRequest = new FilledRequest(responseListener4);
RequestQueue queue4 = Volley.newRequestQueue(ExploreActivity.this);
queue4.add(filledRequest);
If you look in the onResponse method, you can see the attempt to add a value from the jsonResponse into the ArrayClass object. However, when I launch my app, it does not add the value into the object. I'm used to python global variables and not having to deal with the semantics of java, so if you could shed some light on what changes need to be made, I would greatly appreciate it.
Apart from other given answers/solutions to the issue you are facing, let me share a best and optimized way to implement JSON parsing in Android.
I would suggest you to check GSON or Jackson libraries which provides Java serialization/deserialization that can convert Java Objects into JSON and back.
There are some benefits it does provide, one of the main benefits is you do not need to implement parsing manually and less chances of mistakes in implementing parsing, like you may make a mistake in mentioning key "Success" or "success" or any such silly mistakes!
Firstly, since your variable is static, and the methods are static too, you don't have to instantiate the object. You could do something like this:
ArrayClass.add_val("Hello");
But if you want to instantiate then you can do this:
public class ArrayClass {
private ArrayList<String> array;
public ArrayClass() {
array = new ArrayList<>();
}
public void add_val(String s){
array.add(s);
}
public int get_size(){
return array.size();
}
public String get_val(int i){
return array.get(i);
}
}
To make sure the values are filled in, you can check the array size like this:
for (l=0;l<length4;l++){
filled = jsonResponse4.getString(l+"");
fill.add_val(filled);
}
Log.d("TEST", String.valueOf(fill.get_size());
Remove all cases of the static keyword in ArrayClass. Static methods are class level methods, ie. are called on the class itself, rather than an instance of the class.
You can also try this, for ArrayList:
First do some changes in your ArrayClass. Use get And Set method to access your array.
public class ArrayClass {
private ArrayList<String> array = new ArrayList<>();
public ArrayList<String> getArray() {
return array;
}
public void setArray(ArrayList<String> array) {
this.array = array;
}
}
And your other class where you attempt to edit the ArrayList use getArray And SetArray method and some predefined method of ArrayList like this:
Store the data in ArrayList:
for (l=0;l<length4;l++){
filled = jsonResponse4.getString(l+"");
fill.getArray().add(filled);
}
Get Size of ArrayList:
fill.getArray().size();
And also you can store an another ArrayList like
ArrayList<String> tempArrayList = new ArrayList<String>();
tempArrayList.add("string 1");
tempArrayList.add("string 2");
tempArrayList.add("string 3");
tempArrayList.add("string 4");
fill.setArray(tempArrayList)

Dynamically Selecting Fields from Java Objects

I've got an Object in Java representing the contents of a database, like so:
public Database {
int varA;
String varB;
double varC;
}
Now I'm trying to select and order certain elements for forther processing, but I want to make it configurable, so I created an enum which represents all attributes of the object like
public enum Contents {
VarA,
VarB,
VarC;
}
So now when I create a selection like
Contents[] select = { Contents.VarC, Contents.VarB };
i want to generate a List of String values representing the actual database contents from this. Now the only Implementation i could think of is switching for each entry in the selection, with has a pretty ugly quadratic complexity...
public List<String> switchIT(Database db, Contents[] select) {
List<String> results = new ArrayList<String>();
for (Contents s : select) {
switch(s) {
case VarA:
results.add(db.varA.toString());
break;
//go on...
}
}
return results;
}
is there a more direct way to map between enum and dynamic object values?
Or in more general terms: What is the best way to select values from an object dynamically?
Use the power of Java enums, which are fully-fledged classes.
public enum Contents {
VarA { public String get(Database d) { return d.getVarA(); } },
VarB { public String get(Database d) { return d.getVarB(); } },
VarC { public String get(Database d) { return d.getVarC(); } };
public String get(Database d) { return ""; }
}
Your client code then becomes
public List<String> switchIT(Database db, Contents[] select) {
List<String> results = new ArrayList<String>();
for (Contents s : select) results.add(s.get(db));
return results;
}
A more concise, but slower, solution would be to use a single implementation of get based on reflection and use the name of the enum member to generate the appropriate getter name:
public enum Contents {
VarA, VarB, VarC;
private final Method getter;
private Contents() {
try {
this.getter = Database.class.getMethod("get"+name());
} catch (Exception e) { throw new RuntimeException(e); }
}
public String get(Database d) {
try {
return (String) getter.invoke(d);
} catch (Exception e) { throw new RuntimeException(e); }
}
}

Categories

Resources