How to load saved item from JSON file in java - java

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

Related

Overwrite json file after exiting app and relaunching

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);

Insert 360° metadata to mp4 file in java

I'm trying to add 360° metadata to a mp4 file with this library : https://github.com/copiousfreetime/mp4parser
after have check the code, i had created this :
public void injectSphericalMetaV2(TrackBox trackBox) throws IOException {
String sphericalVideoGlobalMetadata = "<rdf:SphericalVideo xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"xmlns:GSpherical=\"http://ns.google.com/videos/1.0/spherical/\"><GSpherical:Spherical>true</GSpherical:Spherical><GSpherical:Stitched>true</GSpherical:Stitched><GSpherical:StitchingSoftware>GIROPTIC 360 CAM</GSpherical:StitchingSoftware><GSpherical:ProjectionType>equirectangular</GSpherical:ProjectionType></rdf:SphericalVideo>";
String UUID_ID = "FFCC8263-F855-4A93-8814-587A02521FDD";
UserBox sphericalAtom = new UserBox(UUID_ID.getBytes());
sphericalAtom.setData(sphericalVideoGlobalMetadata.getBytes());
trackBox.addBox(sphericalAtom);
}
and i execute it here :
protected TrackBox createTrackBox(Track track, Movie movie, Map<Track, int[]> chunks) {
TrackBox trackBox = new TrackBox();
TrackHeaderBox tkhd = new TrackHeaderBox();
tkhd.setEnabled(true);
tkhd.setInMovie(true);
tkhd.setMatrix(track.getTrackMetaData().getMatrix());
tkhd.setAlternateGroup(track.getTrackMetaData().getGroup());
tkhd.setCreationTime(track.getTrackMetaData().getCreationTime());
if (track.getEdits() == null || track.getEdits().isEmpty()) {
tkhd.setDuration(track.getDuration() * getTimescale(movie) / track.getTrackMetaData().getTimescale());
} else {
long d = 0;
for (Edit edit : track.getEdits()) {
d += (long) edit.getSegmentDuration();
}
tkhd.setDuration(d * track.getTrackMetaData().getTimescale());
}
tkhd.setHeight(track.getTrackMetaData().getHeight());
tkhd.setWidth(track.getTrackMetaData().getWidth());
tkhd.setLayer(track.getTrackMetaData().getLayer());
tkhd.setModificationTime(new Date());
tkhd.setTrackId(track.getTrackMetaData().getTrackId());
tkhd.setVolume(track.getTrackMetaData().getVolume());
trackBox.addBox(tkhd);
trackBox.addBox(createEdts(track, movie));
MediaBox mdia = new MediaBox();
trackBox.addBox(mdia);
MediaHeaderBox mdhd = new MediaHeaderBox();
mdhd.setCreationTime(track.getTrackMetaData().getCreationTime());
mdhd.setDuration(track.getDuration());
mdhd.setTimescale(track.getTrackMetaData().getTimescale());
mdhd.setLanguage(track.getTrackMetaData().getLanguage());
mdia.addBox(mdhd);
HandlerBox hdlr = new HandlerBox();
mdia.addBox(hdlr);
hdlr.setHandlerType(track.getHandler());
MediaInformationBox minf = new MediaInformationBox();
if (track.getHandler().equals("vide")) {
try {
injectSphericalMetaV2(trackBox);
} catch (IOException e) {
e.printStackTrace();
}
minf.addBox(new VideoMediaHeaderBox());
} else if (track.getHandler().equals("soun")) {
minf.addBox(new SoundMediaHeaderBox());
} else if (track.getHandler().equals("text")) {
minf.addBox(new NullMediaHeaderBox());
} else if (track.getHandler().equals("subt")) {
minf.addBox(new SubtitleMediaHeaderBox());
} else if (track.getHandler().equals("hint")) {
minf.addBox(new HintMediaHeaderBox());
} else if (track.getHandler().equals("sbtl")) {
minf.addBox(new NullMediaHeaderBox());
}
// dinf: all these three boxes tell us is that the actual
// data is in the current file and not somewhere external
DataInformationBox dinf = new DataInformationBox();
DataReferenceBox dref = new DataReferenceBox();
dinf.addBox(dref);
DataEntryUrlBox url = new DataEntryUrlBox();
url.setFlags(1);
dref.addBox(url);
minf.addBox(dinf);
Box stbl = createStbl(track, movie, chunks);
minf.addBox(stbl);
mdia.addBox(minf);
LOG.logDebug("done with trak for track_" + track.getTrackMetaData().getTrackId());
return trackBox;
}
these 2 methods are in my MP4BuilderV2 and i call it here a TrimActivity like this :
Container out = new DefaultMp4BuilderV2().build(movie);
MovieHeaderBox mvhd = Path.getPath(out, "moov/mvhd");
mvhd.setMatrix(Matrix.ROTATE_180);
if (!dst.exists()) {
dst.createNewFile();
} else {
dst.delete();
dst.createNewFile();
}
FileOutputStream fos = new FileOutputStream(dst);
WritableByteChannel fc = fos.getChannel();
try {
out.writeContainer(fc);
}catch (Exception e) {
Log.e("erreur", e.toString());
}finally {
fc.close();
fos.close();
file.close();
}
file.close();
But in the last try/catch i get this error : java.nio.BufferOverflowException
If someone has the solution thanks in advance
I was with the same problem as you, searching for a solution I found a meta tag insertion implementation that worked for me, maybe it helps you.

Boolean From Text File Online

I want to read from a text file online, then check for a boolean within the first line of the text file. I'm using this to check for updates for an application.
Here's an idea -
public static boolean needsUpdate()
{
URL url;
boolean needs = false;
try
{
url = new URL("https://github.com/../../blob/master/update.txt");
Scanner s = new Scanner(url.openStream());
boolean getUpdate = s.hasNextBoolean();
if (getUpdate = true)
{
needs = true;
}
else
{
needs = false;
}
}
catch (IOException e)
{
e.printStackTrace();
}
return needs;
}
The text inside the file is update = false or update = true.
Do it like that:
try {
URL url = new URL("https://github.com/../../blob/master/update.txt");
Scanner s = new Scanner(url.openStream());
String text = s.nextLine();
s.close();
text = text.replaceAll("update = ", "");
Boolean getUpdate = Boolean.parseBoolean(text);
//do something with the boolean
} catch(Exception ex) {
ex.printStackTrace();
}

Create Database on SD Card From File

I'm working with Android and I'm trying to use a database I already have. I'd like to put it on the SD card. I have the database file in my project's assets folder. How can I make it on the SD card or external storage of whatever device the app is installed on?
//Step1 : Checked accessiblity on sd card
public boolean doesSDCardAccessible(){
try {
return(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}
//Step2 : create directory on SD Card
//APP_DIR : your PackageName
public void createAndInitAppDir(){
try {
if(doesSDCardAccessible()){
AppDir = new File(Environment.getExternalStorageDirectory(),APP_DIR+"/");
if(!AppDir.exists()){
AppDir.mkdirs();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//Step 3 : Create Database on sdcard
//APP_DIR : your PackageName
//DATABASE_VERSION : give Database Vesrion
//DATABASE_NAME : your Databsename Name
public void initDB()
{
try {
//Using SQLiteHelper Class Created Database
sqliteHelper = new SQLiteHelper(Application.this,AppDir.getAbsolutePath()+"/"+DATABASE_NAME,
null, DATABASE_VERSION);
//OR use following
//Creating db here. or db will be created at runtime whenever writable db is opened.
db = SQLiteDatabase.openOrCreateDatabase(AppDir.getAbsolutePath()+"/"+DATABASE_NAME, null);*/
db= sqliteHelper.getWritableDatabase();
db.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
In reference to this answer, you can find the directory of the SD card in Android 4.0+ by trying both of the following (only one should work per device):
new File("/mnt/external_sd/");
or
new File("/mnt/extSdCard/");
On Android <4.0, you can use
Environment.getExternalStorageDirectory();
You can create your SQLite database there. Additionally, if you can't find it, you can iterate over all directories in /mnt/ (note: the sdcard will always be accessible via /mnt/).
Go throuh this link
OR try following
InputStream myInput;
try {
AssetManager assetManager = getAssets();
myInput = assetManager.open("mydatabase.db");
File directory = new File("/sdcard/some_folder");
if (!directory.exists()) {
directory.mkdirs();
}
OutputStream myOutput = new FileOutputStream(directory
.getPath() + "/DatabaseSample.backup");
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The database is like any other flat file. Just copy it to your SD card.
public boolean backup()
{
File sdcard = Environment.getExternalStorageDirectory();
File data = new File("/data/data/com.mydomain.myappname/databases/");
if (sdcard.canWrite())
{
File input = new File(data, DB_NAME);
File output = new File(sdcard, "android/data/com.mydomain.myappname/databases/");
if(!output.exists())
{
if(output.mkdirs())
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
output.createNewFile();
result = true;
}
else
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
result = true;
}
if(input.exists() && result)
{
FileInputStream source;
FileOutputStream destination;
try
{
source = new FileInputStream(input);
try
{
destination = new FileOutputStream(output);
byte[] buffer = new byte[1024];
int length;
while((length = source.read(buffer)) > 0)
{
destination.write(buffer, 0, length);
}
source.close();
destination.flush();
destination.close();
result = true;
}
catch(Exception e)
{
result = false;
destination = null;
}
}
catch(Exception e)
{
result = false;
source = null;
}
}
else
{
result = false;
}
}
else
{
result = false;
}
}
catch(Exception e)
{
result = false;
}
return result;
}

Do Not Crawl certain page in a particular link(exclude certain url from crawling)

This is the below code in my MyCrawler.java and it is crawling all those links that I have provided in href.startsWith but suppose If I do not want to crawl this particular page http://inv.somehost.com/people/index.html then how can I do this in my code..
public MyCrawler() {
}
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
if (href.startsWith("http://www.somehost.com/") || href.startsWith("http://inv.somehost.com/") || href.startsWith("http://jo.somehost.com/")) {
//And If I do not want to crawl this page http://inv.somehost.com/data/index.html then how it can be done..
return true;
}
return false;
}
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String text = page.getText();
List<WebURL> links = page.getURLs();
int parentDocid = page.getWebURL().getParentDocid();
try {
URL url1 = new URL(url);
System.out.println("URL:- " +url1);
URLConnection connection = url1.openConnection();
Map responseMap = connection.getHeaderFields();
Iterator iterator = responseMap.entrySet().iterator();
while (iterator.hasNext())
{
String key = iterator.next().toString();
if (key.contains("text/html") || key.contains("text/xhtml"))
{
System.out.println(key);
// Content-Type=[text/html; charset=ISO-8859-1]
if (filters.matcher(key) != null){
System.out.println(url1);
try {
final File parentDir = new File("crawl_html");
parentDir.mkdir();
final String hash = MD5Util.md5Hex(url1.toString());
final String fileName = hash + ".txt";
final File file = new File(parentDir, fileName);
boolean success =file.createNewFile(); // Creates file crawl_html/abc.txt
System.out.println("hash:-" + hash);
System.out.println(file);
// Create file if it does not exist
// File did not exist and was created
FileOutputStream fos = new FileOutputStream(file, true);
PrintWriter out = new PrintWriter(fos);
// Also could be written as follows on one line
// Printwriter out = new PrintWriter(new FileWriter(args[0]));
// Write text to file
Tika t = new Tika();
String content= t.parseToString(new URL(url1.toString()));
out.println("===============================================================");
out.println(url1);
out.println(key);
//out.println(success);
out.println(content);
out.println("===============================================================");
out.close();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// http://google.com
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("=============");
}
And this is my Controller.java code from where MyCrawler is getting called..
public class Controller {
public static void main(String[] args) throws Exception {
CrawlController controller = new CrawlController("/data/crawl/root");
controller.addSeed("http://www.somehost.com/");
controller.addSeed("http://inv.somehost.com/");
controller.addSeed("http://jo.somehost.com/");
controller.start(MyCrawler.class, 20);
controller.setPolitenessDelay(200);
controller.setMaximumCrawlDepth(2);
}
}
Any suggestions will be appreciated..
How about adding a property to tell which urls you want to exclude.
Add to your exclusions list all the pages that you don't want them to get crawled.
Here is an example:
public class MyCrawler extends WebCrawler {
List<Pattern> exclusionsPatterns;
public MyCrawler() {
exclusionsPatterns = new ArrayList<Pattern>();
//Add here all your exclusions using Regular Expresssions
exclusionsPatterns.add(Pattern.compile("http://investor\\.somehost\\.com.*"));
}
/*
* You should implement this function to specify
* whether the given URL should be visited or not.
*/
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
//Iterate the patterns to find if the url is excluded.
for (Pattern exclusionPattern : exclusionsPatterns) {
Matcher matcher = exclusionPattern.matcher(href);
if (matcher.matches()) {
return false;
}
}
if (href.startsWith("http://www.ics.uci.edu/")) {
return true;
}
return false;
}
}
In this example we are telling that all urls that start with http://investor.somehost.com should not be crawled.
So these wont be crawled:
http://investor.somehost.com/index.html
http://investor.somehost.com/something/else
I recommend you reading about regular expresions.

Categories

Resources