I am trying to store the json data to the file.This is the code for creating directories and file.
public void filecreation() throws IOException {
File mediaStorageDir = new File(getActivity().getFilesDir() + "/" +
"Zerribelum");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory");
// return null;
} else {
Log.d("Apppppp", "create directory");
File textfolder = new File(mediaStorageDir, "Text");
if (!textfolder.exists()) {
textfolder.mkdirs();
File newtext = new File(textfolder, "dummy.txt");
stream = new FileOutputStream(newtext);
bw = new BufferedWriter(new OutputStreamWriter(stream));
}
File imagefolder = new File(mediaStorageDir, "Image");
if (!imagefolder.exists()) {
imagefolder.mkdirs();
}
File videofolder = new File(mediaStorageDir, "Video");
if (!videofolder.exists()) {
videofolder.mkdirs();
}
}
}
}
I want put the json data to the file.
try {
JSONArray mJsonTopicArray = mJsonObject.getJSONArray(AppConstants.APIKeys.TOPICS_LIST);
for (int i = 0; i < mJsonTopicArray.length(); i++) {
Topics mTopics = new Topics();
mTopics.setId(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.ID));
mTopics.setTitle(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS));
mTopics.setImage(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS_IMAGE));
mTopics.setDescription(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.DESCRIPTION));
mTopicsArrayList.add(mTopics);
bw.write(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.DESCRIPTION));
bw.newLine();
}
bw.close();
mCategoryListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mCategoryListRecyclerView.setHasFixedSize(true);
mCategoryListRecyclerView.setAdapter(new ParallaxRecyclerAdapter(context, HomeFragment.this, mTopicsArrayList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
The probelm is if I have'nt add bw.write and bw.close() lines the data will display in recyclerview. But when I add this lines, data is adding to file but not showing in recylcer view. I want both to be done. What will be the problem?
Note: public FileOutputStream stream;
public BufferedWriter bw; Initialised.
Check your stacktrace, your code must be crashing and you arent noticing it because of try catch
Attach a debugger and check the items in the arraylist once the adapter is initialized. If items are present it will work
solved,the issue is because of Nullpointer Exception.So handled using try catch.
try {
bw.write(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS));
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Related
I'm using FileWrite class to Write into a file.and its working fine. But FindBugs is pointing me a Minor issue in my code snippet.
code snippet:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";
FileWriter writer = null;
try {
File root = new File(Environment.getExternalStorageDirectory(), "Test");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, fileName);
writer = new FileWriter(gpxfile, true);
writer.append(text + "\n\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Findbug Report:
OBL_UNSATISFIED_OBLIGATION: Method may fail to clean up stream or resource
writeDataToFile(String) may fail to clean up java.io.Writer on checked exception
In which line i'm getting this Error?
writer = new FileWriter(gpxfile, true);
Could some one please brief me what is this exactly?
And how can we solve this?
You are getting this error because of writer.flush();. This could lead to IOException since it writes any buffered output to the underlying stream. If the exception occurs the writer won't be closed.
If its mandatory to flush in finally{..} then use dedicated try{..} catch{..} for each line as follows:
finally {
if (writer != null) {
try {
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.
I have created a ListView and it can add data dynamically but whenever I restart the App the previous stored list is lost.
How can I save that list ?
You can save them into client local via using android SharedPreferences
Or, you can write your own model.
You should pass your object here;
public boolean writeYourObjectOnLocal(File dir, YourObject yourObject) {
ObjectOutput output = null;
OutputStream buffer = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(dir.toString() + File.separator + "myFile.dat");
buffer = new BufferedOutputStream(fileOutputStream);
output = new ObjectOutputStream(buffer);
output.writeObject(yourObject);
return true;
} catch (Throwable e) {
return false;
} finally {
try {
output.close();
} catch (Throwable e) {}
try {
buffer.close();
} catch (Throwable e) {}
try {
fileOutputStream.close();
} catch (Throwable e) {}
}
}
You can Read your object;
public YourObject readYourObjectFromLocal(File dir) {
ObjectInput input = null;
BufferedInputStream buffer = null;
FileInputStream fileInputStream = null;
try {
String fileName = dir.toString() + File.separator + "myFile.dat";
fileInputStream = new FileInputStream(fileName);
buffer = new BufferedInputStream(fileInputStream);
input = new ObjectInputStream(buffer);
return (YourObject)input;
} catch (Throwable e) {
return null;
} finally {
try {
input.close();
} catch (Throwable e) {
}
try {
fileInputStream.close();
} catch (Throwable e) {
}
try {
buffer.close();
} catch (Throwable e) {
}
}
}
I would recommend you to use caching library like Reservoir. Check instructions how to use it on this link.
https://github.com/anupcowkur/Reservoir
Be sure to allocate enough memory in your application class (size in bytes).
Example: Save data (Async):
// it can be any type of object (here is String)
List<String> strings = new ArrayList<String>();
strings.add("one");
strings.add("two");
strings.add("three");
Reservoir.putAsync("myListKey", strings, new ReservoirPutCallback() {
#Override
public void onSuccess() {
//success
}
#Override
public void onFailure(Exception e) {
//error
}
});
Example: Read saved data (Async):
Reservoir.getAsync("myListKey", new TypeToken<List<String>>() {}.getType(),
new ReservoirGetCallback<List<String>>() {
#Override
public void onSuccess(List<String> strings) {
//success - set your list adapter and show those items
}
#Override
public void onFailure(Exception e) {
//error
}
});
If you need to persist large volume of data you should use SQLite database and it is best for this purpose. But you can also use xml to store your data, xml is slow then SQLite database.
You can refer this standard Storage options.
I have to open a file that in the /res/raw/ folder, but it seems that android, doesn't recognize the path.
Here is my code:
public static void openRec()
{
//this is the wav file that I have to analyze
File file = new File("/res/raw/chirp.wav");
try {
FileInputStream in = new FileInputStream(file);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT:
I have another method openRec in which, the path is passed as argument:
public static void openRec(String path) {
File file = new File(path);
try {
FileInputStream in = new FileInputStream(file);
recording = new byte[(int) file.length()];
in.read(recording);
Log.d("xxx", "" + recording.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I would a method that do the same thing but with the ffile in /res/raw. How do I that?
Use in this manner
public static void openRec()
{
//this is the wav file that I have to analyze
try {
InputStream in = getResources().openRawResource(R.raw.chirp);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
What I am trying to do is store a JSON file as a string in internal storage to access it later. The reasoning behind this is to not have to access the server on every request, as this data is constant. Once it is stored once, it doesn't have to be retrieved again unless there is some sort of update. File storage isn't something I've done before, and I was hoping someone could give me a hand. My current code is throwing a null pointer exception at this line:
File file = new File(getFilesDir(), fileName);
My code:
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" + runeId[0] + "?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String fileName = "runeInfo";
File file = new File(getFilesDir(), fileName);
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileOutputStream os = new FileOutputStream(file);
os.write(jsonString.getBytes());
os.close();
Log.d("Cache", "Cache Complete");
runesCached = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
try {
FileInputStream fis;
File storedRuneInfo = new File(getFilesDir(), fileName);
fis = new FileInputStream(storedRuneInfo);
fis.read(readJson.getBytes());
JSONObject storedJson = new JSONObject(readJson);
try {
name = storedJson.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
}
Try this, instead:
File file = new File(getFilesDir().toString(), fileName);
getFilesDir() returns a File, not a String, which the File class constructor takes as a parameter.
getFilesDir()toString() should return something like /data/data/com.your.app/
EDIT:
This gives the same error. How about:
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "filename");
out = new BufferedWriter(fstream);
out.write(jsonString.getBytes());
out.close();
} catch (Exception e){}