i want to save the user's data in json file in a internel memory but it doesn't work what's the problem???? this is the code...................................................................................................................
public JSONObject addToJson(Context context, String email,String password)throws Exception{
String id_P = UUID.randomUUID().toString();
JSONObject jsonObject = new JSONObject();
jsonObject.put("id_P",id_P);
jsonObject.put("Email",email);
jsonObject.put("password",password);
String j = jsonObject.toString();
System.out.println(j);
File file = new File(context.getFilesDir(),"dbApp.json");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(j);
bufferedWriter.close();
return jsonObject;
}
You can use different of local database like Room, Realm etc. But for
Writing: you need to convert your JSON into String or Model class and then you can store into Database.
Reading : convert string into JSON or Model Class and use the same.
Take more look at https://realm.io/docs/java/latest/
Example of Realm Database in Android You can option of choose this:
Writing
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();
Reading
RealmQuery<User> query = realm.where(User.class);
// Add query conditions:
query.equalTo("name", "John");
query.or().equalTo("name", "Peter");
// Execute the query:
RealmResults<User> result1 = query.findAll();
// Or alternatively do the same all at once (the "Fluent interface"):
RealmResults<User> result2 = realm.where(User.class)
.equalTo("name", "John")
.or()
.equalTo("name", "Peter")
.findAll();
well I am not an expert in this matter but I think here is what you should do:
first add this JSON converter library to your build.gradle:
implementation 'com.google.code.gson:gson:2.8.6'
after that you need to create a model class in which you should categorize your data in different maps, NOTE: use maps all the time array list won't work properly:
Class Model{
Map<String ,String> userData;
public Model(Map<String, String> setUserdata) {
this.setUserdata = setUserdata;
}
public void setSetUserdata(Map<String, String> setUserdata) {
this.setUserdata = setUserdata;
}
}
okay, and then for setting data you should create a Map and then initialize the class and pass it the Map similar to this:
Map<String ,String> userData=new HashMap<>();
setUserdata.put("username","something");
setUserdata.put("password","something");
Model model=new Model(userData);
and now you can easily convert this to a JSON: Gson gson = new Gson(); String json = gson.toJson(model);
and you can easily save this in file with text format.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.