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();
}
Related
I have made news reader App where top 20 news articles from one of the leading news websites are fetched through its API.
One activity contains listview that shows latest news titles and clicking them opens webview in other activity corresponding to that news article.
I am downloading content through AsyncTask and onPostExecute I am updating my listview. I want to do the same in OnCreate if databse is not empty.
I have tried checking if cursor.getstring(0) not null or !articlesDB.equals(null) but not working and the app crashes when opened the first time.
package com.example.freshnews;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;
public class MainActivity extends AppCompatActivity {
static ArrayList<String> titles=new ArrayList<>();
static ArrayList<String> articleHtml=new ArrayList<>();
static ArrayList<String> articleLinks=new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
ListView newsListView;
String articleTitle,articleUrl,result,articleId;
SQLiteDatabase articleDB;
Cursor c;
public void updateListView()
{
c=articleDB.rawQuery("SELECT * FROM articles",null);
int titleIndex=c.getColumnIndex("articleTitle");
int codeIndex=c.getColumnIndex("articleCode");
int linkIndex=c.getColumnIndex("articleLinks");
if(c.moveToFirst())
{
titles.clear();
articleHtml.clear();
articleLinks.clear();
}
do {
titles.add(c.getString(titleIndex));
articleHtml.add(c.getString(codeIndex));
articleLinks.add(c.getString(linkIndex));
}while(c.moveToNext());
c.close();
arrayAdapter.notifyDataSetChanged();
}
public class DownloadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... strings) {
URL url;
result="";
HttpURLConnection urlConnection=null;
try {
url = new URL(strings[0]);
urlConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(inputStream);
int data=reader.read();
while(data != -1)
{
char current=(char) data;
result += current;
data=reader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Received article IDs
int articleCounter;
String newsSourceURL;
articleDB.execSQL("DELETE FROM articles");
try {
JSONArray jsonArray = new JSONArray(result);
if(jsonArray.length()<20)
{
articleCounter=jsonArray.length();
}
else
{
articleCounter=20;
}
for(int i=0;i<articleCounter;i++)
{
// Log.i("JSON Items",jsonArray.getString(i));
articleId=jsonArray.getString(i);
newsSourceURL="https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty";
// Log.i("URL",newsSourceURL);
url=new URL(newsSourceURL);
urlConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream=urlConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(inputStream);
int data=reader.read();
String articleInfo="";
while(data!=-1)
{
char current=(char) data;
articleInfo+=current;
data=reader.read();
}
JSONObject jsonObject=new JSONObject(articleInfo);
if(!jsonObject.isNull("title") && !jsonObject.isNull("url")) {
articleTitle = jsonObject.getString("title");
articleUrl = jsonObject.getString("url");
}
// Log.i("Article Information",articleId + " " + articleTitle + " " + articleUrl);
/* URL urlHtml=new URL(articleUrl);
HttpURLConnection urlConnectionHtml=(HttpURLConnection) urlHtml.openConnection();
InputStream inputStreamHtml=urlConnectionHtml.getInputStream();
InputStreamReader readerHtml=new InputStreamReader(inputStreamHtml);
int dataHtml=readerHtml.read();
while(dataHtml<50)
{
char current=(char) dataHtml;
articleCode+=current;
dataHtml=readerHtml.read();
}
Log.i("Article HTML",articleCode);*/
String articleCode="<html><body><h1>Hi There</h1><p>How did you find my webview?</p></body></html>";
String sql="INSERT INTO articles (articleId,articleTitle,articleCode,articleLinks) VALUES (?, ?, ?, ?)";
SQLiteStatement statement=articleDB.compileStatement(sql);
statement.bindString(1,articleId);
statement.bindString(2,articleTitle);
statement.bindString(3,articleCode);
statement.bindString(4,articleUrl);
statement.execute();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
updateListView();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newsListView=(ListView) findViewById(R.id.newsListView);
arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,titles);
newsListView.setAdapter(arrayAdapter);
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(),NewsActivity.class);
intent.putExtra("news",articleLinks.get(position));
startActivity(intent);
}
});
articleDB=this.openOrCreateDatabase("Articles",MODE_PRIVATE,null);
articleDB.execSQL("CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, articleId INTEGER, articleTitle VARCHAR, articleCode VARCHAR, articleLinks VARCHAR) ");
/* if(!c.moveToFirst()) { Facing the problem here
updateListView();
}*/
DownloadTask task=new DownloadTask();
try {
task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
}catch (Exception e)
{
e.printStackTrace();
}
}
}
/* if(!c.moveToFirst()) { Facing the problem here
You would face as issue as the cursor will be null as it hasn't been instantiated.
Add the line
c = articleDB.rawQuery("SELECT count() FROM articles LIMIT 1",null);
and instead of the above you could use the more indicative :-
if (c.getCount() < 1) {
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
I am fairly new to Android, i want to write a telnet client app for my Android. I have written the code using Apache commons library for telnet. Now i am able to connect to telnet server (for that i have used Asyctask concept) and able to read login banner after a long time i don't know what is causing that. I have modified the example given in Apache commons to work with my android code.I have two java codes in my "src" folder (MainActivity.java and TelnetClientExample.java). First, i want to get the login prompt and then i want user to interact with it please help, Thanks in advance :)
I am posting my screen capture of what i am getting.
MainActivity.java
package com.example.telnetapp;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity{
public static int port_int_address;
private EditText server,port;
private Button connect;
public static String ip,port_address;
public PrintWriter out;
public static TextView textResponse;
static String response;
public InputStream instr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server = (EditText)findViewById(R.id.edittext1);
port = (EditText)findViewById(R.id.edittext2);
connect = (Button)findViewById(R.id.connect);
textResponse = (TextView)findViewById(R.id.response);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ip = server.getText().toString();
port_address = port.getText().toString();
port_int_address = Integer.parseInt(port_address);
try{
MyClientTask task = new MyClientTask(ip, port_int_address);
task.execute();
}
catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
TelnetClientExample job;
MyClientTask(String inetAddress, int port){
dstAddress = inetAddress;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
job = new TelnetClientExample();
job.backgroundjob();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try {
instr = TelnetClientExample.tc.getInputStream();
byte[] buff = new byte[1024];
int ret_read = 0;
do
{
ret_read = instr.read(buff);
if(ret_read > 0)
{
MainActivity.response += new String(buff, 0, ret_read);
}
}
while (ret_read >= 0);
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from telnet server ! \n";
}
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
TelnetClientExample.java
package com.example.telnetapp;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.telnet.TelnetClient;
public class TelnetClientExample {
public String remoteip = MainActivity.ip;
public int remoteport= MainActivity.port_int_address;
public static TelnetClient tc = null;
public void backgroundjob() throws IOException {
tc = new TelnetClient();
try {
tc.connect(remoteip, remoteport);
}
catch (Exception e) {
}
}
public void close_con(){
try {
tc.disconnect();
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from disconnecting telnet server ! \n";
}
}
}
The problem is in this code snippet . please look into this and help me to get an interactive session.
protected void onPostExecute(Void result) {
try {
instr = TelnetClientExample.tc.getInputStream();
byte[] buff = new byte[1024];
int ret_read = 0;
do
{
ret_read = instr.read(buff);
if(ret_read > 0)
{
MainActivity.response += new String(buff, 0, ret_read);
}
}
while (ret_read >= 0);
}
catch (Exception e) {
MainActivity.response += e.toString();
MainActivity.response += "From reading from telnet server ! \n";
}
textResponse.setText(response);
super.onPostExecute(result);
}
The problem i am getting -
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.
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?