I'm using lib FlexibleAdapter to load JSON API in android studio like this.
public void createHolderSectionsDatabase(int size, int headers) {
databaseType = DatabaseType.MODEL_HOLDERS;
HeaderHolder header = null;
mItems.clear();
int lastHeaderId = 0;
for (int i = 0; i < size; i++) {
header = i % Math.round(size / headers) == 0 ? newHeaderHolder(++lastHeaderId) : header;
mItems.add(newItemHolder(i + 1, header));
}
}
private HeaderHolder newHeaderHolder(int i) {
HeaderModel model = new HeaderModel("H" + i);
model.setTitle("Header " + i);
return new HeaderHolder(model);
}
private ItemHolder newItemHolder(int i, HeaderHolder header) {
ItemModel model = new ItemModel("I" + i);
model.setTitle("Holder Item " + i);
model.setSubtitle("Subtitle " + i);
return new ItemHolder(model, header);
}
Above code only loads the data from looping model item.
I could apply with JSON API such as:
How to change code like:
/* for (int i = 0; i < size; i++) {
header = i % Math.round(size / headers) == 0 ? newHeaderHolder(++lastHeaderId) : header;
mItems.add(newItemHolder(i + 1, header));
}*/
Like this:
listArrayFromJSON = getArrayJSON(); //get JSON with GSON request
mItems.addAll(ListArrayFromJSON,header); //not add`
I dont know your json string structure but, you can update question or inspire from below
public class DataHolder{
private ArrayList<ItemHolder> items; //json object name
private ArrayList<HeaderHolder> headers; //json object name
public Arraylist<ItemHolder> getItems(){
return items;
}
public Arraylist<HeaderHolder> getHeaders(){
return items;
}
}
DataHolder holder = new Gson().fromJson(jsonString, DataHolder.class);
mItems.addAll(holder.getItems());
mHeaders.addAll(holder.getHeaders());
Related
I'm studying java, and I'm trying to paginate a list of objects, is it possible using only java?
public class Produto {
public static List<Produto> estoque = new ArrayList<>();
private String nome;
private Double preco;
private int quantidade;
I'm using this toString()
#Override
public String toString() {
return "\nProduto: " + nome + ", preco: R$"
+ preco + ", quantidade: " + quantidade;
}
I got this pagination to work:
public static <Produto> List<Produto> getPageProduct(List<Produto> produtos, int page, int pageSize) {
if(pageSize <= 0 || page <= 0) {
throw new IllegalArgumentException("invalid page size: " + pageSize);
}
int fromIndex = (page - 1) * pageSize;
if(produtos == null || produtos.size() <= fromIndex){
return Collections.emptyList();
}
return produtos.subList(fromIndex, Math.min(fromIndex + pageSize, produtos.size()));
}
But I cant get around having to input manually the number of the page
System.out.println(getPageProduct(getProducts(), 1, 5));
Thread.sleep(3000);
What would be the best solution?
You can calculate the number of pages based on the size of the List and the page size.
final int pageSize = 5;
final int pages = (getProducts().size() + pageSize - 1) / pageSize;
for (int i = 1; i <= pages; i++) {
System.out.println(getPageProduct(getProducts(), i, pageSize));
}
Can anyone help me to correct the /* ... */ code i.e. the function static void display so as to get the passed arraylist as parameter and display it accordingly there, which I am getting error everytime. Please help me I am a novice in java program using util class
import java.util.ArrayList;
public class test1{
static void display(ArrayList<Row> arrayList1)
{
ArrayList<Row> arrayList1 = new ArrayList<>();
Row row;
row = new Row(111,711,1110,111);
// rows.add(row);
arrayList1.add(row);
System.out.println(arrayList1); // passing the arraylist values and adding the element
// Show the Array
System.out.println("u\t v\t t\t lamda");
System.out.println("------------------------------");
for (Row printRow : rows)
{
System.out.println(
printRow.getu() + "\t " +
printRow.getv() + "\t" +
printRow.gett() + "\t" +
printRow.getlamda());
}
*/
}
public static void main(String[] args)
{
ArrayList<Row> rows = new ArrayList<>();
Row row;
row = new Row(4,7,5,1);
rows.add(row);
row = new Row(3,6,6,1);
rows.add(row);
row = new Row(5,9,6,1);
rows.add(row);
row = new Row(6,7,7,1);
rows.add(row);
row = new Row(6,9,7,1);
rows.add(row);
row = new Row(7,10,8,1);
rows.add(row);
row = new Row(7,10,9,1);
rows.add(row);
row = new Row(1,7,10,1);
rows.add(row);
// Show the Array
System.out.println("u\t v\t t\t lamda");
System.out.println("------------------------------");
for (Row printRow : rows)
{
System.out.println(
printRow.getu() + "\t " +
printRow.getv() + "\t" +
printRow.gett() + "\t" +
printRow.getlamda());
}
display(rows);
}/*
}
class Row
{
private final int u;
private final int v;
private final int t;
private final int lamda;
public Row(int u, int v, int t, int lamda)
{
this.u = u;
this.v = v;
this.t = t;
this.lamda = lamda;
}
public int getu()
{
return u;
}
public int getv()
{
return v;
}
public int gett()
{
return t;
}
public int getlamda()
{
return lamda;
}
}
Your arrayList1 is getting passed as an argument, so as mentioned in the comments, you shouldn't be redeclaring or reinitializing it. You also loop through rows which you haven't defined, instead of looping through arrayList1.
static void display(ArrayList<Row> arrayList1) {
Row row;
row = new Row(111,711,1110,111);
arrayList1.add(row);
System.out.println(arrayList1); // passing the arraylist values and adding
// the element
// Show the Array
System.out.println("u\t v\t t\t lamda");
System.out.println("------------------------------");
for (Row printRow : arrayList1) {
System.out.println(
printRow.getu() + "\t " +
printRow.getv() + "\t" +
printRow.gett() + "\t" +
printRow.getlamda());
}
}
I am trying to understand stacks with Objects, so I typed this out, but the problem is that I am getting this really weird message that I can't make sense of. It says "Exception in thread "main" java.lang.NoSuchMethodError: Stack.push(Ljava/lang/Object;)V
at TestObjectStack.main(TestObjectStack.java:12)". I googled it, but I still can't figure out what I'm doing wrong. I redid the main method header, but that didn't fix it. Does anyone have any suggestions or insight that I am missing? Thanks a lot!:
public class TestObjectStack
{
public static void main(String[] args)
{
Object o;
Stack test = new Stack();
test.push("Fred");
test.push(20);
test.push(new ThingB("Barney", 42));
Stack copy = new Stack(test);
System.out.println("Stack test: " + test);
System.out.println(test.pop());
System.out.println("Stack test: " + test);
System.out.println("Stack copy: " + copy);
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a String");
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a string");
if(test.isEmpty()) System.out.println("empty");
}
}
class ThingB
{
private String _name;
private int _ID;
public ThingB(String name, int ID)
{
_name = name;
_ID = ID;
}
public String toString()
{
return "Thing B - name - " + _name + " ID = " + _ID;
}
}
class Stack
{
private Object[] _store;
private int _top;
private static final int MAXSIZE = 50;
public Stack()
{
_store = new Object[MAXSIZE];
_top = 0;
}
public Stack(Stack other)
{
_store = new Object[other._store.length];
_top = other._top;
for(int i = 0; i < _top; ++i)
{
_store[i] = other._store[i];
}
}
public boolean isEmpty()
{
return (_top == 0);
}
public void push(Object item)
{
if(_top >= _store.length)
{
Object[] temp = new Object[_store.length+ MAXSIZE];
for(int i = 0; i < _top; ++i)
{
temp[i] = _store[i];
}
_store = temp;
}
_store[_top] = item;
++_top;
}
public Object pop()
{
if(_top == 0) return 0;
--_top;
return _store[_top];
}
public String toString()
{
String s = "";
s = s + "--Top--";
for(int i = _top-1; i >= 0; --i)
{
s = s + " " + _store[i];
}
s = s + "--Bottom--";
return s;
}
}
I executed your code in the IDE: IntelliJ IDEA. And I have the following result:
Stack test: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
Thing B - name - Barney ID = 42
Stack test: --Top-- 20 Fred--Bottom--
Stack copy: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
20
Not a String
Fred
String length = 4
empty
Your source code is working fine, maybe you need to adjust your IDE parameters. Try with a simple "Hello World" program.
Best regards,
Alvaro
I have a JSON String structured in the following way and it throws an exception passing it into JSONArray timeJSONArray = new JSONArray(time);
This is the error Value [{"daysByte":158,"from":1020,"to":1260},{"daysByte":96,"from":1020,"to":1320}] at 0 of type org.json.JSONArray cannot be converted to JSONObject This is how I receive the array and I can't change it, so I'm having trouble converting it to a JSON Object instead of a JSON String which is the format it's currently in. What am I doing wrong?
[
[
{
"daysByte":30,
"from":660,
"to":1290
},
{
"daysByte":96,
"from":660,
"to":1320
},
{
"daysByte":128,
"from":1050,
"to":1290
}
],
[
{
"daysByte":252,
"from":690,
"to":840
},
{
"daysByte":252,
"from":1050,
"to":1260
}
]
]
This is the code I am working with. I'm getting the value passed in as a string
public ArrayList<String> getTimeList(String time){
System.out.println("PLACES ACTIVITY " + time);
ArrayList<String> times = new ArrayList<>();
try{
//JSONObject timeJSONObject = new JSONObject(time);
JSONArray timeJSONArray = new JSONArray(time);
ArrayList<LegacyTimeSpan> timeSpanList = new ArrayList<>();
LegacyTimeSpanConverterImpl converter = new LegacyTimeSpanConverterImpl();
for(int i = 0; i < timeJSONArray.length(); i++){
int daysByte = timeJSONArray.getJSONObject(i).getInt("daysByte");
int from = timeJSONArray.getJSONObject(i).getInt("from");
int to = timeJSONArray.getJSONObject(i).getInt("to");
System.out.println("TO " + to);
LegacyTimeSpan timeSpan = new LegacyTimeSpan(daysByte, from, to);
timeSpanList.add(timeSpan);
}
Log.d("Time span list", timeSpanList.toString());
WeekSpan weekSpan = converter.convertToWeekSpan(timeSpanList);
List<DayTimeSpanPair> dayTimeSpanPair = weekSpan.toDayTimeSpanPairs();
for(int i = 0; i< dayTimeSpanPair.size(); i++){
String timeRange = buildTimeString(dayTimeSpanPair.get(i));
times.add(timeRange);
}
} catch(JSONException e){
Log.d("PLACES EXCEPTION JSON",e.getMessage());
}
return times;
}
This Code should work i think as u declare the json Format.
[
[
{
} ,{},{} // Json Object Structure as u defined in you Question
topArray = ],
[
{
},{},{}
]
]
for(JSONArray objArray : topArray){
for(JSONObject eachObject : objArray){
System.out.println(eachObject.get("daysByte"););
System.out.println(eachObject.get("from");
System.out.println(eachObject.get("to");
}
}
Hi following code is working for your json I have tried. It is specific for your json not generic. so if you want you can use it.
try{
JSONArray jsonArray = new JSONArray(data); //insted "Data" pass your json Strint
for(int i=0 ; i<jsonArray.length() ; i++){
JSONArray internalArray = jsonArray.getJSONArray(i);
for(int j = 0 ; j < internalArray.length() ; j++){
JSONObject internalObject = internalArray.getJSONObject(j);
Log.d("data" , internalObject.getString("daysByte"));
Log.d("data" , internalObject.getString("from"));
Log.d("data" , internalObject.getString("to"));
}
}
}catch(Exception e){
Log.d("data" ,"Error");
}
}
You have two arrays, one array within other.
You have to do like this:
for(JSONArray temp: timeJsonArray)
{
// try to convert to json object
}
It is a 2D Array.
System.out.println("days");
String content = new Scanner(new File("C:/day.txt")).useDelimiter("\\Z").next();
Day[][] customDayWrap = new Gson().fromJson(content, Day[][].class);
for (Day[] days : customDayWrap) {
for (Day day : days) {
System.out.println(day.getDaysByte());
System.out.println(day.getFrom());
System.out.println(day.getTo());
}
}
And your Day Class will be something like this.
public class Day {
#SerializedName("daysByte")
#Expose
private Integer daysByte;
#SerializedName("from")
#Expose
private Integer from;
#SerializedName("to")
#Expose
private Integer to;
/**
*
* #return
* The daysByte
*/
public Integer getDaysByte() {
return daysByte;
}
/**
*
* #param daysByte
* The daysByte
*/
public void setDaysByte(Integer daysByte) {
this.daysByte = daysByte;
}
/**
*
* #return
* The from
*/
public Integer getFrom() {
return from;
}
/**
*
* #param from
* The from
*/
public void setFrom(Integer from) {
this.from = from;
}
/**
*
* #return
* The to
*/
public Integer getTo() {
return to;
}
/**
*
* #param to
* The to
*/
public void setTo(Integer to) {
this.to = to;
}
}
I tested this (I am using Google GSON library), and I was able to successfully read it.
Basically, there are two JSON arrays but you are accessing only one arrays that is why that error is shown
try {
JSONArray jsonArray = new JSONArray(a);
for (int j=0;j<jsonArray.length();j++) {
JSONArray timeJSONArray = jsonArray.getJSONArray(j);
for(int i = 0; i < timeJSONArray.length(); i++){
int daysByte = timeJSONArray.getJSONObject(i).getInt("daysByte");
int from = timeJSONArray.getJSONObject(i).getInt("from");
int to = timeJSONArray.getJSONObject(i).getInt("to");
System.out.println("TO " + to);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
After 1 hour of debugging your Json array I finally managed to figure out your actual issue. Its not only a Json Array its array inside the array.
So loop like this,
for (int i = 0; i < timeJSONArray.length(); i++) {
for(int j= 0;j<i;j++) {
int daysByte = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("daysByte");
int from = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("from");
int to = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("to");
Log.d("dataRecieved", "daybyte " + daysByte + "from " + from + "to " + to);
}
}
And do others as you need.
I have created a class Hotel defined as follows:
import java.util.Random;
public class Hotel {
private Osoba[] tab = new Osoba[100];
public void zamelduj(Osoba os, int num) {
if (tab[num - 1] == null) {
System.out.println("Pokoj o numerze " + num + "jest zajety");
return;
}
tab[num - 1] = os;
}
public void wymelduj(int num) {
tab[num - 1] = null;
}
public void zamienOsoby(int num1, int num2) {
Osoba o = tab[num1 - 1];
tab[num1 - 1] = tab[num2 - 1];
tab[num2 - 1] = o;
}
public void znajdzWolnePokoje() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println(i + 1);
}
}
public void przydzielPokoje50() {
for (int i = 0; i < 50; i++) {
Random r = new Random();
Osoba o = new Osoba();
int num = r.nextInt(100);
tab[num] = o;
}
}
public void wypisz() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println("Pokoj nr. " + (i + 1) + " jest wolny");
else System.out.println("Pokoj nr. " + i + " jest zajety przez " + tab[i].imie + " " + tab[i].nazwisko);
}
}
public static void main(String[] args) {
Hotel h = new Hotel();
//h.przydzielPokoje50();
//h.wypisz();
h.zamelduj(null, 30);
}
}
I also have a class Osoba:
public class Osoba {
public String imie;
public String nazwisko;
Osoba() {
imie = null;
nazwisko = null;
}
Osoba(String imie, String nazwisko) {
this.imie = imie;
this.nazwisko = nazwisko;
}
}
I want to execute the method Zamelduj, which will assign a person (Osoba) to a cell in a table. However, every time I insert something other than null in the following it says that the first argument is not a capable parameter of the method.
h.zamelduj(null, 30);
What am I doing wrong?
I think your problem is that on the line " h.zamelduj(null, 30);" you need to create a new Osoba:
h.zamelduj(new Osoba("o.o", "._.!"), 30);
what happens is that the function is expecting a Osoba, if you give it another thing, it refuses. i hope it helps
You need to create an object of the class hotel (in your class from where you want to call the method type):
Hotel myObjectHotel = new Hotel();
And then you can call the method trough:
myHotelObject. zamelduj(give parameters here);
:)
Update:
Missed the real question. Just focused on the topic. I'm sorry. ;)