Hashmap to JSON Array - android

I would like to ask if someone here knows how to convert a HashMap to JSON Array to be used on a Adapter. The logic is when you logged in, it will fetch data on a web server using Volley, store it on SQLite database and at the same time it will show the retrieve data on a custom listview. The thing is, if you will move to another fragment on the application and then go back, it will request again on the volley which it will take time. I wanted that if you will go back the data stored on the SQLite database will be retrieved and if the user wanted to update the data using SwipeRefresh, that's the time to update for new data.
Here is my code.
public void LoadMarkets()
{
Map<String,String>tmpRate = new HashMap<String,String>();
RateDb db = new RateDb(getActivity().getApplicationContext());
Cursor rs = db.getData();
if(rs!=null && rs.getCount()>0)
{
if(rs.moveToFirst())
{
while(rs.moveToNext())
{
tmpRate.put("rateID",rs.getString(rs.getColumnIndex(RateDb.rateID)));
tmpRate.put("Name",rs.getString(rs.getColumnIndex(RateDb.rateName)));
tmpRate.put("Rate",rs.getString(rs.getColumnIndex(RateDb.rateRate)));
tmpRate.put("Date",rs.getString(rs.getColumnIndex(RateDb.rateDate)));
tmpRate.put("Time",rs.getString(rs.getColumnIndex(RateDb.rateTime)));
tmpRate.put("Ask",rs.getString(rs.getColumnIndex(RateDb.rateAsk)));
tmpRate.put("Bid",rs.getString(rs.getColumnIndex(RateDb.rateBid)));
tmpRate.put("Balance",rs.getString(rs.getColumnIndex(RateDb.rateBalance)));
//Log.d("MyDebug",rs.getString(rs.getColumnIndex(RateDb.rateName)));
}
}
}
rs.close();
db.close();
JSONObject jsonObject = new JSONObject(tmpRate);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
RowAAdapter rowAAdapter = new RowAAdapter(getActivity(),jsonArray);
lvMarkets.setAdapter(rowAAdapter);
swipeRefreshLayout.setRefreshing(false);
}
The problem is that when i load this function, it only shows the last data.
I hope you can help me with my problem.
Thank you very much.

You can put the values directly into the jsonObject instead of adding it to the hashmap like this :
public void LoadMarkets()
{
RateDb db = new RateDb(getActivity().getApplicationContext());
Cursor rs = db.getData();
if(rs!=null && rs.getCount()>0)
{
if(rs.moveToFirst())
{
while(rs.moveToNext())
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("rateID",rs.getString(rs.getColumnIndex(RateDb.rateID)));
jsonObject.put("Name",rs.getString(rs.getColumnIndex(RateDb.rateName)));
jsonObject.put("Rate",rs.getString(rs.getColumnIndex(RateDb.rateRate)));
jsonObject.put("Date",rs.getString(rs.getColumnIndex(RateDb.rateDate)));
jsonObject.put("Time",rs.getString(rs.getColumnIndex(RateDb.rateTime)));
jsonObject.put("Ask",rs.getString(rs.getColumnIndex(RateDb.rateAsk)));
jsonObject.put("Bid",rs.getString(rs.getColumnIndex(RateDb.rateBid)));
jsonObject.put("Balance",rs.getString(rs.getColumnIndex(RateDb.rateBalance)));
jsonArray.put(jsonObject);
//Log.d("MyDebug",rs.getString(rs.getColumnIndex(RateDb.rateName)));
}
}
}
rs.close();
db.close();
RowAAdapter rowAAdapter = new RowAAdapter(getActivity(),jsonArray);
lvMarkets.setAdapter(rowAAdapter);
swipeRefreshLayout.setRefreshing(false);
}
The problem with your code is that :
You're putting the values with keys "rateID", "Name"... etc. in the while loop again and again, so the previous values are being replaced with the new values and finally you've just one set of data in your hashmap. That's why you're getting only the last set of data.
Try the above code. It should work as expected.
This will work as it creates a new JsonObject in the loop and adds it to the jsonArray when the data is successfully added to it.

Related

Data from API parsing in for cycle with bad result

I parse data from API (https://statsapi.web.nhl.com/api/v1/standings) in for cycle. In debug mode, I see, that data are correct from API, but when I write first record to "tabulkaTimov", and for cycle have j=1 (j=2,j=3, ... etc), my first record is replace by next team.
Screenshot of my app:
https://ctrlv.cz/shots/2019/01/03/bbEf.png
It is table of NHL league.
public static List<TableTeamsModel> convertJsonToTableTeams(JsonObject data){
List<TableTeamsModel> tabulkaTimov = new ArrayList<>();
JsonArray pocetDivizii = data.get("records").getAsJsonArray();
for(int i=0;i<pocetDivizii.size();i++){
TableTeamsModel tabulka = new TableTeamsModel();
JsonObject division = pocetDivizii.get(i).getAsJsonObject();
tabulka.setDivisionName(division.get("division").getAsJsonObject().get("name").getAsString());
JsonArray teams = division.get("teamRecords").getAsJsonArray();
for(int j=0;j<teams.size();j++) {
JsonObject teamRecords = teams.get(j).getAsJsonObject();
tabulka.setTeamName(teamRecords.get("team").getAsJsonObject().get("name").getAsString());
tabulka.setGoalsGot(teamRecords.get("goalsAgainst").getAsInt());
tabulka.setGoalsScored(teamRecords.get("goalsScored").getAsInt());
tabulka.setPoints(teamRecords.get("points").getAsInt());
tabulka.setGamesPlayed(teamRecords.get("gamesPlayed").getAsInt());
tabulkaTimov.add(tabulka);
}
}
return tabulkaTimov;
}
Looks like you are creating a new tabulka object outside of your for loop and then add it multiple times in the same arraylist.
This will add it once (reference) and just update its content.
Here is what you can do
public static List<TableTeamsModel> convertJsonToTableTeams(JsonObject data){
List<TableTeamsModel> tabulkaTimov = new ArrayList<>();
JsonArray pocetDivizii = data.get("records").getAsJsonArray();
for(int i=0;i<pocetDivizii.size();i++){
// Remove the creation of the tabulka object from here
JsonObject division = pocetDivizii.get(i).getAsJsonObject()
JsonArray teams = division.get("teamRecords").getAsJsonArray();
for(int j=0;j<teams.size();j++) {
JsonObject teamRecords = teams.get(j).getAsJsonObject();
// And then put the object creation here.
// as we did't have it above, the division name has to be set here too.
TableTeamsModel tabulka = new TableTeamsModel();
tabulka.setDivisionName(division.get("name").getAsString());
tabulka.setTeamName(teamRecords.get("team").getAsJsonObject().get("name").getAsString());
tabulka.setGoalsGot(teamRecords.get("goalsAgainst").getAsInt());
tabulka.setGoalsScored(teamRecords.get("goalsScored").getAsInt());
tabulka.setPoints(teamRecords.get("points").getAsInt());
tabulka.setGamesPlayed(teamRecords.get("gamesPlayed").getAsInt());
tabulkaTimov.add(tabulka);
}
}
return tabulkaTimov;
}
This way you will add a different/new object each time you go over the loop into your ArrayList; - instead of adding the same reference of the same object every time with its data updated.

Saving Multiple Values in a Key with JSON

I tried to do it with multiple Shared Preferences keys, but it goes quiet complicated.
I saw some said that it is possible with JSON, but have no idea how to do it.
My app has many items in ListView, and I want to save several values in each item.
You can imagine a contact management app.
When the Item(person name) is clicked, you can check the values like phone number, address, and picture. And of course, they can be edited, added and deleted.
Is it possible to save values in single KEY with JSON?
So that I can load the values for each item when it is clicked.
To be able to save multiple values inside a jsonObject you can do this
try {
JSONObject Contacts = new JSONObject();
Contacts.put("Name", "Saul Goodman");
Contacts.put("Address", "Ocean Drive");
Contacts.put("Phone", "13456");
Contacts.put("Contacts", Contacts);
} catch (JSONException e) {
e.printStackTrace();
}
So that will create a structure like this
"Contacts":{
"Name":"Saul Goodman",
"Address":"Ocean Drive",
"Phone":"123456"
}
};
To retrieve this values you should do this
JSONArray array = object.getJSONArray("Contacts");
for(int i = 0; i < array.length; i++) {
JSONObject object = (JSONObject) array.get(i);
String name = object.get("Name");
String address = object.get("Address");
String phone = object.get("Phone");
//you also can use object.getString(""); to get the strings
}
hope it helps
Happy coding !

Android: Issue while saving Hasmap in parse

I am facing an issue while saving a HashMap on Parse and then retrieving it.
Below is the code to put data in the ParseObject.
HashMap<Object, Object> eventInfo = new HashMap<>();
eventInfo.put(ParseTable.Column.AllDay, allday);
JSONArray dateSet = new JSONArray();
JSONObject sdObj = new JSONObject();
sdObj.put("__type", "String");
sdObj.put("iso", sdf.format(sdate));
JSONObject edObj = new JSONObject();
edObj.put("__type", "String");
edObj.put("iso", sdf.format(rEnd.getTime()));
dateSet.put(sdObj);
dateSet.put(edObj);
eventInfo.put(ParseTable.Column.DateSet, dateSet);
eventInfo.put(ParseTable.Column.EventType, eType.getText().toString());
eventInfo.put(ParseTable.Column.Location, loc.getText().toString());
eventInfo.put(ParseTable.Column.Points, points.getText().toString());
obj.put(ParseTable.Column.EventInfo, eventInfo);
Now when I get this data from the same object in which I have set it, its correct.
{eventType=Default, location=, allDay=false, dateSet=[{"__type":"String","iso":"2015-02-25T21:18:00Z"},{"__type":"String","iso":"2015-02-28T00:00:00Z"}], points=}
This also saves properly on server:
{"allDay":false,"dateSet":[{"__type":"String","iso":"2015-02-25T21:18:00Z"},{"__type":"String","iso":"2015-02-28T00:00:00Z"}],"eventType":"Default","location":"","points":""}
But when I retrieve the same data from Parse server, this is what it returns, when I log the HashMap:
{eventType=Default, location=, allDay=false, dateSet=[null, null], points=}
Don't know why this is happening.
The reason why you are getting a blank field is because you are calling getMap on a blank/empty event object.
Map<String, Object> oinfo = event.getMap(ParseTable.Column.EventInfo);
I can't see where your event object comes from but I also don't see that you have saved any of this data to the database.
So make sure that obj has been saved:
obj.saveInBackground()
Then you can get your eventInfo out after making a query:
ParseQuery q = ParseQuery.getQuery("YourClass");
q.whereEqualTo("someColumnName", "someValue");
q.findInBackground(new FindCallback() {
#Override
public void done(List objects, ParseException paramParseException) {
for (Object o: objects){
Map<String, Object> oinfo = o.getMap(ParseTable.Column.EventInfo);
}
}
});
If you are actually saving the obj already to the database and only attempting to grab data from a populated event object then please update your question with each step you are taking to get the data from the server. I would like to see the entire lifecycle of the event object.

How to post multiple rows (or a LIST object) to PHP using JSON (Android)

I am creating an android application in which I am using SQLite. I have one table in which I have 5 fields. There are many rows in that table and I want to send all those rows using JSON to my PHP code so I can receive the object and insert it in the MySQL database.
What is the best way to do it. I am using LIST object but don't know how I can use POST it using JSON.
Please guide!
i am using this code
mCursor =db.rawQuery("SELECT * FROM customer", null);
while (mCursor.moveToNext()) {
// In one loop, cursor read one undergraduate all details
// Assume, we also need to see all the details of each and every undergraduate
// What we have to do is in each loop, read all the values, pass them to the POJO class
//and create a ArrayList of undergraduates
customer = new Customer();
customer.CustomerName = mCursor.getString(0).toString();
customer.Phone = mCursor.getString(1).toString();
customer.BrandName = mCursor.getString(2).toString();
customer.City = mCursor.getString(3).toString();
customer.FamilyMembers = mCursor.getString(4).toString();
customerList.add(customer);
}
for (int i = 0; i < customerList.size(); i++)
{
JSONObject row = new JSONObject();
row.put("Customer", customerList.get(i));
json.put(row);
}
Don't know how to post it to PHP code.
You have to iterate through your List and fill an JSONArray with JSONObjects for each row. In the JSONObject you can have the key as your column-name and the value with the type you need.
JSONArray json = new JSONArray();
for (int i = 0; i < list.size(); i++) {
JSONObject row = new JSONObject();
row.put("key1", list.get(i).value1);
...
json.put(row);
}
(not tested). Then you can post the json.toString() to the server and retrieve it in PHP with
$jsonstring = file_get_contents('php://input', true);

Saving ArrayLists in SQLite databases

So I want to save an ordered set of double values, and I want to be able to insert, retrieve or delete any value from this easily. As of such, I'm using a an ArrayList, where I define a class called Doubles to store the double values.
How do I store this arraylist in a record in an SQLite database? I mean...what should the columns type be? Can it be done?
You cannot insert ArrayList directly into Sqlite. Instead, you could use JSONObject (org.json.JSONObject) to insert the ArrayList. Please check below snippet, you can try something like below....
To insert,
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
String arrayList = json.toString();
Insert the string into db.
To Read,
Read the string from db as String,
JSONObject json = new JSONObject(stringreadfromsqlite);
ArrayList items = json.optJSONArray("uniqueArrays");
To Insert :
ArrayList<String> inputArray=new ArrayList<String>();
Add Values to inputArray
Gson gson = new Gson();
String inputString= gson.toJson(inputArray);
System.out.println("inputString= " + inputString);
Use "inputString" to save the value of ArrayList<String> in SQLite Database
To retreive:
Get the String from the SQLiteDatabse what you saved and changed into ArrayList type like below:
outputarray is a String which is get from SQLiteDatabase for this example.
Type type = new TypeToken<ArrayList<String>>() {}.getType();
ArrayList<String> finalOutputString = gson.fromJson(outputarray, type);
In my case it was ArrayList of POJO classes Note
private String mNoteTitle;
private int mFingerIndex;
private Point mNoteCoordinates;
public Note(String noteTitle, int fingerIndex, Point noteCoordinates) {
this.mNoteTitle = noteTitle;
this.mFingerIndex = fingerIndex;
this.mNoteCoordinates = noteCoordinates;
}
As manual says JSONObject supports only following types: Object: a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities. So, I should break my Note class into supported objects.
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(Note note: chordShape.getNotes()){
JSONObject singleNoteJsonObject = new JSONObject();
try {
singleNoteJsonObject.put(SHAPE_NOTE_TITLE, note.getNoteTitle());
singleNoteJsonObject.put(SHAPE_NOTE_FINGER_INDEX, note.getFingerIndex());
singleNoteJsonObject.put(SHAPE_NOTE_X, note.getNoteCoordinates().x);
singleNoteJsonObject.put(SHAPE_NOTE_Y, note.getNoteCoordinates().y);
} catch (JSONException e){
e.printStackTrace();
}
jsonArray.put(singleNoteJsonObject);
}
Pack created array into JSONObject.
try {
json.put(SHAPE_NOTES, jsonArray);
Log.i(TAG, json.toString());
} catch (JSONException e){
e.printStackTrace();
}
Create String.
String notesList = json.toString();
Put created String in ContentValues, cause in my case it's Android app
if(notesList.length() > 0){
contentValues.put(DatabaseHelper.SHAPE_NOTES_LIST, notesList);
}
And when i should read values from SQLite database.
ArrayList<Note> notes = new ArrayList<>();
while(cursor.moveToNext()){
JSONObject jsonNotes = null;
try {
jsonNotes = new JSONObject(cursor.getString(cursor.getColumnIndex(DatabaseHelper.SHAPE_NOTES_LIST)));
} catch (JSONException e){
e.printStackTrace();
}
if(jsonNotes != null){
Log.i(TAG, jsonNotes.toString());
JSONArray jsonArray = jsonNotes.optJSONArray(SHAPE_NOTES);
for(int i = 0; i < jsonArray.length(); i++){
Note note = null;
JSONObject arrayObject = null;
try {
arrayObject = jsonArray.getJSONObject(i);
} catch (JSONException e){
e.printStackTrace();
}
if(arrayObject != null){
try {
note = new Note(
arrayObject.getString(SHAPE_NOTE_TITLE),
arrayObject.getInt(SHAPE_NOTE_FINGER_INDEX),
new Point(
arrayObject.getInt(SHAPE_NOTE_X),
arrayObject.getInt(SHAPE_NOTE_Y)
)
);
} catch (JSONException e){
e.printStackTrace();
}
}
if(note != null){
notes.add(note);
}
}
}
}
cursor.close();
I suggest going through all 3 Notepad tutorials you want to store the values your storing to a database table. you don't store the actual array directly into the database just the data. but you shouldn't actually need to use an array at all instead of adding a new item to the array instead call your db insert method
I've needed to do something similar in my application, where I have a custom class (Foo, Bar, etc.) and I have an ArrayList of foo, bar, etc. that I persist to SQL. My knowledge of SQL isn't strong, but I'll explain my approach here in case it helps.
My understanding is that to store any kind of object, you need to define a particular table for that object type, where the table has separate columns representing the primitive types within that object. Furthermore, to persist and retrieve an ArrayList of those objects, you'll use one table row per ArrayList entry, and iterate over in a loop to store and retrieve.
There are ArrayLists of several custom classes in my application that I wanted to persist to DB. So, to make things tidy (well, to me at least -- I'm still a relatively new Java / Android programmer, so take this with a pinch of salt) I decided to implement a kind of "SQL Serializable Interface" that my DB-persistable objects must implement. Each object (Foo, Bar, etc.) that can be persisted to DB must implement:
A public static final TABLE_NAME string, the name of the SQL DB table used for this object type.
A public static final TABLE_CREATE_STRING, a complete SQL instruction to create the table for this object.
A constructor method to populate its member variables from a ContentValues object.
A 'get' method to populate a ContentValues from its member variables.
So, say I have ArrayLists of objects Foo and Bar. When the DB is first created, within my DB helper class I call Foo.TABLE_CREATE_STRING, Bar.TABLE_CREATE_STRING, etc. to create the tables for those objects.
To populate my ArrayList, I use something like:
cursor = dbh.retrieve(Foo.TABLE_NAME);
if(!cursor.moveToFirst()){
return false
}
do{
DatabaseUtils.cursorRowToContentValues(cursor, vales);
FooArrayList.add( new Foo(values) );
} while( cursor.moveToNext() );
Create a dbHelper class which has an inner class and pretty much whatever the notepad tutorial says. The class must be having an insertion method somthing like this :-
public long insertRows(ContentValues values, String tableName) {
long val = myDatabase.insert(tableName, null, values);
return val;
}
This method will then add values into the table row.
After that you can call this method from your main activity and since you are using cursor i believe you will call the method in a for loop
for(i=0;list.length();i++) // or may be its list.size :P
{
// Call the method here
}
and keep adding value in the database by calling the method in for loop

Categories

Resources