Following is my code (from MainActivity.java):
public void onWindowFocusChanged(boolean isFocused)
{
super.onWindowFocusChanged(isFocused);
long tempTime = 0;
if(!isFocused)
{
try
{
FileOutputStream fos = this.openFileOutput("timekeeper", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject(AnimationUtils.currentAnimationTimeMillis());
oos.close();
}
catch (IOException e)
{
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else
{
try
{
FileInputStream fis = this.openFileInput("timekeeper");
ObjectInputStream ois = new ObjectInputStream (fis);
tempTime = ois.readLong();
ois.close();
}
catch(Exception e)
{
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
if((tempTime != 0))
{
}
}
}
I checked the code, and it always posts the Toats (when not //'d :)).
What is missing?
Is this the correct way to store/recall information in an android activity?
I did not declare the file anywhere else than in the above code. Should I have?
Let me know if I left out important information...
Thanks!
Related
public class PaymentActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
String FILENAME = "paid";
String data = "yes";
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
File myFile = new File(folder, FILENAME);
FileOutputStream fstream = new FileOutputStream(myFile);
fstream.write(data.getBytes());
fstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
File myFile = new File(folder, FILENAME);
FileInputStream fstream = new FileInputStream(myFile);
StringBuilder sbuffer = new StringBuilder();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
String haspaid = sbuffer.toString();
System.out.println("Help!"+haspaid.equals("yes"));
if (haspaid.equals("yes")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
fstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a file write that inputs "yes" and a file read the reads that "yes" on external storage. I have System.out.println printed it out, and the file read/write seems to work. And yet somehow, when I compare the string resulted, it cannot be checked if it is a value.
What am I doing wrong?
use equals to check the equality of string instead of "!=" or "==".
equals checks the value, and "!=" or "==" checks the reference.
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 2 years ago.
I am making an app with socket in which i want to share data from two devices in the same wifi. With my code i can share the file successfully between two devices with the exact size of the file and saves into the device storage with a specific name but when i try to open it fails to open in the file manager. I have tried this with mp4 file and apk files
Here is the sender's code
#Override
public void run() {
//File file = new File(src);
File file = new File(Environment.getExternalStorageDirectory() + "/c.mp4");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("anything");
dos.writeLong(bytes.length);
int read;
while ((read = dis.read(bytes)) != -1){
dos.write(bytes,0,read);
}
//os.write(bytes, 0, bytes.length); //commented
//os.flush(); //commented
socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, sentMsg, Toast.LENGTH_LONG).show();
}});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And here is the receiver
#Override
public void run() {
Socket socket = null;
int bytesRead;
InputStream in; //changed
int bufferSize=0;
try {
socket = new Socket(dstAddress, dstPort);
bufferSize = socket.getReceiveBufferSize();
in = socket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
File file = new File(Environment.getExternalStorageDirectory(), "c.mp4");
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = clientData.read(buffer)) != -1){
output.write(buffer, 0 , read);
}
//bos.close(); //commented
socket.close();
MainActivity2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity2.this, "Finished", Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity2.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You need to read the clientData (DataInputStream) in the same way you write it to the output stream of the socket.
uft-8 string,
long value,
seq. of bytes
Your mp4 file content will prefixed with "anything" and length. so it will be considered as corrupted file.
save the file without ("anything" and length)
In my App I am using FirebaseMessagingService under which I am receiving the notification, For these notifications I am creating a log in the external storage, When My app is in running mode, The logs are getting created perfectly, but after the app has been killed, the logs are not getting created, but the notification are coming. I don't understand what's the problem, In logcat also am not getting any exception.
public class MyAndroidFirebaseMsgService extends FirebaseMessagingService {
public String message = null;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
message=remoteMessage.getNotification().getBody();
if(message.contains("Text")){
try {
intent1 = new Intent(this, ResultActivity.class);
intent1.putExtra("TextData", message);
intent1.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT );
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setDefaults(Notification.DEFAULT_ALL);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(message);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
try {
File file = new File(getExternalFilesDir("MyStorage"),strNotificationFileName);
if (file.exists())
{
IsFileExist=true;
strNotificationFileName=file.getPath();
}
else
{
IsFileExist=true;
try{
file.createNewFile();
strNotificationFileName=file.getPath();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
catch (Exception ex)
{
}
try {
ArrayList<Object> listNotificationread=readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
UpdateNotificationList("Text");
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
}
public ArrayList<Object> readObject() throws ClassNotFoundException, IOException {
File file = new File(getExternalFilesDir("MyStorage"),"Notification.xml");
if (file.exists()) {
}
listNotification = new ArrayList();
//Create new FileInputStream object to read file
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
//Create new ObjectInputStream object to read object from file
ObjectInputStream obj = new ObjectInputStream(fis);
try {
while (fis.available() != -1) {
//Read object from file
NotificationSavedList acc = (NotificationSavedList) obj.readObject();
listNotification.add(acc);
}
} catch (EOFException ex) {
System.out.println(ex.getMessage());
}
//Collections.reverse(listNotification);
return listNotification;
}
public void writeObject(ArrayList<Object> listNotification) throws IOException {
File file = new File(getExternalFilesDir("MyStorage"),"Notification.xml");
//Create FileOutputStream to write file
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
//Create ObjectOutputStream to write object
ObjectOutputStream objOutputStream = new ObjectOutputStream(fos);
//Write object to file
for (Object obj : listNotification) {
objOutputStream.writeObject(obj);
objOutputStream.reset();
}
objOutputStream.close();
}
public void UpdateNotificationList(String type) {
try {
try {
if (listNotification.size() > 20) {
listNotification.remove(0);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String parsedDate = formatter.format(currentTime);
NotificationSavedList _NotificationSavedList = new NotificationSavedList(listNotification.size()+1, type, message, parsedDate);
listNotification.add(_NotificationSavedList);
writeObject(listNotification);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
I have made an EditText and a Button. The click of the button should save the text from the EditTextinto the ArrayList. The ArrayList is then persisted to a file. Further clicks append the text from the EditText to the ArrayList and then the file. However, after saving the file, I can only retrieve the first item entered from the file. I want to retrieve the whole list in a comma-separated format.
Button Click code:
String filename =“abc.text”;
List arrlist = new ArrayList();
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String listtext = a1.getText().toString();
// a1 is edittext
if (listtext.equals("")) {
Toast.makeText(getApplicationContext(), "Enter product", Toast.LENGTH_SHORT).show();
} else {
arrlist.add(listtext);
a1.setText("");
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrlist);
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
});
Retrieval of ArrayList from file:
List newarrList = new ArrayList();
FileInputStream fis = openFileInput(filename);
ObjectInputStream restore = new ObjectInputStream(fis);
newarrList= (ArrayList)restore.readObject();
restore.close();
String joined = TextUtils.join(", ", newarrList);
Toast.makeText(getApplicationContext(),joined,Toast.LENGTH_LONG).show();
// only the first item is displayed, not sure why
You keep adding ArrayList objects to the file using the ObjectInputStream. But you only read a single one out. I think you want to keep around a single ArrayList that you add the data to and then save that single ArrayList to the file whenever a click occurs instead of appending multiple ArrayLists for each entry.
List arrist = new ArrayList();
arrlist.add(listtext);
a1.setText("");
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
appending an ArrayList object with only one entry each time an onclick occurs
oos.writeObject(arrlist);
oos.close();
fos.close();
}...
If you want to keep your original code and the state is only held for a single Activity and no persistence between Activity changes/App restarts etc.. then this should work.
final String filename = "abc.text";
File file = new File(filename);
// moved out of onClickListener
final List arrlist = new ArrayList();
try {
// load the previous contents if it exists
FileInputStream fis = openFileInput(filename);
ObjectInputStream restore = new ObjectInputStream(fis);
ArrayList newArrList = (ArrayList) restore.readObject();
arrlist.addAll(newArrList);
restore.close();
fis.close();
} catch (FileNotFoundException e) {
// ignore, maybe log
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e)
e.printStackTrace()
}
b2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v
) {
String listtext = a1.getText().toString(); //a1 is edittext
if (listtext.equals("")) {
Toast.makeText(getApplicationContext(), "Enter product", Toast.LENGTH_SHORT).show();
} else {
arrlist.add(listtext);
a1.setText("");
try {
Change Context.MODE_APPEND to Context.MODE_PRIVATE otherwise we keep inflating the file with junk
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrlist);
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
);
The other alternative is to not use the ObjectInputStream but just a straight FileOutputStream and append the String contents on each click.
You store(write) string into file, end the string with comma, and After reading__(read) split the result with "," which returns a String array. Make sure you are appending the string into file. ArrayList variable as global variable.
//global variable
List arrlist = new ArrayList();
......
//write to file
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String listtext = a1.getText().toString();
.....
arrlist.add(listtext);
.....
listtext = listtext + ",";
FileOutputStream fOut = openFileOutput("file name here", Context.MODE_APPEND);
fOut.write(listtext .getBytes());
fOut.close();
....
}
//reading from file
String fileContent = readFile();
String[] items = TextUtils.split(fileContent, ",");
I want to print an object to a file when my app is onStop and read it at onCreate. When I close the app and reopen it the object is not there. The objects acts ok while navigating trough the app, problem only on restart.
The object is an instance ("tl") of TList class - extends ArrayList
read:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
FileInputStream fis;
try {
fis = openFileInput("data_t");
ObjectInputStream ois = new ObjectInputStream(fis);
tl = (TList)ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
write:
#Override
protected void onStop() {
super.onStop();
FileOutputStream fos;
try {
fos = openFileOutput("data_t", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tl);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}