I have this json string to parse {"uid":8,"totalPoints":"7740"}
I have written the below class for this.
public class Points extends WebRequest implements IWebRequest {
private static final String CLASS_TAG = Points.class.getSimpleName();
private WebAPIResponse mWebAPIResponse;
private int mUserId;
/**
* Initialize object
* #param urlEndPoint
* #param uiDelegate
* #param appContext
* #param webServiceRequestCallback
*/
public Points(String urlEndPoint, IUIDelegate uiDelegate,
WeakReference<Context> appContext,
IWebServiceRequestCallback webServiceRequestCallback) {
super(urlEndPoint, uiDelegate, appContext, webServiceRequestCallback);
}
#Override
public String parseResponse(String responseString) {
if (MBUtil.isEmpty(responseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
WebAPIResponse webAPIResponse = objectMapper.readValue(responseString, WebAPIResponse.class);
this.mWebAPIResponse = webAPIResponse;
Errors errors = webAPIResponse.getErrors();
if (errors != null) {
errMsg = errors.getMsg();
}
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}
#Override
public JSONObject buildRequestBody() {
JSONObject jsonObject = new JSONObject();
Context context = getAppContext();
if(context == null) {
return jsonObject;
}
try {
// Authentication body parameters
JSONObject authenticationJsonObject = new JSONObject();
authenticationJsonObject.put(context.getString(R.string.key_points_uid), mUserId);
return authenticationJsonObject;
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
}
return jsonObject;
}
public int getUserId() {
return mUserId;
}
public void setUserId(int mUserId) {
this.mUserId = mUserId;
}
public WebAPIResponse getWebAPIResponse() {
return mWebAPIResponse;
}
public void setWebAPIResponse(WebAPIResponse mWebAPIResponse) {
this.mWebAPIResponse = mWebAPIResponse;
}
public static class WebAPIResponse {
private Data pointsData;
private Errors errors;
public Data getPointsData() {
return pointsData;
}
public void setPointsData(Data pointsData) {
this.pointsData = pointsData;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
}
public static class Data {
#JsonProperty("uid")
private int uid;
#JsonProperty("totalPoints")
private int totalPoints;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getTotalPoints() {
return totalPoints;
}
public void setTotalPoints(int totalPoints) {
this.totalPoints = totalPoints;
}
}
}
I getting proper response in parseResponse() method which is,
responseString = {"uid":8,"totalPoints":"7740"}
But in the same pasreResponse() method once it reached to this line
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
WebAPIResponse webAPIResponse = objectMapper.readValue(responseString, WebAPIResponse.class);
Not responding any thing and unable to parse the string. Please anyone check whether my parsing class is correct or not and why it is not parsing.
With your responseString = {"uid":8,"totalPoints":"7740"} you just can deserialize it by Data object only.
Data data = objectMapper.readValue(responseString, Data.class);
If you want to deserialize your JSON String to WebAPIResponse object, your responseString must be:
{"pointsData":{"uid":8,"totalPoints":"7740"}, "errors": ...}
Related
I am trying to implement transformation logic using flatmap on 7gb input json file.
following code snippet throws
Cannot resolve method 'flatMap(anonymous org.apache.spark.api.java.function.FlatMapFunction<org.apache.spark.sql.Row,com.test.mapper.ProductType>)'
any suggestions please.
dataset is a Dataset<Row> of input json file.
dataset.flatMap(new FlatMapFunction<Row, ProductType>() {
private static final long serialVersionUID = -432662341173300339L;
#Override
public Iterator<ProductType> call(Row row) throws Exception {
List<ProductType> productTypeList = new ArrayList<>();
GenericRowWithSchema dep = row.getAs("dep");
GenericRowWithSchema identity = Util.getRow(dep, "identity");
String dt= Util.getValue(dep, "startDate");
String flg = Util.getValue(dep, "withdrawalPenalty");
return productTypeList.iterator();
}
});
public class ProductType implements Serializable {
String id;
String domain;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}
class Util{
public static GenericRowWithSchema getRow(GenericRowWithSchema row, String fieldName) {
try {
return row.getAs(fieldName);
} catch(Exception ex) {
return null;
}
}
public static String getValue(Row row, String fieldName) {
try {
return row.getAs(fieldName);
} catch(Exception ex) {
return "";
}
}
}
I'm very new in Android and Java Programming and currently developing my skill.
now, i faced a problem with accessing Arraylist from JSONresponse.
It's just i don't know how to initiate my Variable based on Json nested object, and access it without setting it to recylerview etc.
so this is the JSON
{"kode":1,
"pesan":"Anda Berhasil Login",
"data":[{"Id_Ortu":"1","NamaLengkapOrtu":"Alpiyan
Yamin"}]}
ResponseModel class
public class ResponseModel {
private int kode;
private String pesan,sql;
private List<DataModel> data;
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public int getKode() {
return kode;
}
public void setKode(int kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<DataModel> getData() {
return data;
}
public void setData(List<DataModel> data) {
this.data = data;
}
}
ResponseModel class
public class DataModel {
private int Id_Perizinan, Id_Ortu;
private String NamaLengkapSantri, NamaLengkapOrtu, Alasan_Izin, Tgl_Pengajuan,
Durasi_Izin, Tgl_Kembali;
public int getId_Perizinan() {
return Id_Perizinan;
}
public void setId_Perizinan(int id_Perizinan) {
Id_Perizinan = id_Perizinan;
}
public int getId_Ortu() {
return Id_Ortu;
}
public void setId_Ortu(int id_Ortu) {
Id_Ortu = id_Ortu;
}
public String getNamaLengkapSantri() {
return NamaLengkapSantri;
}
public void setNamaLengkapSantri(String namaLengkapSantri) {
NamaLengkapSantri = namaLengkapSantri;
}
public String getNamaLengkapOrtu() {
return NamaLengkapOrtu;
}
public void setNamaLengkapOrtu(String namaLengkapOrtu) {
NamaLengkapOrtu = namaLengkapOrtu;
}
public String getAlasan_Izin() {
return Alasan_Izin;
}
public void setAlasan_Izin(String alasan_Izin) {
Alasan_Izin = alasan_Izin;
}
public String getTgl_Pengajuan() {
return Tgl_Pengajuan;
}
public void setTgl_Pengajuan(String tgl_Pengajuan) {
Tgl_Pengajuan = tgl_Pengajuan;
}
public String getDurasi_Izin() {
return Durasi_Izin;
}
public void setDurasi_Izin(String durasi_Izin) {
Durasi_Izin = durasi_Izin;
}
public String getTgl_Kembali() {
return Tgl_Kembali;
}
public void setTgl_Kembali(String tgl_Kembali) {
Tgl_Kembali = tgl_Kembali;
}
and this is how I try to retrieve the data
public void loginAplikasi(){
APIRequestData apiRequestData = RetroServer.koneksiRetrofit().create(APIRequestData.class);
Call<ResponseModel> loginApp = apiRequestData.ardLogin(username,password);
loginApp.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
listData = response.body().getData();
int Id_Ortu = 0;
String NamaLengkapOrtu;
alertDialog(NamaLengkapOrtu);
} else {
alertDialog(pesan);
}
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
alertDialog(t.getMessage());
}
});
}
i successfully catched 'kode' and 'pesan' From JSON by using
int kode = response.body().getKode();
String pesan = response.body().getPesan();
i've declared a listData as new arraylist
List<DataModel> listData = new ArrayList<>();
however, how can i access the value of
listData = response.body().getData();
which contained array inside of data
so i can initiate variable ( NamaLengkapOrtu = listdata(arrayIndex) )
Thanks in advance.
The issue with DataModel class.
public class DataModel {
#SerializedName("Id_Ortu")
#Expose
private String idOrtu;
#SerializedName("NamaLengkapOrtu")
#Expose
private String namaLengkapOrtu;
public String getIdOrtu() {
return idOrtu;
}
public void setIdOrtu(String idOrtu) {
this.idOrtu = idOrtu;
}
public String getNamaLengkapOrtu() {
return namaLengkapOrtu;
}
public void setNamaLengkapOrtu(String namaLengkapOrtu) {
this.namaLengkapOrtu = namaLengkapOrtu;
}
}
Then you can access data as follows:
String namaLengkapOrtu = listdata.get(index).getNamaLengkapOrtu();
String idOrtu = listdata.get(index).getIdOrtu();
As your JSON response is:
{"kode":1,
"pesan":"Anda Berhasil Login",
"data":[{"Id_Ortu":"1","NamaLengkapOrtu":"Alpiyan
Yamin"}]}
Use the below annotation in your model class:
#SerializedName("data")
#Expose
Here, "data" is the key you want to get from JSON.
Try to use this ResponseModel class:
public class ResponseModel {
private int kode;
private String pesan,SQL;
#SerializedName("data")
#Expose
private List<DataModel> data;
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public int getKode() {
return kode;
}
public void setKode(int kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<DataModel> getData() {
return data;
}
public void setData(List<DataModel> data) {
this.data = data;
}
}
I am calling Restful service using below code :(Java.net implementation )
StringBuilder responseStrBuilder = new StringBuilder();
try
{
URL url = new URL(restUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(httpRequestMethod);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Content-Type", "application/json");
if (requestHeaders != null)
{
for (Map.Entry<String, String> entry : requestHeaders.entrySet())
{
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(urlParameters.getBytes());
os.flush();
os.close();
if (conn.getResponseCode() != 200) {//do something}
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
while ((output = br.readLine()) != null)
responseStrBuilder.append(output);
Approach 1:
I have below string(JSON String) as my Restful service response , how can I convert it to Java object. Since same(Itm) object is repeated multiple times if I use org.codehaus.jettison.json.JSONObject myObject = new org.codehaus.jettison.json.JSONObject(responseStrBuilder.toString());
It only reads first Itm Object and does not bring list of all item object.
JSON String output from service :
{"Response":{"RID":"04'34'",
"Itm":{"id":{"ab":"1","cd":"12"},"qw":"JK","name":"abcd "},
"Itm":{"id":{"ab":"2","cd":"34},"qw":"JK","name":"asdf "},
"Itm":{"id":{"ab":"3","cd":"12"},"qw":"JK","name":"fghj "}
}}
Approach 2:
I also tried below snippet with correct Java object with setters and getters
ObjectMapper objectMapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyJavaReponseObject javaObj = mapper.readValue(json, MyJavaReponseObject.class);
This approach also reads only one object of Itm and not all the object as its not coming in array format in JSON string. Is there any better way of getting all the object(Itm) mapped to single List of Object in java pojo ?
You can use the List class in your response object, if you should parse that json string itself.
I have a ReponseJSON class with json objects, one Response and three Itms
static class ReponseJSON {
private Response Response;
#JsonProperty("Response")
public Response getResponse() {
return Response;
}
public void setResponse(Response Response) {
this.Response = Response;
}
static class Response {
private String rid;
private Itm Itm;
private List<Itm> listItm = new ArrayList<Itm>();
public Itm getItm() {
return Itm;
}
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
public String getRID() {
return rid;
}
public List<Itm> getItms() {
return listItm;
}
#JsonProperty("RID")
public void setRID(String rid) {
this.rid = rid;
}
static class Itm {
private Id id;
private String qw, name;
public String getQw() {
return qw;
}
public void setQw(String qw) {
this.qw = qw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Id getId() {
return id;
}
public void setId(Id id) {
this.id = id;
}
static class Id {
private String ab, cd;
public String getCd() {
return cd;
}
public void setCd(String cd) {
this.cd = cd;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
}
}
}
}
In a Response class, I have a list class and save a Itm object whenever object mapper call this class.
static class Response {
... skip ..
private List<Itm> listItm = new ArrayList<Itm>();
... skip ..
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
}
Check the full source code as follows.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonParserTest {
static class ReponseJSON {
private Response Response;
#JsonProperty("Response")
public Response getResponse() {
return Response;
}
public void setResponse(Response Response) {
this.Response = Response;
}
static class Response {
private String rid;
private Itm Itm;
private List<Itm> listItm = new ArrayList<Itm>();
public Itm getItm() {
return Itm;
}
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
public String getRID() {
return rid;
}
public List<Itm> getItms() {
return listItm;
}
#JsonProperty("RID")
public void setRID(String rid) {
this.rid = rid;
}
static class Itm {
private Id id;
private String qw, name;
public String getQw() {
return qw;
}
public void setQw(String qw) {
this.qw = qw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Id getId() {
return id;
}
public void setId(Id id) {
this.id = id;
}
static class Id {
private String ab, cd;
public String getCd() {
return cd;
}
public void setCd(String cd) {
this.cd = cd;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
}
}
}
}
public static void main(String[] args) {
String responseJson =
"{\"Response\":{\"RID\":\"04'34'\","
+ "\"Itm\":{\"id\":{\"ab\":\"1\",\"cd\":\"12\"},\"qw\":\"JK\",\"name\":\"abcd\"}"
+ ",\"Itm\":{\"id\":{\"ab\":\"2\",\"cd\":\"34\"},\"qw\":\"JK\",\"name\":\"asdf\"}"
+ ",\"Itm\":{\"id\":{\"ab\":\"3\",\"cd\":\"12\"},\"qw\":\"JK\",\"name\":\"fghj\"}"
+ "}} ";
ObjectMapper mapper = new ObjectMapper();
ReponseJSON responseObj = null;
try {
responseObj = mapper.readValue(responseJson, ReponseJSON.class);
ReponseJSON.Response response = responseObj.getResponse();
for(int i = 0; i < response.getItms().size(); i++)
{
ReponseJSON.Response.Itm item = response.getItms().get(i);
System.out.println(item.getId().getAb());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The version of my jackson mapper is 2.9.1.
You check the main method of the source, because the JSON string you prepared is invalid as coddemonkey mentioned.
Have a good day.
Make your json response looks something similar to this
{"Response":{"RID":"04'34'",
"Itms":[{"id":{"ab":"1","cd":"12"},"qw":"JK","name":"abcd "},
{"id":{"ab":"2","cd":"34"},"qw":"JK","name":"asdf "},
{"id":{"ab":"3","cd":"12"},"qw":"JK","name":"fghj "}]
}}
then, use org.json jar to parse the string to jsonObject
JSONObject jsonObject=new JSONObject(responseString);
This is one type of solution, if you can't change the response as mentioned above then you have to manually parse the string(using java bean) there is no other option available.
Here is the intentservice where I get error in logout
public class intentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
RequestQueue queue = MyVolley.getRequestQueue(this);
queue = MyVolley.getRequestQueue(this);
GsonRequest<Routes> gsonRequest = new GsonRequest<Routes>(
url_routes + key, Routes.class, null, createMyReqSuccessListenerRoutes(key),
createMyReqErrorListenerRoutes());
queue.add(gsonRequest);
Function for receive in intentservice
private Response.Listener<Routes> createMyReqSuccessListenerRoutes(final int key) {
return new Response.Listener<Routes>() {
#SuppressLint("LongLogTag")
#Override
public void onResponse(Routes response) {
if (ds.checkTable(DataBaseHelper.TABLE_NAME_TRANSPORT)) {
ds.createTableRoute();
final int size = response.getResults().size();
if (size > 0) {
final int part = 100 / size;
int i;
for (i = 0; i < size; i++) {
ds.insertRoutes(DataBaseHelper.TABLE_NAME_ROUTE,
response.getResults().get(i).getRoute(),
response.getResults().get(i).getStop_id(),
response.getResults().get(i).getNum(),
response.getResults().get(i).getLat(),
response.getResults().get(i).getLon(),
response.getResults().get(i).getRadius(),
response.getResults().get(i).getAudio(),
response.getResults().get(i).getEnd(),
response.getResults().get(i).getMove_time(),
response.getResults().get(i).getStop_time(),
response.getResults().get(i).getPlayonce(),
response.getResults().get(i).getName(),
key
);
}
}
}
}
}
}
Call it from another activity
serviceintentRoute = new Intent(DataBase.this, intentService.class);
startService(serviceintentRoute.putExtra("key", idp));
My RouteData class
public class RoutesData {
private Integer route;
private Integer stop_id;
private Integer num;
private String name;
private String lat;
private String lon;
private Integer radius;
private String audio;
private Integer stop_time;
private Integer move_time;
private Integer end;
private Integer trid;
public RoutesData() {
}
public Integer getRoute() {
return route;
}
public void setRoute(Integer route) {
this.route = route;
}
public Integer getStop_id() {
return stop_id;
}
public void setStop_id(Integer stop_id) {
this.stop_id = stop_id;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getRadius() {
return radius;
}
public void setRadius(Integer radius) {
this.radius = radius;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getTrid() {
return trid;
}
public void setTrid(Integer trid) {
this.trid = trid;
}
public Integer getStop_time() {
return stop_time;
}
public void setStop_time(Integer stop_time) {
this.stop_time = stop_time;
}
public Integer getMove_time() {
return move_time;
}
public void setMove_time(Integer move_time) {
this.move_time = move_time;
}
}
And Routes
public class Routes {
public ArrayList<RoutesData> data;
public Routes(ArrayList<RoutesData> data) {
this.data = data;
}
#Override
public String toString() {
return "Response [results=" + data + "]";
}
public ArrayList<RoutesData> getResults() {
return data;
}
}
Class MyVolley
public class MyVolley {
private static RequestQueue mRequestQueue;
private Context context;
public MyVolley() {
}
static void init(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
// Use 1/8th of the available memory for this memory cache.
int cacheSize = 1024 * 1024 * memClass / 8;
// mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
}
public static RequestQueue getRequestQueue(Context mContext) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mContext);
}
return mRequestQueue;
}
}
class gsonrequest
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.d("Response.success", json.toString());
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
I don`t know how to receive all data
Logcat output in Android Studio
The logout
D/Response.success: {"status":true,"data"
:[{"route":1,"num":1,"stop_id":30,"name":"\u043f\u043b.......etc..
not full the line, the next line I had the error
D/ERRORĀ RESPONSE: ERROR RESPONSE Routes
If I understand right the memory is not enough for all array of json massive
I had tried to increase it via
int cacheSize = 2048 * 2048 * memClass / 8;
but not luck
I had to receive all massive not devided it
Sorry for my formatted code
I am entering the objects in the list and noticed that the last added this overriding all others on the list, the following code snippets.
private List<NoticiaListView> getNoticias() {
try {
List<Noticia> lNoticiaParseObject = null;
List<NoticiaListView> lNoticiaListView = new ArrayList<NoticiaListView>();
NoticiaListView nListView = new NoticiaListView();
ParseQuery<Noticia> query = ParseQuery.getQuery(Noticia.class);
query.whereEqualTo("ativo", true);
query.include("imagem");
lNoticiaParseObject = query.fromLocalDatastore().find();
if (!lNoticiaParseObject.isEmpty()) {
for (Noticia noticia : lNoticiaParseObject) {
nListView.setImagem(noticia.getImagemByteArray((Midia) noticia.getParseObject("imagem")));
nListView.setTitulo(noticia.getTitulo());
nListView.setConteudo(noticia.getConteudo());
nListView.setLink(noticia.getLink());
nListView.setCreatedAt(noticia.getCreatedAt().getTime());
lNoticiaListView.add(nListView);
}
return lNoticiaListView;
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
classe NoticiaListView:
public class NoticiaListView {
private String titulo;
private String conteudo;
private String link;
private long createdAt;
private byte[] imagemBytes;
public NoticiaListView() {
/*this.titulo = titulo;
this.conteudo = conteudo;
this.link = link;
this.createdAt = createdAt;
this.imagemBytes = imagemBytes;*/
}
//region GETTERS
public String getTitulo() {
return titulo;
}
public String getConteudo() {
return conteudo;
}
public String getLink() {
return link;
}
public long getCreatedAt() {
return createdAt;
}
public byte[] getImagem() {
return imagemBytes;
}
//endregion
//region SETTERS
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setConteudo(String conteudo) {
this.conteudo = conteudo;
}
public void setLink(String link) {
this.link = link;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
public void setImagem(byte[] imagem) {
this.imagemBytes = imagem;
}
//endregion
}
Class Noticia:
public class Noticia extends ParseObject {
public Noticia() {
/*deixar vazio*/
}
//region GETTERS
public ParseACL getParseACL(){
return getParseACL();
}
/*public String getObjectId() {
return getObjectId();
}*/
/*public Date getCreatedAt() {
return getCreatedAt();
}*/
/* public Date getUpdatedAt() {
return getUpdatedAt();
}*/
public boolean isAtivo() {
return getBoolean("ativo");
}
public String getConteudo() {
return getString("conteudo");
}
public String getLink() {
return getString("link");
}
public String getTitulo() {
return getString("titulo");
}
public byte[] getImagemByteArray(Midia midia) {
byte[] imageData = new byte[0];
try {
imageData = midia.getParseFile("arquivo").getData();
} catch (ParseException e) {
e.printStackTrace();
}
return imageData;
}
//endregion
//region SETTERS
public void setACL(ParseACL acl){
put("ACL", acl);
}
public void setCreatedAt(Date createdAt) {
put("createdAt", createdAt);
}
public void setUpdatedAt(Date updatedAt) {
put("updatedAt", updatedAt);
}
public void setAtivo(boolean ativo) {
put("ativo", ativo);
}
public void setConteudo(String conteudo) {
put("conteudo", conteudo);
}
public void setLink(String link) {
put("link", link);
}
public void setTitulo(String titulo) {
put("titulo", titulo);
}
public void setImagem(ParseRelation<Midia> imagem) {
put("imagem", imagem);
}
//endregion
}
How to solve this problem by using lists? I hope not need to change for collections only for one reason thereof. I read another question that the possible problem could be "static fields", but in my code does not have any static field.
please change your code as below. because you have just created object one time and It should be create multiple times depend on your list size. you should create object in for loop.
private List<NoticiaListView> getNoticias() {
try {
List<Noticia> lNoticiaParseObject = null;
List<NoticiaListView> lNoticiaListView = new ArrayList<NoticiaListView>();
ParseQuery<Noticia> query = ParseQuery.getQuery(Noticia.class);
query.whereEqualTo("ativo", true);
query.include("imagem");
lNoticiaParseObject = query.fromLocalDatastore().find();
if (!lNoticiaParseObject.isEmpty()) {
for (Noticia noticia : lNoticiaParseObject) {
NoticiaListView nListView = new NoticiaListView();/// change here.
nListView.setImagem(noticia.getImagemByteArray((Midia) noticia.getParseObject("imagem")));
nListView.setTitulo(noticia.getTitulo());
nListView.setConteudo(noticia.getConteudo());
nListView.setLink(noticia.getLink());
nListView.setCreatedAt(noticia.getCreatedAt().getTime());
lNoticiaListView.add(nListView);
}
return lNoticiaListView;
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Android: last object added to the list overrides all others
Create nListView object of NoticiaListView class inside for-each loop to add new object in ArrayList:
for (Noticia noticia : lNoticiaParseObject) {
// create object here
NoticiaListView nListView = new NoticiaListView();
// ... your code here..
lNoticiaListView.add(nListView);
}
Re initialize the object nListView
for (Noticia noticia : lNoticiaParseObject) {
nListView.setImagem(noticia.getImagemByteArray((Midia) noticia.getParseObject("imagem")));
nListView.setTitulo(noticia.getTitulo());
nListView.setConteudo(noticia.getConteudo());
nListView.setLink(noticia.getLink());
nListView.setCreatedAt(noticia.getCreatedAt().getTime());
lNoticiaListView.add(nListView);
nListView = new NoticiaListView();
}
Hope this will help you..