I have two classes/Activities:
FirstClass:
public class FirstClass extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void addData(String filename, String data); {
SecondClass second = new SecondClass();
second.save(name, data);
}
}
SecondClass:
public class SecondClass extends Activity {
public void save(String filename, String data) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
As you can see, what I want to do is to call a method from SecondClass in FirstClass. The method savse some data to the internal storage.
What is the correct way of doing this? I know i should probably do something with Context, but i don't know what exactly.
Make it as a simple java class.
public class ThirdClass
{
public void save(String filename, String data, Context context)
{
try {
FileOutputStream fos = context.openFileOutput(filename,Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Call this method like in your First Activity.
ThirdClass third= new ThirdClass();
third.save(name, data,this);
Alternative If you don't want to make the Third class and want to do with SecondClass. Then make this save method to static.
public class SecondClass extends Activity
{
//Oncreate method....
public static void save(String filename, String data)
{
try {
FileOutputStream fos = openFileOutput(filename,Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and Call this method from First Activity.
SecondClass.save(name, data);
make save a static method and/or move it to its own static class (not activity).
So you can call it using the following:
SecondClass.save(name, data);
and define it as the following:
public static void save(String filename, String data)
{
You should create a class named something like SaveHelper, that doesn't extend activity and add a static method so you can do:
FileHelper.save(...)
public class FileHelper {
public static void save(Context context, String filename, String data) {
try {
FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
I'm currently learning about IO and Async but am having issues. I'm following a guide, and according to the guide this is supposed to work. I have created an activity with a simple EditText, TextView, and 2 Buttons(save and load). I am trying to have the save button take the text in the EditText and save to internal storage, and the load button take whatever is saved and set the TextView as that. Everything works flawlessly when I put all the code to run in the UI thread, but if I change the code to have the UI thread call the Async class for the loading, nothing seems to happen.
**Packages and imports have been removed to save space.
public class InternalData extends Activity implements OnClickListener {
EditText etSharedData;
TextView tvDataResults;
FileOutputStream fos;
String FILENAME = "InternalString";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
setupVariables();
}
private void setupVariables() {
Button bSave = (Button) findViewById(R.id.bSave);
Button bLoad = (Button) findViewById(R.id.bLoad);
etSharedData = (EditText) findViewById(R.id.etSharedPrefs);
tvDataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
bSave.setOnClickListener(this);
bLoad.setOnClickListener(this);
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();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSave:
String sData = etSharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(sData.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.bLoad:
String sCollected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
sCollected = 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();
tvDataResults.setText(sCollected);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
The previous code makes everything work, but the UI lags a bit when trying to load large strings. When I try to have an LoadSomeStuff(Async) class do the loading, it does absolutely nothing when I hit Load on my phone. Within the LoadSomeStuff class it has the doInBackground method open the file and read the data into a string then return that string, and the onPostExecute method set the TextView's text to the returned String. Here's the code:
The onClick method for load button has:
new LoadSomeStuff().execute(FILENAME);
LoadSomeStuff Class *Note: This class is declared within the InternalData class.
public class LoadSomeStuff extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String sCollected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
sCollected = 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();
return sCollected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
tvDataResults.setText(result);
}
}
}
Any help is greatly appreciated, thanks!
It actually looks like I had an extra method or two(like onPreExecute) with no code in them and when I deleted them it starting working.
I'm trying to serlize an Enum Class so I can restore in in onCreate() method so each run I have an updated class.
Here is the code for serlizing and deserializing the class:
private void serializeModulesManager() {
try {
FileOutputStream fos = openFileOutput("modules.ser",
Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(Module.values());
out.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void restoreModulesManager() {
FileInputStream fileIn;
Module[] arr = null;
try {
fileIn = openFileInput("modules.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
arr = (Module[]) in.readObject();
for (Module c : arr) {
Module.valueOf(c.name()).serilize(c);
}
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I call serializeModulesManager() in onDestroy() , and I call restoreModulesManager() in onCreate()..
The problem is that when I force close (from task manager), ObjectInputStream fails to read the object and I get an "EOFException"..
How can I fix this?
Here is how i would handle this. This is a simple object with only a title field but you can use this same idea for more complicated objects
public class MyObject implements Parcelable{
public String title;
public MyObject(){}
public MyObject(Parcel source){
title = source.readString();
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
// Parcel Overrides
#Override
public int describeContents(){return 0;}
#Override
public void writeToParcel(Parcel dest, int flags){
dest.writeString(title);
}
// Parcelable Creator
public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>(){
#Override
public MyObject createFromParcel(Parcel source){
return new MyObject(source);
}
#Override
public MyObject [] newArray(int size){
return new MyObject[size];
}
}
}
And then in your class that instantiates the object
// Add this in onSavedInstanceState(Bundle outState)
outState.putParcelableArray("MyObjectArray",myObjects);
then in OnCreate or whichever method your using to restore UI
// Add this
myObjects = (MyObject [])savedInstanceState.getParcelableArray("MyObjectArray");
I am using FTP to upload a file. This works great. This file contains information what the app should do.
So I am doing the following:
1) Download the file with Apache FTP Client (seems to work fine)
2) Try to read out the file with a BufferedReader and FileReader.
The problem:
I get a NullPointerException while reading the file. I guess that this is a timing problem.
The code has this structure:
...
getFile().execute();
BufferedReader br = new BufferedReader(...);
How can I solve this problem?
I have to use a seperate Thread (AsyncTask) to download the file because otherwise it will throw a NetworkOnMainThread Exception.
But how can I wait until the file is completely downloaded without freezing the UI?
I cannot use the BufferedReader inside AsyncTask because I use GUI elements and I have to run the interactions on the GUI Thread, but I have no access to it from AsyncTask. RunOnUiThread does not work as well because I am inside a BroadcastReceiver.
Some code:
private class GetTask extends AsyncTask{
public GetTask(){
}
#Override
protected Object doInBackground(Object... arg0) {
FTPClient client = new FTPClient();
try {
client.connect("*****");
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
client.login("*****", "*****");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream( "/sdcard/"+userID+".task" );
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
resultOk &= client.retrieveFile( userID+".task", fos );
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}/**
try {
client.deleteFile(userID+".task");
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
**/
try {
client.disconnect();
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
return null;
}
}
The Broadcastreceiver class:
public class LiveAction extends BroadcastReceiver {
...
private Context cont;
FileReader fr = null;
BufferedReader br;
#Override
public void onReceive(Context context, Intent intent)
{
cont = context;
...
new GetTask().execute();
try {
Thread.sleep(3000);
}
catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fr = new FileReader("/sdcard/"+userID+".task");
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
br = new BufferedReader(fr)
String strline = "";
try {
while ((strline = br.readLine()) != null){
if(strline.equals("taskone")){
//Some GUI Tasks
}
....
This is the relevant code.
I think the best approach would be to read the file's contents from the doInBackground inside the AsyncTask and then output an object which contains the info you need on the onPostExecute method of the async stask and then manipulate your UI.
private AsyncTask<String,Void,FileInfo> getFile(){
return new AsyncTask<String,Void,FileInfo>{
protected FileInfo doInBackground(String url){
FileInfo finfo = new FileInfo(); // FileInfo is a custom object that you need to define that has all the stuff that you need from the file you just downloaded
// Fill the custom file info object with the stuff you need from the file
return finfo;
}
protected void onPostExecute(FileInfo finfo) {
// Manipulate UI with contents of file info
}
};
}
getFile().execute();
Another option is to call another AsyncTask from onPostExecute that does the file parsing but I would not recommend it
I would try some thing like this:
private class GetTask extends AsyncTask{
LiveAction liveAction;
public GetTask(LiveAction liveAction){
this.liveAction = liveAction;
}
...
#Override
protected void onPostExecute(String result) {
liveAction.heyImDoneWithdownloading();
}
}
Ps: why the Thread.sleep(5000)?
public class LiveAction extends BroadcastReceiver {
...
public void heyImDoneWithdownloading(){
//all the things you want to do on the ui thread
}
}
I have a class that contains 2 functions:
public class FileHandler extends Activity {
public void writeToFile(){
String fileName = "lastDevice.txt";
try {
FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE); //Exception thrown here
fos.write("some device id".getBytes());
fos.close();
Toast.makeText(this, "File updated", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String readFromFile(){
try {
String fileName = "lastDevice.txt";
FileInputStream fis = openFileInput(fileName); //Exception thrown here
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String sLine = null;
String data ="";
while ((sLine = br.readLine())!=null) {
data+= sLine;
}
return data;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "FileNotFoundException";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "IOException";
} catch (NullPointerException e){
// TODO Auto-generated catch block
e.printStackTrace();
return "Null Pointer Exception";
}
}
these functions are called from my main activity as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvDevices = (ListView)findViewById(R.id.ListViewDevices);
lastDeviceTxt = (TextView)findViewById(R.id.lastDeviceTxt);
//get last connected device
FileHandler fh = new FileHandler();
String last = fh.readFromFile();
lastDeviceTxt.setText(last);
}
but i keep getting a NullPointerException from both functions.
when running the functions from my MainActivity (I copied them to my main activity) they work fine.
What am I doing wrong? (please remember that I'm very new to android development).
You've defined FileHandler as an Activity. You can't instantiate an Activity yourself, which you are doing here:
FileHandler fh = new FileHandler();
Activities need to be instantiated by the Android framework (otherwise their context isn't set up correctly).
If you don't want these methods in your own Activity, then you can put them in another class. However, that class cannot inherit from Activity. You will then find that you need to pass your Activity's Context to these methods so that they can call methods like openFileInput()
I tried this:
public class People implements Serializable {
String name;
public People(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void saveAsObject(People p) throws FileNotFoundException, IOException
{
try
{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(new File("test","test.dat") ));
os.writeObject(p);
os.close();
System.out.println("Sucess");
}
catch(IOException e)
{
System.out.println(e);
}
}
}
I created that folder manually. It throws this eror: "java.io.FileNotFoundException: /test/test.txt: open failed: ENOENT" (No such file or directory)
When i tried
new FileOutputStream("text.dat")
it throws java.io.FileNotFoundException: EROFS (Read only file system)
This is my main class:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
People p = new People("Ray");
try {
p.saveAsObject(p);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this new File("test","test.dat") is not a valid way of getting a file path on Android.
try this:
new File(Environment.getExternalStorageDirectory(), "/data.dat");
Your app's default current working directory is "/", which you won't have permission to write to.