firstly, I coded some methods in Main Activity, But I decided they should be a class.
this is my code... openFileOutput and openFileInput are undefined. Any idea?? maybe it should be service or activity...??
package spexco.hus.system;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import spexco.hus.cepvizyon.CepVizyon;
import android.content.Context;
public class LicenseIDB {
private String PHONECODEFILE = "CepVizyonCode";
private static String PhoneCode = null;
public LicenseIDB() {
if (readLocal(PHONECODEFILE, 8) == null)
createSystemCode();
}
public static long getDate() {
Date currentTime = new Date();
return currentTime.getTime();
}
public void createSystemCode() {
long date = getDate();
String str = Integer.toHexString(Integer.MAX_VALUE - (int) date);
for (int i = str.length(); i < 8; i++) {
str += "" + i;
}
PhoneCode = str.substring(0, 8);
saveLocal(PhoneCode, PHONECODEFILE);
}
public static String getPhoneCode() {
return PhoneCode;
}
public void saveLocal(String fileString, String Adress) {
try {
FileOutputStream fos = openFileOutput(Adress, Context.MODE_PRIVATE);
fos.write(fileString.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String readLocal(String Adress, int lenght) {
byte[] buffer = new byte[lenght];
String str = new String();
try {
FileInputStream fis = openFileInput(Adress);
fis.read(buffer);
fis.close();
str = new String(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}
Those are methods defined on the Context class, not methods defined in your class. When your code was part of an Activity, it could use a convenience method openFileInput() in its Activity base class to access the underlying Context.getApplicationContext().openFileInput() (and similarly for openFileOutput()).
Now you'll have to replace those with the direct calls to the underlying Context methods.
Replace
FileOutputStream fos = openFileOutput(Adress, Context.MODE_PRIVATE);
with below line
FileOutputStream fos = getApplicationContext().openFileOutput(filename, getActivity().MODE_PRIVATE);
If used inside Fragment
FileOutputStream fos =getActivity().openFileOutput(filename, getActivity().MODE_PRIVATE);
Related
I am trying to delete a file from storage however when I do it returns true as it's been deleted yet on next boot up reads out the file as if it still exists :/
package com.example.Mazer.Utilities;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import java.io.*;
public class ObjectSaver {
public static void writeObjectToFile(Context c, Object object, String filename) {
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = c.getApplicationContext().openFileOutput(filename, Activity.MODE_WORLD_READABLE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
Log.d("GameActivity", "Can't close objectOut ObjectOutputStream");
}
}
}
}
public static void deleteObjectFromFile(Context c, String filename) {
c.deleteFile( filename);
//NOPE
c.getApplicationContext().deleteFile(filename);
//NOPE
String s = c.getFilesDir().getAbsolutePath() + "/" + filename;
c.deleteFile(s);
//NOPE
}
public static Object readObjectFromFile(Context c, String filename) {
ObjectInputStream objectIn = null;
Object object = null;
try {
FileInputStream fileIn = c.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
// do nowt
}
}
}
return object;
}
}
As you can see I have added a few out of the million approaches I have tried, I have even tried over-writing the file.
I read from the file like so:
maze = (Maze) ObjectSaver.readObjectFromFile(Splash.this, "currentMaze");
and... I save to the file like so..
ObjectSaver.writeObjectToFile(context, new Maze(this), "currentMaze");
This might help:
import java.io.File;
public static void deleteObjectFromFile(Context c, String filename) {
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
}
boolean deleted = false;
File file = new File(selectedFilePath);
if (file.exists())
deleted = file.delete();
where selectedFilePath is the path of the file you want to delete - for example:
/sdcard/MyFolder/example.mp3
I have a log package.I want to filter the log.e, and save it to another file. But I find BufferedWriter can not reach the expected effect. Such as the two lines in log file below can not store another file.
E/Vold ( 96): Sleep 2s to make sure that coldboot() events are handled
E/WindowManager( 244): setEventDispatching false
attach code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSpider {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\log.txt"));
String line = "";
try {
while((line = bufferedReader.readLine())!=null)
{
Parseelog(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line)
{
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\logspider2.txt"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Pattern pattern = Pattern.compile("[\\w[.-]]+\\#[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
while(matcher.find())
{
String string = new String(matcher.group());
string += "\n";
System.out.println(string); //here can print the search results
try {
bufferedWriter.write(string, 0, string.length());
bufferedWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
The problem with you code was that you where opening the logspider2.txt file every time you want to write the matching line. So it was overwriting all the previous data. To solve the issue you need to open your file in the append mode as follows:
bufferedWriter = new BufferedWriter(
new FileWriter(
"F:\\praful\\androidworkspace_2\\Test\\src\\logspider2.txt",true));
I tried you code and made some modification to make it work. Following is the working code:
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(
"F:\\praful\\androidworkspace_2\\Test\\src\\logs.txt"));
String line = "";
try {
while ((line = bufferedReader.readLine()) != null) {
Parseelog(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line) {
BufferedWriter bufferedWriter = null;
// Pattern pattern =
// Pattern.compile("[\\w[.-]]+\\#[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
try {
bufferedWriter = new BufferedWriter(
new FileWriter(
"F:\\praful\\androidworkspace_2\\Test\\src\\logspider2.txt",true));
while (matcher.find()) {
String string = new String(matcher.group());
string += "\n";
System.out.println(string); // here can print the search results
bufferedWriter.write(string);
}
bufferedWriter.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Please changed the file path to your local paths. Hope it help you..
I'm trying to permanently store three strings as user preferences for my Android application. These three strings are a url, username, and password. I don't really understand SharedPreferences, so I tried to use internal file storage. I'm not able to retrieve the three strings from the file, and I get a runtime error. I know I probably coded something wrong, but I'm just not proficient enough in Android to understand data storage. Could somebody help me out?
Preferences activity:
package com.amritayalur.mypowerschool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
FileOutputStream fos;
String url = "";
String FILENAME = "InternalStrings";
String str;
String username;
String password;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
textViewTitle = (TextView) findViewById(R.id.textViewTitle);
textViewDesc = (TextView) findViewById(R.id.textViewDesc);
editTextURL = (EditText) findViewById(R.id.editTextURL);
editTextUser = (EditText) findViewById(R.id.editTextUser);
editTextPass = (EditText) findViewById(R.id.editTextPass);
//Start TextView
textViewTitle.setText("MyPowerSchool");
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//button listener
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if ( ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) )
{
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
//Saving data via File
/* File f = new File(FILENAME);
try {
fos = new FileOutputStream(f);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(url.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(username.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(password.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);
//i.putExtra("pschoolurl", editTextURL.getText().toString());
//i.putExtra("pschooluser", editTextUser.getText().toString());
//i.putExtra("pschoolpass", editTextPass.getText().toString());
// get the text here
final int result = 1;
startActivityForResult(i, result);
}
};
});}}
Activity in which I am trying to retrieve credentials:
package com.amritayalur.mypowerschool;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class creds extends Activity {
String url;
String username;
String password;
TextView TextViewTest;
String FILENAME = "InternalStrings";
;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent intent = getIntent();
//String url = intent.getExtras().getString("pschoolurl");
//String username = intent.getExtras().getString("pschooluser");
//String password = intent.getExtras().getString("pschoolpass");
String collected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1 ){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
TextViewTest.setText(collected);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The commented text is a result of me trying to mess around with different aspects of the code.
SharedPreferences is not too difficult.
To add something to the preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
Editor edit = prefs.edit(); //Needed to edit the preferences
edit.putString("name", "myname"); //add a String
edit.putBoolean("rememberCredentials", true); //add a boolean
edit.commit(); // save the edits.
To read something:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
String name = prefs.getString("name", "defaultName"); //get a String
boolean rememberCredentials = prefs.getBoolean("rememberCredentials", true); //get a boolean.
//When the key "rememberCredentials" is not present, true is returned.
I am an android newbie and wrote this code for file handling but for some reason i am always getting back null values from the file. I also tried using readline() but got the same result. Would appreciate any help.
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String file = "test123";
try
{
OutputStream out = v.getContext().openFileOutput(file, MODE_PRIVATE);
InputStream in = v.getContext().openFileInput(file);
WriteFile(out);
String str = ReadFile(in);
Toast.makeText(v.getContext(), str, Toast.LENGTH_LONG);
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public static void WriteFile(OutputStream out)
{
OutputStreamWriter tmp = new OutputStreamWriter(out);
try
{
for (int i = 0 ; i < 10; i++)
{
tmp.write(i);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String ReadFile(InputStream in)
{
InputStreamReader tmp = null;
String str = "";
tmp = new InputStreamReader(in);
BufferedReader reader=new BufferedReader(tmp);
try
{
for (int i = 0; i < 10; i++)
{
str += " " + reader.readLine();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}
String file = "test123";
So, the path of your file should be {root}/test123
Try defining a path were you can access to see if it has written something. (usually : /mnt/storage/your_file)
Then, you'll be able to determine if the Write/Read process works or not
Note : Take a look at FileOutputStream, it already implements lots of useful methods
I am an amateur programmer developing for android. I am just trying get the basics down right now, but I am having an error and I don't know why.
I am creating a activity that has a save and a load button, which using the fileOutputStream and fileInputStream to achieve this task.
The problem I am having is if I hit the load button the first time I use the activity, my application crashes. Can anyone help me with how to skip the load section if the file hasn't been created yet? What should I use within my if statement.
Thanks a ton, here is my code:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class InternalData extends Activity implements OnClickListener {
String FILENAME = "InternalString";
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String d;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (EditText) findViewById(R.id.etSharedPrefs);
dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
save.setOnClickListener(this);
load.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSave:
d = sharedData.getText().toString();
try {
fos.write(d.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.bLoad:
FileInputStream fis = null;
try {
if (openFileInput(FILENAME) != null){
fis = openFileInput(FILENAME);
byte[] data = new byte[fis.available()];
while(fis.read(data) != -1){
String readData = new String(data);
dataResults.setText(readData);
}}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
}
Thanks for the help Lukas, I have updated my code, and I was wondering if you could look it over to make sure I am using the AsyncTask properly. Thanks again!
public class InternalData extends Activity implements OnClickListener {
String FILENAME = "InternalString";
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String d;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (EditText) findViewById(R.id.etSharedPrefs);
dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
save.setOnClickListener(this);
load.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSave:
d = sharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(d.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.bLoad:
AsyncTask<String, Integer, String> dat = new loadInternalData().execute(FILENAME);
break;
}
}
public class loadInternalData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput(FILENAME);
byte[] data = new byte[fis.available()];
while (fis.read(data) != -1){
collected = new String(data);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
return collected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return collected;
}
#Override
protected void onPostExecute( String result )
{
super.onPostExecute(result);
Log.i( "InteralStorage", "onPostExecute(): " + result );
dataResults.setText( result );
}
}
}
You are calling openFileInput twice. Just call it once.
Instead of this
if (openFileInput(FILENAME) != null){
fis = openFileInput(FILENAME);
}
Do this:
fis = openFileInput(FILENAME);
if (fis != null) {
// Read file
}
If you execute something on the UI-Thread, it shouldn't take longer then 5 seconds or an ANR will be triggered.
If you want to do something that might take longer then those 5 seconds, you'll want to do it in a Service or an AsyncTask.
Also, if your App gets force closed and you don't know why, you should always have a look at the LogCat output which can be shown in Eclipse. Also, you should include it with every question you ask here (about Android).