I'm trying to save a single int to a file in my Android project although i cant get my write function to work.
My JSON file:
{
"user":
{
"userid":"0"
}
}
My code:
public String getJsonFile() {
String jsonLocation = "";
try {
InputStream is = getAssets().open("useriidd.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonLocation = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
return jsonLocation;
}
public void jsonRead(){
try {
JSONObject reader = new JSONObject(getJsonFile());
JSONObject sys = reader.getJSONObject("user");
userid = Integer.parseInt(sys.getString("userid"));
}
catch (final JSONException e) {
Log.e("asdasd", e.getMessage());
}
}
public void jsonWrite(){
try {
JSONObject writer = new JSONObject(getJsonFile());
JSONObject sys = writer.getJSONObject("user");
sys.put("userid", Integer.toString(userid));
Log.d("asdasd", getJsonFile());
}
catch (final JSONException e) {
Log.e("asdasd", e.getMessage());
}
}
I need the userid value to also be saved if i exit the app and relaunch it.
You should store it in Preferences, SharedPreferences or in the file on external storage (SD card). You cannot (or should not) edit the assets in run-time.
Declare on Class level
public static final String KEY = "key";
private String value = "you can place any value";
private SharedPreferences sharedPreferences;
onCreate Method
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(YourMainActivity.this);
sharedPreferences.edit().putString(KEY, value);
onResume Method
value = sharedPreferences.getString(KEY, "defaultValue");
You can also do this step on onPause Method
sharedPreferences.edit().putString(KEY, value);
Related
I am making an app where user can change theme (dark and light mood) as per his convenience. And the theme that the user chooses will be saved and the saved theme will be there when the app is opened again later.
I have saved the data to file using JSON.
And when the user clicks on the theme change button, the data will be written to the file.
The code of the theme:
private void darkTheme() {
FlatDarkLaf.setup();
UIManager.put("TextField.foreground", new ColorUIResource(Color.WHITE));
UIManager.put("Label.foreground", new ColorUIResource(Color.WHITE));
UIManager.put("Button.foreground", new ColorUIResource(Color.WHITE));
SwingUtilities.updateComponentTreeUI(contentPane);
for(int i=0; i<arList.size(); i++) {
((JLabel)arList.get(i).getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
}
}
And the Code for the theme change and write to the file button:
btnDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String path = "resources/config.cfg";
JSONObject json = new JSONObject();
try {
json.put("Theme", "darkTheme();");
} catch (JSONException ex) {
ex.printStackTrace();
}
try (PrintWriter out = new PrintWriter(new FileWriter(path))) {
out.write(json.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
darkTheme();
}
});
I can read the file but can't Load the save data.
Here the code for read the file:
private void readData() {
try {
String path = "resources/config.cfg";
InputStream is = Button.class.getResourceAsStream(path);
if (is == null) {
throw new NullPointerException("Cannot find resource file " + path);
}
JSONTokener tokener = new JSONTokener(is);
JSONObject object = new JSONObject(tokener);
// object.getString("darkTheme();");
object.getJSONObject("Theme");
}
catch (Exception e) {
}
}
Can anyone please help me how to do this correctly.
Ok Finally I've got a solution by my own and someone's idea.
I have changed the line in btnDark
json.put("Theme", "darkTheme();");
to
json.put("Theme", "Dark");
and in the readData() method I write like this
private void readData() {
String jsonText;
try {
String path = "resources/config.cfg";
jsonText = IOUtils.toString(new FileInputStream(new File(path)));
int i = jsonText.indexOf("{");
jsonText = jsonText.substring(i);
JSONObject ob = new JSONObject(jsonText);
String Theme = ob.getString("Theme");
if(Theme.equals("Dark")) {
darkTheme();
}
else if(Theme.equals("Light")) {
lightTheme();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
And now it's work perfectly
I have a custom model class like this -
public class MyModel implements Parcelable {
String title;
String message;
/**
* Creator method for the Parcel to use.
*/
public static final Parcelable.Creator<MyModel> CREATOR = new Parcelable.Creator<MyModel>() {
public MyModel createFromParcel(Parcel source) {
return new MyModel(source);
}
public MyModel[] newArray(int size) {
return new MyModel[size];
}
};
public void setTitle(final String titleValue) {
title = titleValue;
}
public void setMessage(final String messageValue) {
message = messageValue;
}
public String getTitle() {
return title;
}
public String getMessage() {
return message;
}
public MyModel() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeString(this.message);
}
private MyModel(Parcel in) {
this.title = in.readString();
this.message = in.readString();
}
}
My JSON in assets folder is -
[
{
"title": "1",
"message": "Hi"
},
{
"title": "2",
"message": "Bye"
},
{
"title": "3",
"message": "Ciao"
}
]
I need to read and parse this JSON and write it as a list of MyModel object into the shared prefs. To write into prefs, I am doing like this -
public void setSteps(final ArrayList<MyModel> steps) {
Gson gson = new Gson();
getPrefs(mContext).edit().putString("steps", gson.toJson(steps)).apply();
}
How can I parse this JSON and write it to the prefs as a list of MyModel object?
The JSON is currently stored in my assets folder.
Later I can read from the prefs and get the list
It's quite simple:
Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);
public ArrayList<MyModel> getSteps(){
String localData = getPrefs(mContext).getString("steps");
return new Gson().fromJson(localData , new TypeToken<ArrayList<MyModel>>(){}.getType());
}
firstly load json data from asset folder to string:
public String loadJSONFromAsset() {
// check here data available in pref or not
// if available then return string object of pref here else fetch //from asset and set into pref
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
this method will return the string json file then pass your string json into this:
Type listType = new TypeToken<ArrayList<ModelClass>>(){}.getType();
List<ModelClass> yourClassList = new Gson().fromJson(yourJsonString, listType);
Write this code read JSON from your asset folder.
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Write this code to read array data from your preference file.
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
...
String jsonArray = getPrefs(mContext).getString("steps","[]").apply();
Type stepType = new TypeToken<ArrayList<YourModelClass>>(){}.getType();
ArrayList<YourModelClass> yourClassList = new Gson().fromJson(jsonArray, stepType);
Let's assume that you have data.json file in data folder in your assets.
just try below code to parse your json.
private void getJsonData()
{
String json = null;
try {
InputStream is = getAssets().open("data/data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
Type listType = new TypeToken<List<MyModel>>(){}.getType();
ArrayList<MyModel> steps = new Gson().fromJson(json, listType);
setSteps(steps);
}
public void setSteps(final ArrayList<MyModel> steps) {
Gson gson = new Gson();
Log.e("~~~~~", gson.toJson(steps));
}
Here is my logcat result :
E/~~~~~: [{"message":"Hi","title":"1"},{"message":"Bye","title":"2"},{"message":"Ciao","title":"3"}]
I am very new to Vaadin, REST and Vertx. I want to post the data into MYSQL db from a JSON file. So I have created a base url "localhost:1443" and am able to call the handler in the other project where db is connected. But don't know to to pass the JSON file my current project to the another project where the MYSQL is configured.
Here am calling the method which is defined in REST,
public OutputStream receiveUpload(String filename, String mimeType) {
FileOutputStream fos = null; // Output stream to write to
file = new
File(VaadinService.getCurrent().getBaseDirectory().getAbsolutePath()
+"/Jsonfile/" + filename);
FILE_PATH =
VaadinService.getCurrent().getBaseDirectory().getAbsolutePath()
+"/Jsonfile/" + filename;
try{
fos = new FileOutputStream(file);
JSONArray products =
productsDataProvider.uploadCatalogs(file.toString());
Notification.show("Succesfully converted :)");
}
catch (final java.io.FileNotFoundException e) {
// Error while opening the file. Not reported here.
e.printStackTrace();
return null;
}
return fos; // Return the output stream to write to
}
this is where I defined method,
public JSONArray uploadCatalogs(String catalogClass) {
return dataProviderUtil.getResourceArray("gapi/upload_products", new
HashMap<String, String>(){
{
put("class", catalogClass);
}
});
This is the product handler in another project,
router.mountSubRouter("/gapi/upload_products", new
UploadCatalog(VertxInstance.get()));
Here the class defined,
public class UploadCatalog extends AbstractRouteHandler {
private final static Logger LOG =
LogManager.getLogger(UploadCatalog.class);
public UploadCatalog(Vertx vertx) {
super(vertx);
this.route().handler(BodyHandler.create());
this.get("/").handler(this::upload);
}
private void upload(RoutingContext routingContext) {
LOG.info("hello");
}
i can see the logger info in console...
I tried the below one,
private void upload(RoutingContext routingContext) {
JsonObject paramsObject = routingContext.getBodyAsJson();
JsonObject result = new JsonObject();
Integer id = LocalCache.getInstance().store(new
QueryData("product.insert", paramsObject));
LOG.info("Executing query:" + "product.insert" );
vertx.eventBus().send(DatabaseService.DB_QUERY, id,
(AsyncResult<Message<Integer>> res) -> {
QueryData resultData = (QueryData)
LocalCache.getInstance().remove(res.result().body());
if (resultData.errorFlag ||
resultData.updateResult.getUpdated() == 0) {
/*result.put("status", "error").put("error", "Error
in creating user profile.");
response.putHeader("content-type",
"application/json").end(result.encode());*/
} else {
/*LOG.info("Insert query (ms):" +
resultData.responseTimeInMillis);
this.sendNewUserProfile(data, response);*/
}
});
}
How to insert data in mysql db from JSON file?
I made class Employee and I also made List<Employee> which accept object from the the class.
I put three objects in that list and I want to save them after close the app. I try to use SharedPreferences to put the list but it seem that SharedPreferences does not accept to put list in it. How can I do it?
#Override
protected void onPause() {
super.onPause();
SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
// I cant use editor to put list<Employee>
}
Shared Preferences takes only string so you can't keep an object into shared preferences. This problem comes if you want to send Employee object from one activity to another activity
This is how i solved it:
Add the following library to your project(take the latest one):
'com.google.code.gson:gson:1.7.2'
You convert the Employee object to string and store in shared preferences:
Gson gson = new Gson();
String jsonString = gson.toJson(employeeObject);
//store this string in shared preferences and next time when you come back
//get string from shared preferences and convert this back to object
Gson gson = new Gson();
Employee example = gson.fromJson(jsonString, Employee.class);
Comment below if you have doubts
This isn't exactly the answer using shared preferences but thought it may help
Serialize an object and pass it around :
I use the code below and then write a class that will have any variables rather than shared preferences that is not dependable.
public class SharedVariables {
public static <S extends Serializable> void writeObject(
final Context context, String key, S serializableObject) {
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = context.getApplicationContext().openFileOutput(key, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(serializableObject);
fileOut.getFD().sync();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
}
}
}
}
public static <S extends Serializable> S readObject(
final Context context, String key, Class<S> serializableClass) {
ObjectInputStream objectIn = null;
try {
FileInputStream fileIn = context.getApplicationContext().openFileInput(key);
objectIn = new ObjectInputStream(fileIn);
final Object object = objectIn.readObject();
return serializableClass.cast(object);
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
} catch (ClassNotFoundException e) {
Log.e("SharedVariable", e.getMessage(), e);
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
}
}
}
return null;
}}
Then example class:
public class Timestamps implements Serializable {
private float timestampServer;
public float getTimestampServer() {
return timestampServer;
}
public void setTimestampServer(float timestampServer) {
this.timestampServer = timestampServer;
}
}
Then in activity:
SharedVariables.writeObject(getApplicationContext(), "Timestamps", timestampsData);
You can't store a list of objects in sharedPrefs, but you can store a Set of String:
#Override
protected void onPause() {
super.onPause();
// Your list of epmloyees
List<Employee> someList;
// The Set to store the converted objects
Set<String> objects = new HashSet<String>();
// Convert each Object into a JSON-String
for (Employee e : someList) {
objects.add(new Gson().toJson(e));
}
SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
// Store the Set of JSON-String into the sharedPrefs
editor.putStringSet("key", objects);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);
// Empty list of employees
List<Employee> someList = new ArrayList<>();
// Set of JSON-Strings from the sharedPrefs
Set<String> objects = data.getStringSet("key", null);
// Convert each JSON-String into an Object of Employee
for (String s : objects) {
objects.add(new Gson().fromJson(s, Employee.class);
}
}
In order to store your custom objects as a string, you need to serialize them (for example as json) and save this string. On loading the value you need to deserialize them.
You can read this guide for advanced help on how to serialize Objects into JSON.
Does anyone know where to find a little how to on using dbpedia spotlight in java or scala? Or could anyone explain how it's done? I can't find any information on this...
The DBpedia Spotlight wiki pages would be a good place to start.
And I believe the installation page has listed the most popular ways (using a jar, or set up a web service) to use the application.
It includes instructions on using the Java/Scala API with your own installation, or calling the Web Service.
There are some additional data needed to be downloaded to run your own server for full service, good time to make a coffee for yourself.
you need download dbpedia spotlight (jar file) after that u can use next two classes ( author pablomendes ) i only make some change .
public class db extends AnnotationClient {
//private final static String API_URL = "http://jodaiber.dyndns.org:2222/";
private static String API_URL = "http://spotlight.dbpedia.org:80/";
private static double CONFIDENCE = 0.0;
private static int SUPPORT = 0;
private static String powered_by ="non";
private static String spotter ="CoOccurrenceBasedSelector";//"LingPipeSpotter"=Annotate all spots
//AtLeastOneNounSelector"=No verbs and adjs.
//"CoOccurrenceBasedSelector" =No 'common words'
//"NESpotter"=Only Per.,Org.,Loc.
private static String disambiguator ="Default";//Default ;Occurrences=Occurrence-centric;Document=Document-centric
private static String showScores ="yes";
#SuppressWarnings("static-access")
public void configiration(double CONFIDENCE,int SUPPORT,
String powered_by,String spotter,String disambiguator,String showScores){
this.CONFIDENCE=CONFIDENCE;
this.SUPPORT=SUPPORT;
this.powered_by=powered_by;
this.spotter=spotter;
this.disambiguator=disambiguator;
this.showScores=showScores;
}
public List<DBpediaResource> extract(Text text) throws AnnotationException {
LOG.info("Querying API.");
String spotlightResponse;
try {
String Query=API_URL + "rest/annotate/?" +
"confidence=" + CONFIDENCE
+ "&support=" + SUPPORT
+ "&spotter=" + spotter
+ "&disambiguator=" + disambiguator
+ "&showScores=" + showScores
+ "&powered_by=" + powered_by
+ "&text=" + URLEncoder.encode(text.text(), "utf-8");
LOG.info(Query);
GetMethod getMethod = new GetMethod(Query);
getMethod.addRequestHeader(new Header("Accept", "application/json"));
spotlightResponse = request(getMethod);
} catch (UnsupportedEncodingException e) {
throw new AnnotationException("Could not encode text.", e);
}
assert spotlightResponse != null;
JSONObject resultJSON = null;
JSONArray entities = null;
try {
resultJSON = new JSONObject(spotlightResponse);
entities = resultJSON.getJSONArray("Resources");
} catch (JSONException e) {
//throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
}
LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
if(entities!=null)
for(int i = 0; i < entities.length(); i++) {
try {
JSONObject entity = entities.getJSONObject(i);
resources.add(
new DBpediaResource(entity.getString("#URI"),
Integer.parseInt(entity.getString("#support"))));
} catch (JSONException e) {
LOG.error("JSON exception "+e);
}
}
return resources;
}
}
second class
/**
* #author pablomendes
*/
public abstract class AnnotationClient {
public Logger LOG = Logger.getLogger(this.getClass());
private List<String> RES = new ArrayList<String>();
// Create an instance of HttpClient.
private static HttpClient client = new HttpClient();
public List<String> getResu(){
return RES;
}
public String request(HttpMethod method) throws AnnotationException {
String response = null;
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
LOG.error("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
} catch (HttpException e) {
LOG.error("Fatal protocol violation: " + e.getMessage());
throw new AnnotationException("Protocol error executing HTTP request.",e);
} catch (IOException e) {
LOG.error("Fatal transport error: " + e.getMessage());
LOG.error(method.getQueryString());
throw new AnnotationException("Transport error executing HTTP request.",e);
} finally {
// Release the connection.
method.releaseConnection();
}
return response;
}
protected static String readFileAsString(String filePath) throws java.io.IOException{
return readFileAsString(new File(filePath));
}
protected static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
#SuppressWarnings("resource")
BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
return new String(buffer);
}
static abstract class LineParser {
public abstract String parse(String s) throws ParseException;
static class ManualDatasetLineParser extends LineParser {
public String parse(String s) throws ParseException {
return s.trim();
}
}
static class OccTSVLineParser extends LineParser {
public String parse(String s) throws ParseException {
String result = s;
try {
result = s.trim().split("\t")[3];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), 3);
}
return result;
}
}
}
public void saveExtractedEntitiesSet(String Question, LineParser parser, int restartFrom) throws Exception {
String text = Question;
int i=0;
//int correct =0 ; int error = 0;int sum = 0;
for (String snippet: text.split("\n")) {
String s = parser.parse(snippet);
if (s!= null && !s.equals("")) {
i++;
if (i<restartFrom) continue;
List<DBpediaResource> entities = new ArrayList<DBpediaResource>();
try {
entities = extract(new Text(snippet.replaceAll("\\s+"," ")));
System.out.println(entities.get(0).getFullUri());
} catch (AnnotationException e) {
// error++;
LOG.error(e);
e.printStackTrace();
}
for (DBpediaResource e: entities) {
RES.add(e.uri());
}
}
}
}
public abstract List<DBpediaResource> extract(Text text) throws AnnotationException;
public void evaluate(String Question) throws Exception {
evaluateManual(Question,0);
}
public void evaluateManual(String Question, int restartFrom) throws Exception {
saveExtractedEntitiesSet(Question,new LineParser.ManualDatasetLineParser(), restartFrom);
}
}
main()
public static void main(String[] args) throws Exception {
String Question ="Is the Amazon river longer than the Nile River?";
db c = new db ();
c.configiration(0.0, 0, "non", "CoOccurrenceBasedSelector", "Default", "yes");
System.out.println("resource : "+c.getResu());
}
I just add one little fix for your answer.
Your code is running, if you add the evaluate method call:
public static void main(String[] args) throws Exception {
String question = "Is the Amazon river longer than the Nile River?";
db c = new db ();
c.configiration(0.0, 0, "non", "CoOccurrenceBasedSelector", "Default", "yes");
c.evaluate(question);
System.out.println("resource : "+c.getResu());
}
Lamine
In the request method of the second class (AnnotationClient) in Adel's answer, the author Pablo Mendes hasn't finished
TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
which is an annoying warning that needs to be removed by replacing
byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
with
Reader in = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
StringWriter writer = new StringWriter();
org.apache.commons.io.IOUtils.copy(in, writer);
response = writer.toString();