Json text to RecyclerView in Android - java

I need help with my RecyclerView. I have a atring array from my SQL Database which looks like this:
{"success":true,"0":{"order_number":"078","typ_first":"E3rft","typ_last":"Split","order_date_time":"2016-10-11 19:20:03"},"1":{"order_number":"166","typ_first":"E483f","typ_last":"Split_test","order_date_time":"2016-10-12 18:39:30"}}
In my RecyclerView I have the following fields:
order_number
typ_all (type first and last)
date(only a date without time)
This is how I get my string array:
String plansData = plansPreferenceData.getString("plansPreferenceData", "");
This is how I set the data to my RecyclerView:
// Set plan data
Plans plan = new Plans("123", "E3rft Split", "11.10.2016");
// Add Object to list
planList.add(plan);
// Notify data changes
pAdapter.notifyDataSetChanged();
My Plans class:
public class Plans {
private String planTitle, planType, planDate;
public Plans(String planTitle, String planType, String planDate) {
this.planTitle = planTitle;
this.planType = planType;
this.planDate = planDate;
}
public void setPlanTitle(String planTitle) {
this.planTitle = planTitle;
}
public String getPlanTitle() {
return planTitle;
}
public void setPlanType(String planType) {
this.planType = planType;
}
public String getPlanType() {
return planType;
}
public void setPlanDate(String planDate) {
this.planDate = planDate;
}
public String getPlanDate() {
return planDate;
}
}
My onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_training, container, false);
preparePlansData();
return view;
}
My preparePlansData():
private void preparePlansData() {
// Set plan data
Plans plan = new Plans("123", "fkfjfjeje", "21.04.1977");
// Add Object to list
planList.add(plan);
plan = new Plans("test", "tttt", "22.01.2017");
planList.add(plan);
// Notify data changes
pAdapter.notifyDataSetChanged();
}
My question is how can I get the information out of the string array into my adapter? I also need to format the date before adding. Thanks for your help!

read about Gson here:
http://guides.codepath.com/android/leveraging-the-gson-library
After that you will be able to write code like that:
Type type = new TypeToken<Map<Integer, Plans>>(){}.getType();
Map<Integer, Plans> myMap = gson.fromJson("your json from db", type);
and use this map.values() in your adapter
your Plans class should look like this:
class Plans {
String order_number;
String typ_first;
String typ_last;
String order_date_time;
}
If you want another field names you have to use #SerializedName annotation
Finally, you should write something like that, (I do not know if syntax is 100% do not have IDE open now) :
private void preparePlansData() {
String plansData = plansPreferenceData.getString("plansPreferenceData", "");
Type type = new TypeToken<Map<Integer, Plans>>(){}.getType();
Map<Integer, Plans> myMap = gson.fromJson(plansData, type);
planList.addAll(myMap.values());
// Notify data changes
pAdapter.notifyDataSetChanged();
}
and modify your model class:
public class Plans {
#SerializedName("order_number")
String planTitle;
#SerializedName("typ_last")
String planType;
#SerializedName("order_date_time")
String planDate;
....
I hope it will help you.

Check this code (you can remove #Test annotation):
class Plans {
String typ_firstString;
String typ_last;
String order_date_time;
public Plans(String typ_firstString, String typ_last, String order_date_time) {
this.typ_firstString = typ_firstString;
this.typ_last = typ_last;
this.order_date_time = order_date_time;
}
}
class PlansResponse {
boolean status;
List<Plans> plans;
}
#Test
public void testPlacesResponseDeserializer() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(PlansResponse.class, new PlansResponseDeserializer())
.create();
String jsonString = "{\"success\":true,\"0\":{\"order_number\":\"078\",\"typ_first\":\"E3rft\",\"typ_last\":\"Split\",\"order_date_time\":\"2016-10-11 19:20:03\"},\"1\":{\"order_number\":\"166\",\"typ_first\":\"E483f\",\"typ_last\":\"Split_test\",\"order_date_time\":\"2016-10-12 18:39:30\"}}";
PlansResponse plansResponse = gson.fromJson(jsonString, PlansResponse.class);
assert plansResponse.status == true;
assert plansResponse.plans.size() == 2;
}
class PlansResponseDeserializer implements JsonDeserializer<PlansResponse> {
private String getElementAsString(JsonObject jsonObject, String key) {
JsonElement element = jsonObject.get(key);
return element.getAsString();
}
#Override
public PlansResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
PlansResponse plansResponse = new PlansResponse();
List<Plans> plansList = new ArrayList<>();
Gson gson = new Gson();
Type type = new TypeToken<Map<String, JsonObject>>(){}.getType();
Map<String, JsonElement> map = gson.fromJson(json, type);
for(Map.Entry<String, JsonElement> entry : map.entrySet()) {
String key = entry.getKey();
if("success".equals(key)) {
JsonPrimitive jsonPrimitive = (JsonPrimitive) entry.getValue();
plansResponse.status = jsonPrimitive.getAsBoolean();
continue;
}
JsonObject jsonObject = (JsonObject)entry.getValue();
String typ_firstString = getElementAsString(jsonObject, "typ_first");
String typ_last = getElementAsString(jsonObject, "typ_last");
String order_date_time = getElementAsString(jsonObject, "order_date_time");
plansList.add(new Plans(typ_firstString, typ_last, order_date_time));
}
plansResponse.plans = plansList;
return plansResponse;
}
}

Related

Serialization of an Object having a polymorphic list of different type

I am trying to build a custom App to control Smart Home devices utilizing the Tasmota firmware and MQTT. Primarily that is smart lights at the moment. Therefore I have a Device class with children depending on the type of the device. Each device stores a DeviceState which is updated due to any changes made through the app. So the DeviceState is always the current state of the device. Depending on the device I need different DeviceStates, so again there is one superclass and subclass.
Now i want to store scenes with an ArrayList of DeviceStates to first store and than recreate certain light atmospheres. Therefore there is a class called Scene holding basic information and the described ArrayList.
To Store those lists i am using the Gson library in Android. My question is now how to be able to save those scenes objects with a polymorphic list inside.
I have followed this stackoverflow post: Gson serialize a list of polymorphic objects to save my devices as an Json String using the Gson library and a custom serializer / deserializer. But now Hence DeviceState doesn´t extend Scene I can´t use one serializer to create a String out of the Scene object. And if i would extend DeviceState to Scene, the DeviceState class would declare multiple JSON fields with the same name, because I am using "typeName" to differentiate those classes.
So basically i am getting the errors, that DeviceState doesn´t extend Scene or that DeviceState declares multiple JSON fields named "typeName".
public class Scene{
private ArrayList<DeviceState> states;
private String name;
private String room;
private String typeName;
public ArrayList<Scene> sceneList = new ArrayList<>();
public Scene(){
}
public Scene(String pName, String pRoom) {
name = pName;
room = pRoom;
states = new ArrayList<>();
typeName = "Scene";
}
public String getName() {
return name;
}
public String getRoom() {
return room;
}
public void addDevice(Device d) {
states.add(d.getState());
}
public void execute() {
System.out.println(states.size());
}
public String getTypeName(){
return typeName;
}
}
public class DeviceState {
private String typeName;
private String deviceTopic;
public static final String RGBWLightState = "RGBWLightState";
public static final String Default = "DeviceState";
public DeviceState(String pTypeName, String pDeviceTopic){
typeName = pTypeName;
deviceTopic = pDeviceTopic;
}
public DeviceState(){
typeName = Default;
}
public String getTypeName() {
return typeName;
}
}
public class CustomSceneSerializer implements JsonSerializer<ArrayList<Scene>> {
private static Map<String, Class> map = new TreeMap<>();
static {
map.put(DeviceState.RGBWLightState, RGBWLightState.class);
map.put(DeviceState.Default, DeviceState.class);
map.put("Scene", Scene.class);
}
#Override
public JsonElement serialize(ArrayList<Scene> src, Type typeOfSrc, JsonSerializationContext context) {
if(src == null) {
return null;
}else{
JsonArray ja = new JsonArray();
for(Scene s : src){
Class c = map.get(s.getTypeName());
if(c == null){
throw new RuntimeException("Unkown class: " + s.getTypeName());
}
ja.add(context.serialize(s, c));
}
return ja;
}
}
}
public class CustomSceneDeserializer implements JsonDeserializer<List<Scene>> {
private static Map<String, Class> map = new TreeMap<>();
static {
map.put(DeviceState.RGBWLightState, RGBWLightState.class);
map.put(DeviceState.Default, DeviceState.class);
map.put("Scene", Scene.class);
}
#Override
public List<Scene> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ArrayList list = new ArrayList<Scene>();
JsonArray ja = json.getAsJsonArray();
for (JsonElement je : ja) {
String type = je.getAsJsonObject().get("typeName").getAsString();
Class c = map.get(type);
if (c == null)
throw new RuntimeException("Unknow class: " + type);
list.add(context.deserialize(je, c));
}
return list;
}
}
To save the Object holding a list of those objects I am using:
String json = preferences.getString("scene_holder", "");
GsonBuilder gb = new GsonBuilder();
List<Scene> al = new ArrayList<>();
gb.registerTypeAdapter(al.getClass(), new CustomSceneDeserializer());
gb.registerTypeAdapter(al.getClass(), new CustomSceneSerializer());
Gson gson = gb.create();
System.out.println(list.size());
list.get(0).execute();
System.out.println(json);
if (!(json.equals(""))) {
Scene result = gson.fromJson(json, Scene.class);
System.out.println(result.sceneList.size());
result.sceneList = list;
System.out.println(result.sceneList.size());
editor.putString("scene_holder", gson.toJson(result)).commit();
} else {
Scene scene = new Scene();
scene.sceneList = list;
editor.putString("scene_holder", gson.toJson(scene)).commit();
}

GSON: JSON deserialization to variable type (List/String)

At this point it's already an old question and I've probably read every related topic on SO.
But to the point. I need some advice or correction maybe?
For some reason we have generatable Jsons of 2 types:
{"data": {"id": "value"}} and {"data":[{"id": "value"}]}
Object and Array. There are also other params but they doesn't matter here. "id" is differ for every request. Sometimes it's userId, portfolioId etc. So I get "id" and pass it to related var.
For a long time I was working with the first case. And created POJO like this:
Data.class
public class Data {
#SerializedName("id")
#Expose
private String id;
public Data() {
}
public Data(String id) {
super();
this.id = id;
}
protected String getId() {
return id;
}
And I adress "data" paramets via User.class.
#JsonAdapter(UserDeserializer.class)
public Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public User() {
}
public User(Data data) {
super();
this.data = data;
}
Gson gson = new Gson();
public String getPortfolioList(String tokenId, String userId) {
Call<User> call = apiRequest.getPortfolioList(userId, tokenId);
try {
User newResult = gson.fromJson(String.valueOf(call.execute().body()), User.class);
System.out.println(newResult.getData().getId());
} catch (IOException e) {
e.printStackTrace();
}
return getPortfolioId();
}
Deserializer.class
public class UserDeserializer implements JsonDeserializer<User> {
private Type listType = new TypeToken<List<Data>>(){}.getType();
#Override
public User deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
User user = new User();
JsonElement jsonElement;
if (json.isJsonArray()) {
jsonElement = json.getAsJsonArray();
user.data = context.deserialize(jsonElement,listType);
// user.data = new Gson().fromJson(jsonElement, new TypeToken<List<Data>>() {}.getType());
} else {
jsonElement = json.getAsJsonObject();
user.data = context.deserialize(jsonElement, Data.class);
// user.setData(new Gson().fromJson(jsonElement, new TypeToken<Data>() {}.getType()));
}
return user;
}
}
Gson builder in BaseApi class just in case:
Gson gson = new GsonBuilder().registerTypeAdapter(UserDeserializer.class, new UserDeserializer()).setLenient().create();
Without custom deserialization and Array JSON issue this would work perfectly. But now I have to determine "data" 's exact type I get.
In above case I get java.lang.ClassCastException: java.util.ArrayList cannot be cast to auto.Rest.Data
I assume I have to create another Data class (for example there will be DataObject & DataArray) and describe every parameter as I did before in Data.class to get this work? I think I do something wrong during deserialization but I'm not sure where tbh.
Or am I wrong and it is possible to invoke Data as List and Data as an Object of the same class?
I'm working on this for several days already(?) and was thinking about use generics instead of Gson help, yeah, I'm desperate. So any help appreciated.
if there is always one object, just add
json.getAsJsonArray().get(0);
public class UserDeserializer implements JsonDeserializer<User> {
private Type listType = new TypeToken<List<Data>>(){}.getType();
#Override
public User deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
User user = new User();
JsonElement jsonElement;
if (json.isJsonArray()) {
jsonElement = json.getAsJsonArray().get(0);
user.data = context.deserialize(jsonElement,listType);
// user.data = new Gson().fromJson(jsonElement, new TypeToken<List<Data>>() {}.getType());
} else {
jsonElement = json.getAsJsonObject();
user.data = context.deserialize(jsonElement, Data.class);
// user.setData(new Gson().fromJson(jsonElement, new TypeToken<Data>() {}.getType()));
}
return user;
}
}
if there are more objects, change field data to the list
public class UserDeserializer implements JsonDeserializer<User> {
private Type listType = new TypeToken<List<Data>>(){}.getType();
#Override
public User deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
User user = new User();
JsonElement jsonElement;
if (json.isJsonArray()) {
jsonElement = json.getAsJsonArray();
user.data = context.deserialize(jsonElement,listType);
// user.data = new Gson().fromJson(jsonElement, new TypeToken<List<Data>>() {}.getType());
} else {
jsonElement = json.getAsJsonObject();
List<Data> data = new ArrayList<Data>();
data.add(context.deserialize(jsonElement, Data.class)) ;
user.data = data ;
// user.setData(new Gson().fromJson(jsonElement, new TypeToken<Data>() {}.getType()));
}
return user;
}
}
and change User.class field data to List
public List<Data> data;
this is a similar topic in kotlin language link
If you always have object or one-element array you can write custom deserialiser as below:
class OneOrElementJsonDeserializer<T> implements JsonDeserializer<T> {
#Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json instanceof JsonArray) {
final JsonArray array = (JsonArray) json;
final int size = array.size();
if (size == 0) {
return null;
}
return context.deserialize(array.get(0), typeOfT);
}
return context.deserialize(json, typeOfT);
}
}
Your example model after simplification looks like below:
class User {
#JsonAdapter(OneOrElementJsonDeserializer.class)
private Data data;
public User() {
}
public User(Data data) {
super();
this.data = data;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
#Override
public String toString() {
return "User{" +
"data=" + data +
'}';
}
}
class Data {
private String id;
protected String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return "Data{" +
"id='" + id + '\'' +
'}';
}
}
Example usage:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.JsonAdapter;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
User root = gson.fromJson(new FileReader(jsonFile), User.class);
System.out.println(root);
}
}
Above code for below JSON payload:
{
"data": [
{
"id": "c87ca3fe85781007869b83f"
}
]
}
prints:
User{data=Data{id='c87ca3fe85781007869b83f'}}
And for object case JSON payload:
{
"data": {
"id": "c87ca3fe85781007869b83f"
}
}
prints:
User{data=Data{id='c87ca3fe85781007869b83f'}}
In case your property could contain JSON object or multi-element array see my answer to this question Mapping Json Array to Java Models. There is implemented deserialiser which handle cases like this.

Convert ArrayList of custom objects to JSON

I have an ArrayList of custom Objects. Each of these objects have an arraylist of another custom object. Then these second level of custom objects have an arraylist of another custom object.
This is how the class hierarchy looks like
public class Undle {
private String undleStatus;
private ArrayList<ArcelFolder> arcelFolders;
public ArrayList<ArcelFolder> getArcelFolders() {
return arcelFolders;
}
public void setArcelFolders(ArrayList<ArcelFolder> arcelFolders) {
this.arcelFolders = arcelFolders;
}
//Other getter and setters
}
public class ArcelFolder {
private ArrayList<ArcelDocument> arcelDocuments;
private String arcelStatus;
public String getArcelStatus() {
return arcelStatus;
}
public void setArcelStatus(String arcelStatus) {
this.arcelStatus = arcelStatus;
}
public ArrayList<ArcelDocument> getArcelDocuments() {
return arcelDocuments;
}
public void setArcelDocuments(ArrayList<ArcelDocument> arcelDocuments) {
this.arcelDocuments = arcelDocuments;
}
}
public class ArcelDocument {
private String gain;
public String getGain() {
return gain;
}
public void setGain(String gain) {
this.gain = gain;
}
}
I have an arraylist of Undle objects
ArrayList<Undle> undleList = new ArrayList<Undle>();
// Create objects of ArcelFolder and ArcelDocument
// Add ArcelDocument list to ArcelFolder
// Add ArcelFolder list to Undle arraylist
I would like to convert Undle ArrayList to a JSON. How can I flatten this hierarcical structure of beans and put it in a JSON?
I tried doing something like
org.json.simple.JSONObject resultObj = new JSONObject(undleList);
and
org.json.simple.JSONArray arr = new JSONArray(undleList);
But it seems that they work only if a String ArrayList is passed.
Gson gson = new Gson();
Type type = new TypeToken<List<Bundle>>() {}.getType();
String json = gson.toJson(bundleList, type);
System.out.println(json);
List<Bundle> fromJson = gson.fromJson(json, type);
for (Bundle bundle : fromJson) {
System.out.println(bundle);
}

How to fetch JSONObject’s properties from a nested ArrayList and showing it to ListView?

I have an ArrayList of ‘wholeYearRiskArray’, at each index of ArrayList there is another ArrayList of JSONObjects that contains the per month news/risks. Each index represents one month of news/risks.
I want to show the displaydate and subject properties of each JSONObject in the ListView.
Because each month data is separated by other month data by index.
I want to generate Fragments in ViewPager without any tabs. Each Fragment will hold each data of a month. The Fragments will dynamically generate according to the size of wholeYearRisksArray.
Here is the picture in the debug mode.
http://i.imgur.com/3RvqDMn.png
Here is the picture that i want to implement.
http://i.imgur.com/NQdkUXr.png
Here is my MainActivity.java code.
public class MainActivity extends AppCompatActivity {
public static String TAG = MainActivity.class.getSimpleName();
ArrayList<Risks> risksArrayList = new ArrayList<>();
HashMap<String, String> firstObjectHashMap = new HashMap<>();
HashMap<String, String> lastObjectHashMap = new HashMap<>();
String latestDateStr;
String oldestDateStr;
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime formatedLatestDate;
DateTime formatedOldestDate;
DateTime upDate;
JSONArray filteredJSONArray = new JSONArray();
ArrayList<ArrayList<JSONObject>> wholeYearRiskArray = new ArrayList<>();
Risks risks = new Risks();
private String JsonUrl = "https://api.myjson.com/bins/4goeq"; // https://api.myjson.com/bins/4goeq
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest req = new StringRequest(JsonUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectFromArray = jsonArray.getJSONObject(i);
if (jsonObjectFromArray.getString("publishtype").equals("PUBLISHED")) {
filteredJSONArray.put(jsonObjectFromArray);
risks.setUID(jsonObjectFromArray.getString("UID"));
risks.setSubject(jsonObjectFromArray.getString("subject"));
risks.setArticletext(jsonObjectFromArray.getString("articletext"));
risks.setDisplaydate(jsonObjectFromArray.getString("displaydate"));
risks.setPublishdate(jsonObjectFromArray.getString("publishdate"));
risks.setKeywords(jsonObjectFromArray.getString("keywords"));
risks.setPublishdate(jsonObjectFromArray.getString("publishtype"));
risks.setTimestamp(jsonObjectFromArray.getString("timestamp"));
risksArrayList.add(risks);
}
}
risksArrayList.get(0);
JSONObject firstObjectFromJsonArray = filteredJSONArray.getJSONObject(0);
JSONObject lastObjectFromJsonArray = filteredJSONArray.getJSONObject(filteredJSONArray.length() - 1);
firstObjectHashMap.put("UID", firstObjectFromJsonArray.getString("UID"));
firstObjectHashMap.put("subject", firstObjectFromJsonArray.getString("subject"));
firstObjectHashMap.put("articletext", firstObjectFromJsonArray.getString("articletext"));
firstObjectHashMap.put("displaydate", firstObjectFromJsonArray.getString("displaydate"));
firstObjectHashMap.put("publishdate", firstObjectFromJsonArray.getString("publishdate"));
firstObjectHashMap.put("keywords", firstObjectFromJsonArray.getString("keywords"));
firstObjectHashMap.put("publishtype", firstObjectFromJsonArray.getString("publishtype"));
firstObjectHashMap.put("timestamp", firstObjectFromJsonArray.getString("timestamp"));
lastObjectHashMap.put("UID", lastObjectFromJsonArray.getString("UID"));
lastObjectHashMap.put("subject", lastObjectFromJsonArray.getString("subject"));
lastObjectHashMap.put("articletext", lastObjectFromJsonArray.getString("articletext"));
lastObjectHashMap.put("displaydate", lastObjectFromJsonArray.getString("displaydate"));
lastObjectHashMap.put("publishdate", lastObjectFromJsonArray.getString("publishdate"));
lastObjectHashMap.put("keywords", lastObjectFromJsonArray.getString("keywords"));
lastObjectHashMap.put("publishtype", lastObjectFromJsonArray.getString("publishtype"));
lastObjectHashMap.put("timestamp", lastObjectFromJsonArray.getString("timestamp"));
oldestDateStr = firstObjectHashMap.get("publishdate");
latestDateStr = lastObjectHashMap.get("publishdate");
oldestDateStr = oldestDateStr.substring(0, 10);
oldestDateStr = oldestDateStr + " 00:00:00";
formatedOldestDate = fmt.parseDateTime(oldestDateStr);
formatedLatestDate = fmt.parseDateTime(latestDateStr);
int daysInMonth;
ArrayList<JSONObject> perMonthRisksArray = new ArrayList<JSONObject>();
while (formatedOldestDate.isBefore(formatedLatestDate) || formatedOldestDate.isEqual(formatedLatestDate)) {
daysInMonth = formatedOldestDate.dayOfMonth().getMaximumValue();
upDate = formatedOldestDate.plusDays(daysInMonth - 1);
long formatedLatestDateMillis = formatedOldestDate.getMillis();
long upDateMillis = upDate.getMillis();
perMonthRisksArray = fetchObjectsByDate(filteredJSONArray, formatedLatestDateMillis, upDateMillis);
wholeYearRiskArray.add(perMonthRisksArray);
formatedOldestDate = upDate.plusDays(1);
}
wholeYearRiskArray.get(0);
Log.d(TAG, Integer.toString(wholeYearRiskArray.size()));
risksArrayList.get(0);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
queue.add(req);
}
public ArrayList<JSONObject> fetchObjectsByDate(JSONArray array, long startDate, long endDate) {
final ArrayList<JSONObject> list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
final JSONObject object = array.optJSONObject(i);
if (object != null) {
final String dateStr = object.optString("publishdate");
if (dateStr != null) {
final long date = fmt.parseDateTime(dateStr).getMillis();
if ((date >= startDate) && (date <= endDate)) {
list.add(object);
}
}
}
}
return list;
}
}
Here is my Risks.Java code.
public class Risks {
String UID;
String subject;
String articletext;
String displaydate;
String publishdate;
String keywords;
String publishtype;
String timestamp;
public String getUID() {
return UID;
}
public void setUID(String UID) {
this.UID = UID;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDisplaydate() {
return displaydate;
}
public void setDisplaydate(String displaydate) {
this.displaydate = displaydate;
}
public String getArticletext() {
return articletext;
}
public void setArticletext(String articletext) {
this.articletext = articletext;
}
public String getPublishdate() {
return publishdate;
}
public void setPublishdate(String publishdate) {
this.publishdate = publishdate;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getPublishtype() {
return publishtype;
}
public void setPublishtype(String publishtype) {
this.publishtype = publishtype;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
Should i is use a ListView or TableLayout or LayoutInflator?
How can i generate dynamically fragments without any tabs and show the data according to the above scenario?
Ok first you need to add all required that into a List.
then you have to make a custom List and make a seperate layout for your list.
then put all the data from that list to custom list. This is the solution.
Check this https://stackoverflow.com/a/8166802/5275639 it will help you.
Try the Gson library. Key-value mappings from JSON to custom user models can be easily done, Hope it helps!
use http://www.jsonschema2pojo.org/ to create your POJO classes for your JSON response. Then use the Gson library to map THE response to POJO class. It'll be much easier to show it in ViewPager after this. Give a try
Create the fragments dynamically according to the size of the array. No need to have separate fragments. Create a sample viewpager fragment example from Android Studio then you'll come to know how to have a dynamic fragments on time. By default the default view pager implementation examples which you can find anywhere on internet would come without tab.

Converting the Database details to JSON object

I have a table with has the columns namely
recordID, recordName , titleFeild, titleIDMap, titleId, titleStartDate, titleEndDate, languageId
Now I have convert the data from above columns to the JSON object data which looks like below
{
"recordId" :10,
"recordName" : "RECORDS",
"records" : [ {
"titleField" : 1,
"titleIDMap" : null,
"titleId" : 500,
"titleStartDate" : "2013-12-22T00:00:00.000+0000",
"titleEndDate" : "2013-12-03T00:00:00.000+0000",
"languageId" : 20
}]
}
Please note that records is an array of columns ( titleFeild,titleIDMap,titleId,titleStartDate,titleEndDate,languageId)
The code so far I have developed is
List<Object[]> objList = dao.getStatus();
Integer result = null;
JSONObject jsonData = new JSONObject();
JSONArray jsonDataArray = new JSONArray();
if(objList!=null && objList.size()>10000)
{
for (Object[] nameObj : objList) {
jsonData.put("", nameObj.get(arg0) );
}
}
How do I construct the JSON Object from the columns data ?
You can easily achieve this with google-gson library. In simple terms you would have to create a couple of Pojos (with reference to another containin a list of references).
Consider RecordID and RecordName as Meta Data.
Create a pojo representing this information:
public class DbMetaPojo {
private int recordID;
private String recordName;
private List<Record> records;
public List<Record> getRecords() {
return records;
}
public void setRecords(List<Record> records) {
this.records = records;
}
public String getRecordName() {
return recordName;
}
public void setRecordName(String recordName) {
this.recordName = recordName;
}
public int getRecordID() {
return recordID;
}
public void setRecordID(int recordID) {
this.recordID = recordID;
}
}
Create another pojo with the actual Record fields:
public class Record {
public int getTitleFeild() {
return titleFeild;
}
public void setTitleFeild(int i) {
this.titleFeild = i;
}
public String getTitleIDMap() {
return titleIDMap;
}
public void setTitleIDMap(String titleIDMap) {
this.titleIDMap = titleIDMap;
}
public int getTitleId() {
return titleId;
}
public void setTitleId(int titleId) {
this.titleId = titleId;
}
public String getTitleStartDate() {
return titleStartDate;
}
public void setTitleStartDate(String titleStartDate) {
this.titleStartDate = titleStartDate;
}
public String getTitleEndDate() {
return titleEndDate;
}
public void setTitleEndDate(String titleEndDate) {
this.titleEndDate = titleEndDate;
}
public int getLanguageId() {
return languageId;
}
public void setLanguageId(int languageId) {
this.languageId = languageId;
}
private int titleFeild;
private String titleIDMap;
private int titleId;
private String titleStartDate;
private String titleEndDate;
private int languageId;
}
Now just a method to populate your POJOs with the relevant data (replace the hardcoding logic with your data retrieve):
public static void main(String... main) {
DbMetaPojo obj = new DbMetaPojo();
obj.setRecordID(10);
obj.setRecordName("RECORDS");
Record record = new Record();
record.setLanguageId(20);
record.setTitleEndDate("2013-12-22T00:00:00.000+0000");
record.setTitleFeild(1);
record.setTitleId(500);
record.setTitleIDMap("SOME NULL");
record.setTitleStartDate("2013-12-22T00:00:00.000+0000");
List<Record> list = new ArrayList<Record>();
list.add(record);
obj.setRecords(list);
Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println(json);
}
Output is your formed JSON:
{
"recordID": 10,
"recordName": "RECORDS",
"records": [
{
"titleFeild": 1,
"titleIDMap": "SOME NULL",
"titleId": 500,
"titleStartDate": "2013-12-22T00:00:00.000+0000",
"titleEndDate": "2013-12-22T00:00:00.000+0000",
"languageId": 20
}
]
}
EDIT:
To align to your code, you might want to do something like:
List<Object> objList = dao.getStatus();
List<DbMetaPojo> metaList = new ArrayList<DbMetaPojo> ();
if (objList != null && objList.size() > 10000) {
for (Object nameObj : objList) {
DbMetaPojo meta = new DbMetaPojo();
meta.setRecordID(nameObj[0]);
meta.setRecordName(nameObj[0]);
...
...
...
metaList.add(meta);
}
}
First of all what you have to do is retrieve the data from the columns of the table using your DAO and calling a Function from DAOIMPL which in turn will return the list of data(POJO probably).
Create a map like this which will contain your key value pair for example recordid and value,
recordname and value
Map<String,Object> objMap = new HashMap<String,Object>();
objMap.put("recordId", Record.getId());
objMap.put("recordName",Record.getName());
// Now here is the deal create another hashmap here whose key will be records "the key for your second array"
//Put the values in this second hashmap as instructed above and put it as a key value pair.
........
.......
.......
JSONObject JsonObject = JSONObject.fromObject(objMap);//This will create JSON object out of your hashmap.
objJSONList.add(JsonObject);
}
StringBuffer jsonBuffer = new StringBuffer();
jsonBuffer.append("{\"data\": {");
jsonBuffer.append(objJSONList.tostring());
jsonBuffer.append("}");
//jsonBuffer.append(",\"total\":"+ objJSONList.size());// TOTAL Optional
//jsonBuffer.append(",\"success\":true}");//SUCCESS message if using in callback Optional
Create an object which has your attribues. (recordID, recordName , titleFeild, titleIDMap, titleId, titleStartDate, titleEndDate, languageId)
Get data from dao and convert it to json. It will looks like what you want.
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
I think your dao.getStatus() should return a List with Map keys and values. Your key would be column name and value would be content.
List<Map<String,Object>> objList = dao.getStatus();
if(objList!=null && objList.size()>10000){
for(Map<String,Object> row : objList) {
Iterator<String> keyList = row.keySet().iterator();
while(keyList.hasNext()){
String key = keyList.next();
jsonData.put(key, row.get(key));
}
}
}
For the records array you need to build it while iterating table columns.
Combining above code with building records array would be something like this..
String[] group = {"titleField","titleIDMap","titleId","titleStartDate","titleEndDate","languageId"};
List<String> recordGroup = Arrays.asList(group);
Map<Object, JSONArray> records = new HashMap<Object,JSONArray>();
List<Map<String,Object>> objList = dao.getStatus();
JSONObject jsonData = new JSONObject();
if(objList!=null && objList.size()>10000){
for(Map<String,Object> row : objList) {
int columnCount = 0;
Iterator<String> keyList = row.keySet().iterator();
while(keyList.hasNext()){
String key = keyList.next();
if(recordGroup.contains(key)){
Object recordId = row.get("recordId");
JSONArray recordArray = new JSONArray();
if(records.containsKey(recordId)){
recordArray = records.get(recordId);
JSONObject jsonObj = null;
if(columnCount >= recordGroup.size()){
jsonObj = new JSONObject();
recordarray.add(jsonObj);
columnCount = 0;
}
else {
jsonObj = (JSONObject) recordArray.get(recordArray.size()-1);
}
jsonObj.put(key, row.get(key));
columnCount++;
}
else {
JSONObject jsonObj = new JSONObject();
jsonObj.put(key, row.get(key));
recordArray.add(jsonObj);
records.put(recordId, recordArray);
}
jsonData.put("records", records.get(recordId));
}
else {
jsonData.put(key, row.get(key));
}
}
}
}

Categories

Resources