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();
}
}
Related
I have an application that
takes data from the user and
creates a file in the internal memory based on the name entered by the user
and saves the user data.
But when the file is saved by that name, the fileInputStream does not respond to that name.
what should I do ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_food);
bundle = getIntent().getExtras();
Toolbar toolbar=(Toolbar)findViewById(R.id.food_lood_toolbar);
setSupportActionBar(toolbar);
file=bundle.getString("diname");
getSupportActionBar().setTitle(file);
String q=”123”;
if (bundle.getString("activity").equals(q)) {
String e1=editText1.getText().toString() +"/";
fileOutputStream=openFileOutput(file,Context.MODE_PRIVATE);
fileOutputStream.write(e1.getBytes());
}
String t="321";
if (bundle.getString("activity").equals(t)){
try {
fileInputStream= openFileInput(file);
int x;
StringBuffer y = new StringBuffer();
while((x=fileInputStream.read())!=-1){
y.append((char)x);
}
String c=y.toString();
txt=c.split("/");
editText1.setText(txt[0]);
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(),"file not found",Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getBaseContext(),"io",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am writing a mobil application which contains Dynamic Report part. I'm making it with Java ItextPdf Library but when I sent it to printer printer don't accept my file and giving a notification "File Type is not supported by this device." But When I send normal pdf file which is created by pc it is printing.
Printing Class
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
// Set job name, which will be displayed in the print queue
String jobName = " Document";
// Start a print job, passing in a PrintDocumentAdapter implementation
// to handle the generation of a print document
File path = context.getFilesDir();
File file = new File(path,"ss.pdf");
FileOutputStream os = null;
FileInputStream is = null;
try {
os = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Adisyon a = new Adisyon(os);
a.createFile();
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
printManager.print(jobName, new printAdapter(Siparis.this,is),
PrintAdapter Class
#TargetApi(Build.VERSION_CODES.KITKAT)
public class printAdapter extends PrintDocumentAdapter
{
Context context;
InputStream input;
public printAdapter(Context context,FileInputStream input)
{
this.context = context;
this.input = input;
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
OutputStream output = null;
try {
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee){
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("deneme.txt").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
callback.onLayoutFinished(pdi, true);
}
}
Itext Class
public class Adisyon {
FileOutputStream stream;
Context appContext = LoginActivity.getContextOfApplication();
public Adisyon(FileOutputStream stream) {
this.stream = stream;
}
public void createFile() {
try {
Document document = new Document();
PdfWriter.getInstance(document, stream);
document.open();
//addMetaData(document);
//addTitlePage(document);
//addContent(document);
createAdisyon(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
...
I have an activity which contains a listview, the activity (MainActivity) launches another activity (HomeworkAddActivity), this retrieves a string from the user and adds it to the listview (all of the above works).
However in order that the listview 'remembers' its contents whilest the other activity is launched I try to save the list to a file, code:
public void saveHomework() {
try {
#SuppressWarnings("resource")
FileOutputStream fos = new FileOutputStream(homeworkFileName);
fos = openFileOutput(homeworkFileName,
Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(homeworkItems);
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public void populateHomework() {
try {
#SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(homeworkFileName);
fis = getParent().openFileInput(homeworkFileName);
ObjectInputStream is = new ObjectInputStream(fis);
homeworkItems = (ArrayList<String>) is.readObject();
is.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I then read it from the file.
saveHomework is called onPause
and populateHomework:
#Override
public void onResume() {
super.onResume();
homeworkItems = new ArrayList<String>();
activity = this;
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
populateHomework();
homeworkListAdapter.notifyDataSetChanged();
}
However it only ever shows the items added by addHomeworkActivity, not those 'saved' and 'restored' (they don't get saved/restored successfully), why is this?
It has 2 problems
your listview still connect with your old adapter
notifyDataSetChanged might not work in your case, it relate to this answer
notifyDataSetChanged example
you need to reorder your command in onResume()
#Override
public void onResume() {
super.onResume();
homeworkItems = new ArrayList<String>();
activity = this;
populateHomework(); // I move this line up
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
//homeworkListAdapter.notifyDataSetChanged(); // this line might not work
yourListView.setAdapter(homeworkListAdapter); // because your listview still connect with your old ArrayAdapter
}
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!
I'm trying to learn how to make RSS Reader for my android app by following this tutorial.
The feed is generated from a wordpress blog and I want to figure out a way to read by categories. It's currently reading the entire feed items but I'm trying to sort out specific categories from the list.
This is the Activity class to read the feed.
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, GridActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(http://mywordpressblog.com/feed/);
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
before adding the items to your list you can check like this:
if(item.getCategory().contains("categorytoshow")){
add it to the list because it contains the category you want
}
then add it to the list