Compare Two JSONArray In Android - android

I want to compare two JSONArray with the same value with different order how compare it. This code work fine if value place in the same index.
String a = "[\"ABC-110101-056079-0001\",\"CBA-111101-056079-0001\",\"BCD-110101-056079-0011\"]";
String b = "[\"ABC-111101-056079-0001\",\"CBA-110101-056079-0001\",\"BCD-110101-056079-0011\"]";
JSONArray jsonArraya = null;
JSONArray jsonArrayb = null;
try {
jsonArraya = new JSONArray(a);
jsonArrayb = new JSONArray(b);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonArraya.equals(jsonArrayb)) {
Log.i("TAG",str2 is equal to str1 = " + "true");
}

You could add the elements of each array to a SortedSet instance and compare those:
SortedSet<Object> seta = new TreeSet<>();
jsonArraya.forEach(seta::add);
SortedSet<Object> setb = new TreeSet<>();
jsonArrayb.forEach(setb::add);
Log.i("TAG", "str2 is equal to str1 = " + seta.equals(setb));

The best solution in this situation is to parse values of those arrays first using Gson into POJO files, After that create .equals() method, which will add all strings from array into Set<>.
Then iterate over one set and remove all current item from another set and remove the same elements. Both objects are the same if at the end there will be no elements in the second set.

Related

Parse get multiple objects using their objectIds

I have a ArrayList<String> -named listObjectId below- of objectIds. I'm trying to get all the objects that have an objectId contained in the ArrayList.
The solution I have right now, I think, is very bad from a performance point of view:
for (int i = 0; i < listObjectId.size(); i++) {
ItemModel mItemModelRetrieved = null;
ParseQuery<ItemModel > query = ParseQuery.getQuery(ItemModel .class);
try {
mItemModelRetrieved = query.get(listObjectId.get(i));
subscriber.onNext(mItemModelRetrieved ); //-- I'm using RxJava
} catch (ParseException e) {
Log.e(TAG, "Error Local " + e.getMessage());
}
}
You're using the wrong method. You have the object ids, so create a ParseObject with them using ParseObject.createWithoutData and then fetch the object. Try the following:
List<ParseObject> parseObjects = new ArrayList<>();
for (String objectId : listObjectId) {
parseObjects.add(ParseObject.createWithoutData(ItemModel.class, objectId));
}
ParseObject.fetchAll(parseObjects);
// parseObjects will now contain all data retrieved from Parse.
The error you're getting tells you that the data type of the column you query must be of type Array, not the value you pass into the method.

Get Data from ArrayList Model class in android

I am using Gson library for pasring json,
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
PropertyModel[] response = gson.fromJson(reader, PropertyModel[].class);
i had set all data in Araylist like
Arraylist<PropertyModel[]> model=Arraylist<PropertyModel[]>();
model.add(response);
Now My problem is i am not able to get Arraylist PropertyModel class data
Please suggest me how can get Value from ArrayList
Thanks in Advance
try this code it will probably work...
String responseString = jsonArray.toString();
Log.e("jsonArray string --->", "" + responseString);
Type listType = new TypeToken<ArrayList<ModelOneVOneListItem>>() {
}.getType();
yourArrayList = new Gson().fromJson(responseString, listType);
First add values in Arraylist . Assume your modelclass name is CorpusHeadingModel:
ArrayList<CorpusHeadingModel> lemmaHeadingList = new ArrayList<CorpusHeadingModel>();
CorpusHeadingModel headingModel = new CorpusHeadingModel();
headingModel.setLemmaWord("Apple");
headingModel.setLemmaOccurance("3");
// now add the values to the list :
lemmaHeadingList.add(headingModel);
Now, Retrive one value with list position or any number corresponding the length of lemmaHeadingList :
CorpusHeadingModel model = lemmaHeadingList.get(position);// "position" or any number value according to your lemmaHeadingList.size().
String word = model.getLemmaWord();
String countWord= model.getLemmaOccurance();
Toast.makeText(mContext, "word= " +word+" Occurance= "+ countWord, Toast.LENGTH_SHORT).show();
Output:
word= Apple Occurance= 3
Hope, It helps, to retrieve any string from a list with modelClass.
Try like this
Add in Array list
ArrayList<String>() AddList= new ArrayList<String>();
Values = jb.getString("Your value");
AddList.add(Values);
Then Convert Array List to String Array
String[] BrandNameArray = new String[AddList.size()];
BrandNameArray = AddList.toArray(BrandNameArray);
use the Array
Your way is wrong assigning Array to Arraylist change last two lines:-
change these two line in the code
Arraylist<PropertyModel[]> model=Arraylist<PropertyModel[]>();
model.add(response);
to this:-
Arraylist<PropertyModel> model = new ArrayList<PropertyModel>(Arrays.asList(response));
For getting values you can use for loop
for(int i=0 ; i<model.size() ; i++){
PropertyModel object = model.get(i); //getting single object from Arraylist
}
as we know arraylist uses index to store values we must provide it an index but when its associated with a model class, it can be done in two ways.
let me give you an example.
1) you use your arraylist in the recycler adapter and get its object value using position,
holder.name.setText(myarraylist.get(position).getName()); // for recycler adapter in "onBindViewHolder"
name.setText(myarraylist.get(position).getName());//for base adapter in getview
2) if you want to check your object values in arraylist before passing it to the adapter you can do it this way,
for (contact d :emps ){
Log.e("name object of array",d.getName()+""); // getting the required object using the instance of model class
}
where contact is the model class, which is also the type of the arraylist emps. I hope this helps you. good luck

Android get string from an Array and create another array

Hi im creating a list that has headers of dates and then content underneath. i have a JSON feed that contains fixtures inside each is an array containing the data for each fixture one string i need is matchdate to create my headers however if i was to just run through it it will create multiple instances of the same match day so id have 3 headers with the same date for example. how can i extract that information and the create another array that says if this date already exists go through the next one and so on. i know it's pretty specific question but if someone could at least point me in the right direction. thanks in advance.
heres my feed
fixturesArray = [{"awayteam":"Team 1","comp":"LGE","location":null,"attendance":null,"awayscore":null,"division":"Testing 1","homescore":null,"fixture_note":null,"kickoff":"15:30:00","awayteam_id":"64930","matchdate":"2012-07-07","awaypens":null,"homepens":null,"division_id":"5059","hometeam":"Team 3","hometeam_id":"64932"},{"awayteam":"Team 2","comp":"LGE","location":null,"attendance":null,"awayscore":null,"division":"Testing 1","homescore":null,"fixture_note":null,"kickoff":"15:00:00","awayteam_id":"64931","matchdate":"2012-07-07","awaypens":null,"homepens":null,"division_id":"5059","hometeam":"Team 4","hometeam_id":"64933"},{"awayteam":"Team 4","comp":"LGE","location":null,"attendance":null,"awayscore":null,"division":"Testing 1","homescore":null,"fixture_note":null,"kickoff":"15:00:00","awayteam_id":"64933","matchdate":"2012-07-14","awaypens":null,"homepens":null,"division_id":"5059","hometeam":"Team 1","hometeam_id":"64930"}]
heres what i have tried so far
Log.v("MyFix", "fixturesArray = " + fixturesArray);
if(fixturesArray.length() < 1){
TextView emptytext = (TextView) fixturesView.findViewById(R.id.TextView02);
emptytext.setText("No Upcoming Fixtures Available");
}else{
try{
JSONArray datesArray = null;
fixturesInfo = null;
String matchDateTemp = "";
for(int t = 0; t < fixturesArray.length(); t++){
JSONObject matchDateDict = fixturesArray.getJSONObject(t);
String matchDate = matchDateDict.getString("matchdate");
JSONArray matchdates = matchdates.put(matchDate);
Log.v("MyFix", "matchdate = " + matchDate);
tempArray.put(t, fixturesArray);
fixturesInfo.put(matchDate, tempArray);
}
Log.v("MyFix", "fixturesInfo = " + fixturesInfo);
Log.v("MyFix", "tempArray = " + tempArray);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Just get the piece of data then iterate through the new arraylist checking for a duplicate before adding.
int matchCount=0; // set count of matches to 0
String matchDate = matchDateDict.getString("matchdate"); // get the data to compare
for (int i = 0; i < uniqueDateArrayList.size(); i++){ // set loop to iterate through unique date arraylist
if (matchDate.equals(uniqueDateArray[i])){ // compare the date to the date stored at position i
matchCount++; // if it matches increase the match count
}
}
if (matchCount == 0) {
uniqueDateArrayList.add(matchDate) // if there is no matching date, add it to the unique date arraylist
}
That should give you an array list containing all of the unique dates in your data.

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

How do I use a hashmap iterator to print more than one entryKey in Android?

I have a hashmap and an iterator that iterates through four alternatives and the corresponding value to a question. I have a TableLyaout where a TableRow is added programmatically depending on how many rows there are.
I get it to print a random alternative, but only the one. How can I get all four alternatives to get written in a textview each?
Iterator<Entry<String, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Entry<String, Integer> entry = entries.next();
String alternative = entry.getKey();
Integer value = entry.getValue();
try {
alternative = new String(alternative.getBytes("macintosh"), "UTF-8");}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mTvAlt.setText(alternative +" "+value);}
I found the solution.
arrayAlternative = map.keySet().toArray();
arrayValue = map.values().toArray();
Object [] alternative = arrayAlternative[x].toString();
Object [] value = arrayValue[x].toString();
I would have preferred to get the value as an integer array, but didn't know how so I took it as a string array.

Categories

Resources