where should I put json data inside android - android

I am planning to store some data in json in that way I can read and write this json data.
I want to use it as a simple database instead of using sqlite.
Where should I create this json data in file hierarchy and how to write and read data from json.

just declare a string variable and then set that to your json like :
String myjson = "obj1: {}..." //it is your json
JsonObject obj = new JsonObject(myJson);
then you can do
String s = obj.getString("key");

This is a very nice question for a beginner in Android so I will tell you about singleton class which we use to store data in any language.
"Singleton class" this is a class which have only one reference (object). Code how to make this class is below:
public class DataController {
private static DataController ref;
public static DataController getInstance()
{
if(ref==null)
ref = new DataController();
return ref;
}
public void deleteInstance()
{
ref=null;
}
public ArrayList<MediaWrapper>videoWrapper = new ArrayList<MediaWrapper>();
public ArrayList<MediaWrapper>audioWrapper = new ArrayList<MediaWrapper>();
public ArrayList<MediaWrapper>documentWrapper = new ArrayList<MediaWrapper>();
}// you can add any data type under this class
Now anywhere you can use this class like this put this code inside your activity on-create method where you want to use this.
private DataController controller;
controller = DataController.getInstance();
Now just call that datatype in which you want to add your data like this.
controller.videoWrapper = //put your data inside this. This data will be save until or unless your activity in the stack
Also you can access that data like this controller.videoWrapper it will give you all data which you save in this.

Related

Best practices for fetching same data in multiple objects using web service VS front-end computations for accessing existing data?

In my application I have fetched some data called data1 from web server and displayed, after two three screen navigation I need some data which is existing in data1 but it requires some iterations to access, So is this right I should invoke another web service which is providing required data or front end computations needs to be done.
YOu can Save your data in a Separate class and fetch from there when you need it,
like getter setter.
Like this..
public class Global {
private static JSONObject jsonObject;
public static void saveData(JSONObject object) {
jsonObject = object;
}
public static JSONObject getData() {
return jsonObject;
}
}
From your Activity:
Global.saveData(jsonObject);
Orr
JsonObject jsonObj = Global.getData();

how to pass HashSet object from from one Fragment to another Fragment in android

i want to Pass Hash_set object when click on button,object pass from one fragment to another fragment. in Hash_set object I Put multiple Parse Object in Hash_set object .How to do it ? i tried with Intent and Bundle but not get successful to pass object.
please provide me any best idea. thanks `
You can Also use Application.
step1:Use this class
public class JsonApplication extends Application {
public JSONObject jsonObject;
public JSONObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}}
step2: set data and get data as your desire
Simply, create an static object of your hashset in the activity like this,
public static Set<YourObject> mObject = new HashSet<YourObject>();
and from your BaseAdapter-button-onClick call it in this way,
ActivityName.mObject = mYourHashSet;
A public static field/method
An alternate way to make data accessible across Activities/Services is
to use public static fields and/or methods. You can access these
static fields from any other class in your application. To share an
object, the activity which creates your object sets a static field to
point to this object and any other activity that wants to use this
object just accesses this static field.
Other way todo this,
In you baseAdapter-onClick, convert it to JSONObject like that,
JSONObject multiple = new JSONObject();
multiple.put("hash_set_object", mHashSetObject);
Intent ii = new Intent(mActivity, ActivityName.class);
ii.putExtra("hash_set_json", multiple.toString());
startActivity(ii);
In Activity's onCreate call it in this way,
String HashString = getIntent().getExtras().getString("hash_set_json");
JSONArray array = new JSONArray(new JsonObject(HashString).getString("hash_set_object"));
//Now make for-loop to re-populate hashSet from JSONArray

Set value to a realm object

I have following class
public class Student extends RealmObject{
private int studentID;
private String studentName;
// getters and setters here
}
Then I try to set a value to a already created student object
student.setStudentName("Peter");
Then I get following error
java.lang.IllegalStateException: Mutable method call during read
transaction.
In order to overcome this I have to do it as follows
Realm realm = Realm.getInstance(this);
realm.beginTransaction();
student.setStudentName("Peter");
realm.commitTransaction();
I don't want to persist this change in the database. How can I just set/change a value to an realm object variable without always persisting it to the database?
If you want to modify the object in a non-persisted manner, you need an unmanaged copy of it.
You can create a copy using realm.copyFromRealm(RealmObject realmObject); method.
When you are using Realm.createObject(), the object is added to the Realm and it only works within a write transaction. You can cancel a transaction and thereby discard the object.
Moreover, you can use your model class as a standalone class and create objects in memory (see http://realm.io/docs/java/0.80.0/#creating-objects for details). If you need to persist the objects, you can use the Realm.copyToRealm() method.
You might want to create a new Model. And your new model should implement RealmModel.
public class StudentRM extends RealmModel{
private int studentID;
private String studentName;
// Constructors here
// getters and setters here
}
Now you can do this.
studentRm.setStudentName("Peter"); //Setting Vale Or
studentRm.addAll(student); //Add all value from DB
studentRm.setStudentName("Jhon"); //It won't change DB anymore
studentRm.getStudentName(); // "Jhon"
You can use realm.cancelTransaction();, instead of realm.commitTransaction();

how to pass the ArrayList<data class> from one activity to another activity android

In my application whenever we click the "SEARCH" button it makes Http call and get the json as response. I parsed the json and save the data in arraylist bdata.
ArrayList bdata = new ArrayList();
BusData contain getters and setters . I also used one adapter class for custom listview.
now i want to set the adapter to listview but the listview is in another class (not in the class where search button is locate) so how to send my arraylist from one activity to another activity with the help of intents for set the adapter to listview.
Thank you.
A way to do this is by serializing your arraylist to a JSON.
Use GSON library
compile 'com.google.code.gson:gson:2.3.1'
Add the above line in your build.gradle file.
Make a class to help you serializing your objects
public class SerializationHelper {
private static Gson gson = new Gson();
public static String serialize(Object object) {
return gson.toJson(object);
}
public static Object deserialize(String json, Class classType) {
return gson.fromJson(json, classType);
}
}
Now when you want to start the new activity add the serialized string.
String json=SerializationHelper.serialize(myArrayList);
intent.putExtra("data",json);
And in your new activity on create get it and create your object again.
String json=intent.getStringExtra("data");
Object deserializedObject=SerializationHelper.deserialize(json,ArrayList.class);
Now cast your object!
ArrayList<MyClass> myCoolArray=(ArrayList<MyClass>)deserializedObject.
Other simpler way is to make your arraylist static and public, and store it in an other class.
public class GlobalStuff{
public static ArrayList<MyClass> myAwesomeList;
}
Now acces your list by GlobalStuff.myAwesomeList.
You need to create custom class (ArrayList<data class>) to Parcelable and then you can pass it to other activity.
http://androidideasblog.blogspot.in/2010/02/passing-list-of-objects-between.html
When passing data through activities you should use Parcelable, the are many examples in stackoverflow, this one is good:
https://stackoverflow.com/a/22446641/2091315
Next, you need to configure the intent, on the "sender" Activity:
Intent intent = new Intent(getApplicationContext(),
ReceiverActivity.class);
intent.putExtra("arrayListIdentifier",parcelableArrayClass);
startActivity(intent);
On the "receiver" Activity:
parcelableArrayClass myParcelableObject = (parcelableArrayClass) getIntent().getParcelableExtra("arrayListIdentifier");

JSONObject as class attribute storage/retrieval

In android, I'm using model classes with methods to handle the data manipulation. My data is brought in from webservices as json. I'm contemplating the possibility of using JSONObjects to store the values of class level attributes. But, I don't know of a way to use the JSONObj as the "holder" variable and create access methods. I don't want to predetermine these methods, as jsonRepository should hold the values, not always known at design time
For example, I'd like to have:
public class User {
private JSONObject jsonAttributes;
public User(String json) {
this.jsonAttributes= new JSONObject(json);
}
[IMPLICIT attribute access methods]
public string Prop1() returns jsonAttributes.getString("prop1");
public string Prop1(String newProp1) returns jsonAttributes.putString("prop1",newProp1);
public string Prop2() returns jsonRepository.getString("id");
public string Prop2(String newProp2) returns jsonAttributes.putString("prop2",newProp2);
....
from outside this class then, I would access the attributes simply...
User myUser = new User(someValidJson);
String myString = myUser.Prop1
Misguided? If not, how does one manage implicit property setting/getting?
As was mentioned in the comment above, why not create your user class, with all of the relevant memeber variables, and simply parse your JSON data in order to populate the ionformation in your user class.
There are a lot of ways you can do this, but I would consider using the builder pattern, as it is flexible, which could be useful if your JSON data changes in the future.

Categories

Resources