onCreateOptionMenu android Issue - java

It's the usual activity. The problem is in onCreateOptionMenu. When I click the menu button nothing is done. I don't see where the problem is.
I also try to comment all code without menu but It's still don't work.
It is either a very strange problem or I don't see some simple things..
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
public class Izu4aikaActivity extends Activity implements OnClickListener {
public final int INFO = 101;
public final int BLOCK = 102;
public final int CLOSE = 103;
final String sdDir = Environment.getExternalStorageDirectory()+"/izuchaika/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// Thread to write files to SD
final String file = "Files";
File dir = new File(sdDir);
dir.mkdir();
dir.mkdirs();
new Thread(new Runnable() {
public void run() {
copyFileOrDir(file);
}
}).start();
LinearLayout ll = (LinearLayout) findViewById(R.id.main_layout);
ll.setOnClickListener(this);
}
//Menu
public boolean onCreateOptionMenu(Menu menu) {
menu.add(Menu.NONE, INFO, Menu.NONE, "О программе").setIcon(
R.drawable.info);
menu.add(Menu.NONE, BLOCK, Menu.NONE, "Блокировать").setIcon(
R.drawable.block);
menu.add(Menu.NONE, CLOSE, Menu.NONE, "Выход").setIcon(R.drawable.exit);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onClick(View v) {
Intent i = new Intent(this, mScr.class);
startActivity(i);
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = sdDir + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = sdDir + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}
Help if you see a solution.

You've misspelled method name - it should be onCreateOptionsMenu(), not onCreateOptionMenu().
It's preferable to use #Override annotation to avoid such mistakes:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
This way it will give you compile time error if you misspell method name or use wrong parameters.

Change your onCreateOptionsMenu to:
//Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, INFO, Menu.NONE, "О программе").setIcon(
R.drawable.info);
menu.add(Menu.NONE, BLOCK, Menu.NONE, "Блокировать").setIcon(
R.drawable.block);
menu.add(Menu.NONE, CLOSE, Menu.NONE, "Выход").setIcon(R.drawable.exit);
return true;
}
It should work now!

try to add
#Override to public boolean onCreateOptionMenu
And do you try to use MenuInflater and inflate menu from xml?

Related

what code would I need to add to be able to use this App on phone? [duplicate]

This question already has an answer here:
NetworkOnMainThreadException with AsyncTask
(1 answer)
Closed 6 years ago.
Would some one tell where and what code I would need to add to my Java file to make my app work using NetworkOnMainThreadException because I am really struggling. App crashed when it starts saying the app has stopped working.
package com.airrocketapps.matthillman.guessthecelebrity;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends Activity {
ArrayList<String> celebURLs = new ArrayList<String>();
ArrayList<String> celebNames = new ArrayList<String>();
int chosenCeleb = 0;
int locationOfCorrectAnswer = 0;
String[] answers = new String[4];
ImageView imageView;
Button button0;
Button button1;
Button button2;
Button button3;
public void celebChosen(View view) {
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))) {
Toast.makeText(getApplicationContext(), "Correct!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Wrong! It was " + celebNames.get(chosenCeleb), Toast.LENGTH_LONG).show();
}
createNewQuestion();
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button0 = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
button2 = (Button) findViewById(R.id.button3);
button3 = (Button) findViewById(R.id.button4);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.posh24.com/celebrities").get();
String[] splitResult = result.split("<div class=\"sidebarContainer\">");
Pattern p = Pattern.compile("<img src=\"(.*?)\"");
Matcher m = p.matcher(splitResult[0]);
while (m.find()) {
celebURLs.add(m.group(1));
}
p = Pattern.compile("alt=\"(.*?)\"");
m = p.matcher(splitResult[0]);
while (m.find()) {
celebNames.add(m.group(1));
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
createNewQuestion();
}
public void createNewQuestion() {
Random random = new Random();
chosenCeleb = random.nextInt(celebURLs.size());
ImageDownloader imageTask = new ImageDownloader();
Bitmap celebImage;
try {
celebImage = imageTask.execute(celebURLs.get(chosenCeleb)).get();
imageView.setImageBitmap(celebImage);
locationOfCorrectAnswer = random.nextInt(4);
int incorrectAnswerLocation;
for (int i=0; i<4; i++) {
if (i == locationOfCorrectAnswer) {
answers[i] = celebNames.get(chosenCeleb);
} else {
incorrectAnswerLocation = random.nextInt(celebURLs.size());
while (incorrectAnswerLocation == chosenCeleb) {
incorrectAnswerLocation = random.nextInt(celebURLs.size());
}
answers[i] = celebNames.get(incorrectAnswerLocation);
}
}
button0.setText(answers[0]);
button1.setText(answers[1]);
button2.setText(answers[2]);
button3.setText(answers[3]);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Everything looks fine in your code.
Make sure you have active internet connection in your mobile where you are trying to run this application.
If you are using Internet, then don't forget to add this to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
More help: https://stackoverflow.com/a/6343299/7004388

How can I get my app to read external text file correctly? Only showing weird characters and diamonds

I'm working on my first app. Got everything set up and working correctly, except displaying a random quote from a text file. Clicking the button shows weird characters (diamonds, question marks, etc) and not the actual text except for the placeholder off and on.
I followed the github source correctly as far as I know.
package drewstephensdesigns.com.dailyquotes;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private String STATE_DQ;
private static String TEXT_VALUE = "";
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.dq_view);
//Adds scrolling to the TextView
mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
}
//Code to save state on orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
mTextView = (TextView) findViewById(R.id.dq_view);
outState.putString(STATE_DQ, mTextView.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTextView = (TextView) findViewById(R.id.dq_view);
mTextView.setText(STATE_DQ);
}
private AssetManager getApplicationAssets() {
// open random quotes file
AssetManager assetmanager = getAssets();
return assetmanager;
}
private String getAssetPath(AssetManager assetmanager) {
String[] dirs = null;
String[] files = null;
String path = null;
try {
dirs = assetmanager.list(""); //get list of files / dirs from the project 'assets' directory
files = assetmanager.list(dirs[2]); //Directories are listed in alphabetical order so fetch the 'txt' directory
path = dirs[2].toString() + "/" + files[0].toString(); //construct the path (there is only 1 file in the dir)
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
// Get the path for the random quote file
private InputStreamReader getQuoteReader() throws IOException {
// open random quotes file
AssetManager assets = getApplicationAssets();
String path = null;
path = getAssetPath(assets);
InputStream inputStream = null;
try {
inputStream = assets.open(path);
Log.v("QotD path", path);
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader textReader = new InputStreamReader(inputStream);
return textReader;
}
// Get the total number of lines in the file
private int getFileLineCount(InputStreamReader textReader) {
BufferedReader br = new BufferedReader(textReader);
int lineCount = 0;
try {
while ((br.readLine()) != null) {
lineCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
return lineCount; // total number of lines in the text file
}
// Return a random line number from where to get the
// corresponding quote string
private int getRandomLineNumber(int totalLines) {
Random rand = new Random();
return rand.nextInt(totalLines);
}
private String getRandomQuote(int lineToFetch)
throws IOException {
//1. get path
AssetManager assets = getApplicationAssets();
String path = null;
path = getAssetPath(assets);
//2. open assets
InputStream stream = assets.open(path);
InputStreamReader randomQuote = new InputStreamReader(stream);
//3. Get BufferedReader object
BufferedReader buf = new BufferedReader(randomQuote);
String quote = null;
String line = null;
int currLine = 0;
//4. Loop through using the new InputStreamReader until a match is found
while ((line = buf.readLine()) != null && currLine < lineToFetch) {
currLine++;
}
//Got the quote
quote = line;
//Clean up
randomQuote.close();
buf.close();
return quote;
}
// Set the EditText widget to display the new random quote
private void displayQuote(String quote) {
TextView quoteDisplay = (TextView) findViewById(R.id.dq_view);
TEXT_VALUE = quote;
quoteDisplay.setText(TEXT_VALUE);
}
// onClick handler for the button click
public void fetch_quote(View view) throws IOException {
// open random quotes file
InputStreamReader textReader = getQuoteReader();
final int totalLines = getFileLineCount(textReader);
int lineToFetch = 0;
String quote = null;
// We want to get the quote at the following line number
lineToFetch = getRandomLineNumber(totalLines);
quote = getRandomQuote(lineToFetch);
displayQuote(quote);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem shareItem = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(item.getItemId()){
case R.id.menu_item_share:
if(TEXT_VALUE == "") {
Toast.makeText(this, "Nothing to share! First generate a quote by clicking the button", Toast.LENGTH_SHORT).show();
} else {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, TEXT_VALUE);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Thought you might like this interesting Quote");
startActivity(Intent.createChooser(shareIntent, "Share the quote via..."));
}
break;
case R.id.action_settings:
Toast.makeText(getApplicationContext(), "Settings not yet implemented", Toast.LENGTH_LONG).show();
break;
case R.id.action_about:
Intent aboutIntent = new Intent(this, AboutActivity.class);
startActivity(aboutIntent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
This is what I see:
I had a folder called "fonts" that was not being used. My code was looking for the assets folder with just the randomquote.txt file. Due to the extra folder in there, it was unable to locate the txt file. Deleted the folder since it wasn't being used, saved, boom and progress.

FileNotFoudException occur when zipping file because of output zip file open failed ENOTDIR

I am newbie in android.i am currently developing mulitple files zip in my project
i have a create Array list and use it as source files but i have got filenotfoundexception in pinstacktrace that says Testzip which is my outputfile open failed ENOTDIR. I dont know why is happening . i have tried to convert Arraylist in String Array but nothing happend but garbage value created how could i solve this problem. The Zipfile(ArrayListzipinputlist)is my zipfunction
Here is my code
package com.example.testmutilplefile;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import android.os.Environment;
import android.util.Log;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ArrayAdapter;
public class MainActivity extends Activity {
public static String TAG = "SelectFiles";
// public static String ZIP="zippingfile";
public File filepath = Environment.getExternalStorageDirectory();
public ListView directorytree;
public ListView filetree;
public TextView directorynames;
public TextView files;
public Button sdclick;
public ArrayList<File> resultFilelist;
public ArrayList<File> directorylist = new ArrayList<File>();
public ArrayList<String> directoryname = new ArrayList<String>();
public ArrayList<File> filelist = new ArrayList<File>();
public ArrayList<String> myfilename = new ArrayList<String>();
public byte[] buffer = new byte[4096];
FileInputStream fileinput;
FileOutputStream fileoutput;
ZipOutputStream zipout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialComponent();
sdclick.setClickable(true);
}
public void initialComponent() {
sdclick = (Button) findViewById(R.id.sdcardbutton);
directorynames = (TextView) findViewById(R.id.directoriesname);
files = (TextView) findViewById(R.id.filesname);
directorytree = (ListView) findViewById(R.id.directorySelectionList);
filetree = (ListView) findViewById(R.id.fileSelectionList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_select_file, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onTestClick(MenuItem item) {
Log.d(TAG, "Testclicked, Activity Finishing");
resultFilelist = new ArrayList<File>();
for (int i = 0; i < filetree.getCount(); i++) {
if (filetree.isItemChecked(i)) {
System.out.println(" Selected File is"
+ resultFilelist.add(filelist.get(i)));
Toast.makeText(this, "selected", Toast.LENGTH_SHORT).show();
}
}
if (resultFilelist.isEmpty()) {
Log.d(TAG, "NO File ADDED");
finish();
}
// String fileArray= resultFilelist;
System.out.println(resultFilelist);
Log.d(TAG, "Files:" + resultFilelist);
ArrayList<File> zipInputList = resultFilelist;
zipFile(zipInputList);
// File []zipinputArray= resultFilelist.toArray(new
// File[resultFilelist.size()]);
// Log.d(TAG,"FileArray"+ zipinputArray.toString());
}
private void zipFile(ArrayList<File> zipInputList) {
// TODO Auto-generated method stub
Log.d(TAG, "Current Input files are:" + zipInputList);
String path = Environment.getExternalStorageDirectory().getPath();
String zippedfile = path + File.separator + "Test.zip";
try {
fileoutput = new FileOutputStream(zippedfile);
zipout = new ZipOutputStream(fileoutput);
for (int i = 0; i < zipInputList.size(); i++) {
File storagefileindex = new File(zipInputList.get(i),
zippedfile);
Log.v(TAG, "Add:" + zipInputList.get(i));
Log.v("compressing", "Adding" + zipInputList.get(i));
fileinput = new FileInputStream(storagefileindex);
zipout.putNextEntry(new ZipEntry(storagefileindex.getName()));
int bytecount;
while ((bytecount = fileinput.read(buffer)) > 0) {
zipout.write(buffer, 0, bytecount);
}
zipout.closeEntry();
fileinput.close();
}
zipout.close();
}
catch (Exception e) {
Log.d(zippedfile, "Error occurs in Creating zip");
e.printStackTrace();
}
}
public void onSdCardListener(View v) {
File parentfile = filepath.getParentFile();
Log.d(TAG, parentfile.toString());
listTree();
/*
* if (filepath.equals(Environment.getExternalStorageDirectory())) {
* Toast.makeText(this, "cant exit external storage",
* Toast.LENGTH_SHORT).show(); listTree();
*
* }
*//*
* else { filepath = parentfile; //listTree();
*
* }
*/
}
private void listTree() {
// TODO Auto-generated method stub
FileFilter filefilter = new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
};
FileFilter directoryfilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
/* List of Directory */
if (filepath.exists() && filepath.length() > 0) {
File[] directorylistArray = filepath.listFiles(directoryfilter);
for (File file : directorylistArray) {
directorylist.add(file);
directoryname.add(file.getName());
}
ArrayAdapter<String> directoryadapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, directoryname);
directorytree.setAdapter(directoryadapter);
File[] filelistArray = filepath.listFiles(filefilter);
for (File file : filelistArray) {
filelist.add(file);
myfilename.add(file.getName());
}
ArrayAdapter<String> fileadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myfilename);
filetree.setAdapter(fileadapter);
Log.d(TAG, "List Created");
}
}
}
and my exception output is
01-17 14:01:02.322: V/compressing(854): Adding/storage/sdcard/formpicture.JPG
01-17 14:01:02.332: D//storage/sdcard/Test.zip(854): Error occurs in Creating zip
01-17 14:01:02.332: W/System.err(854): java.io.FileNotFoundException: /storage/sdcard/formpicture.JPG/storage/sdcard/Test.zip: open failed: ENOTDIR (Not a directory)
01-17 14:01:02.352: W/System.err(854): at libcore.io.IoBridge.open(IoBridge.java:409)
01-17 14:01:02.352: W/System.err(854): at java.io.FileInputStream.<init>(FileInputStream.java:78)
You are trying to acces to : /storage/sdcard/formpicture.JPG/storage/sdcard/Test.zip in the line File storagefileindex = new File(zipInputList.get(i), zippedfile); in zipFile function.
Use just File storagefileindex = new File(zipInputList.get(i));

Writing multiple strings to file in android

I am looking to write multiple strings to file for storage using android. Is it possible to add all strings to a toString using .getText and if so how. I am looking to create some edit text fields and take the information contained in these fields and write them to a file before then reading the file in a different activity. Any help would be greatly appreciated.
Here is my code so far if it is any help:
package app.project.newapp;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class AddActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
}
public void saveClick(String filename, EditText v){
EditText name = (EditText) findViewById(R.id.namet);
EditText tel = (EditText) findViewById(R.id.emerg_tel);
EditText cond = (EditText) findViewById(R.id.conditions);
EditText other = (EditText) findViewById(R.id.other);
String userDetails = "Hello_File";
String string = "";
FileOutputStream fos = null;
try {
fos = openFileOutput(userDetails, Context.MODE_PRIVATE);
} catch (FileNotFoundException e){
e.printStackTrace();
}
try {
string=name.getText().toString();
string=tel.getText().toString();
string=cond.getText().toString();
string=other.getText().toString();
fos.write(string.getBytes());
} catch (IOException e){
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("hello_file")));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
} catch(IOException e) {
e.printStackTrace();
}//end catch
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this in your saveClick method, in the second try:
try {
string=name.getText().toString() + "\n"
+ tel.getText().toString() + "\n"
+ cond.getText().toString() + "\n"
+ other.getText().toString();
fos.write(string.getBytes());
} catch(IOException e) {
e.printStackTrace();
}

Change the content of text file in onclick() method of dialogue box

Problem is the string which writes to outputstreamswriter has correct value but in try/catch block within onclick() method of dialogue box outputstreamwriter is not working. My file name is default.txt i'm sure file name has nothing to do with the problem. outputstreamwriter does not change the content of file whatsoever i've tried bufferwriter or fileoutputstream but nothing seems to work. Kindly help i'm losing my mind from days now!
here's the code.
package zafus.personalitymeter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
public class ChoseAnswers extends Activity {
private final String TAG="";
public String vale;
public List<String> obj;
public int numOfAnswers=0;
//public RelativeLayout mylayout =(RelativeLayout)findViewById(R.id.calayout);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chose_answers);
obj=null;
obj=readFromFile("answer.txt", this);
numOfAnswers=Integer.valueOf(obj.get(0).toString());
int i=1;
LinearLayout mylayout =(LinearLayout)findViewById(R.id.linearLayout1);
while(i<=numOfAnswers){
Button tt = new Button(this);
tt.setText(obj.get(i));
tt.setId(i+1);
tt.setPadding(5, 10, 5, 10);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tt.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
vale=((Button)v).getText().toString();
AlertDialog.Builder dlgAlert1 = new AlertDialog.Builder(ChoseAnswers.this);
dlgAlert1.setMessage("Show this answer as a result of next test?");
dlgAlert1.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
obj=null;
obj=readFromFile("default.txt", ChoseAnswers.this);
obj.set(1,vale);
String receiveString = "";
int num=Integer.valueOf(obj.get(0))+2;
StringBuilder ab = new StringBuilder();
int i=0;
for(;i<num;i++){
ab.append(obj.get(i)+"\n");
}
receiveString=ab.toString();
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("default.txt", Context.MODE_PRIVATE));
//outputStreamWriter.write("");
outputStreamWriter.write(receiveString);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
ChoseAnswers.this.finish();
}});
dlgAlert1.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}});
dlgAlert1.show();
}
});
if (i == 1){
params.setMargins(0, 150, 0, 20);
}
else{
params.setMargins(0, 20, 0, 20);
}
tt.setLayoutParams(params);
tt.setBackgroundResource(R.drawable.bxml);
tt.setTextColor(Color.parseColor("#330011"));
mylayout.addView(tt);
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.choseanswers, menu);
return true;
}
public static List<String> readFromFile(String fileName, Context context) {
List<String> words = new ArrayList<String>();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets().open(fileName, context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
words.add(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return words;
}
}
In your onClick you read a file from assets and save it to internal memory.
On the next click the same happens.
You should read the file from internal memory too if you want to check if the write succeeded.

Categories