this code is supposed to create a new user with the username and password he entered and then save that new object to phone memory with the file name matching his email so that in the login method I can look for the file matching the email entered deserialize it, and all his user info would be there... But I keep getting a FileNotFooundException... I really don't understand... please someone help me! :)
Here's the code:
package com.example.eventmanager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class CreateAccount extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
}
public void createUserAccount(View v) {
EditText username = (EditText) findViewById(R.id.editText1);
EditText password = (EditText) findViewById(R.id.editText2);
EditText secondPassword = (EditText) findViewById(R.id.editText3);
if (!(password.getText().toString().equals((secondPassword.getText()
.toString())))) {
Toast.makeText(this, "Passwords Don't Match", Toast.LENGTH_LONG).show();
} else {
User newUser = new User(username.getText().toString(), password.getText().toString());
String fileName = newUser.getEmail();
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));
os.writeObject(newUser);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "FileNotFoundException", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "IOException", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Intent intent = new Intent(this, LoginScreen.class);
startActivity(intent);
Toast.makeText(this, "Account Created Successfully",
Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_create_account, menu);
return true;
}
}
Per FileOutputStream documentation: it throws FileNotFoundException in below scenario:
FileNotFoundException - if the file exists but is a directory rather than a regular file OR does not exist but cannot be created, or cannot be opened for any other reason
Please make sure, String fileName = newUser.getEmail().toString(); results in valid file name, which I suspect is the case.
FileOutputStream uses an absolute path which (I think) will default to the root of the internal storage if you only provide a filename - on a normal device, the root of the internal storage will not be accessible.
You should use openFileOutput(String name, int mode) instead. This guarantees creating a file in the internal storage in the area allocated to your own app. To read the file back, use the corresponding openFileInput(String name) method.
Related
I am trying to build an app, which takes the patient id as a shared preference and uses that id in another activity for getting the records of that id. In Main Activity I set the Shared Preferences, and it sets the value correctly. However, in FetchSinglePatientData, I am not able to get the same Shared Preference Value.
P.S : Before to that error, I was getting nothing at all. My codes at below:
public void getSinglePatient(View v)
{
etID = findViewById(R.id.editTextID);
SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("patientId",etID.getText().toString());
editor.apply();
String xx = sharedPref.getString("patientId","hayamk");
Log.d("XX","DEGER" + xx);
//instantiate intent class
Intent intent=new Intent(MainActivity.this, GetSinglePatient.class);
//start the activity
startActivity(intent);
}
GetSinglePatient activity, this activity uses the fetchSinglePatientData in background.fetchSinglePatientData is like below:
package project.android.mapd713.college.centennial.com.mapd713application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchSinglePatientData extends AsyncTask<Void,Void,Void> {
String data = "";
String dataParsed = "";
String singleParsed = "";
JSONObject myObject;
private Context ctx;
public fetchSinglePatientData(Context ctx) {
this.ctx = ctx;
}
#Override
protected Void doInBackground(Void... voids) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
//String patientId = prefs.getString("patientId", "");
String xx = sharedPref.getString("patientId","fafafa");
Log.d("XX2","DEGE2R" + xx);
Log.i("fonksiyon","ICINE GIRDI");
try {
URL url = new URL("https://mapd713prjct.herokuapp.com/patients/5bf63c770fc33ea59c9c3a97");
Log.i("URL","URL ICINE GIRDI");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null) {
line = bufferedReader.readLine();
data = data + line;
}
myObject = new JSONObject(data);
myObject.getString("doctor");
Log.d("DOKTOR BU NE","hmm" + myObject.getString("doctor"));
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.print("HATA 1: " + e);
} catch (IOException e) {
e.printStackTrace();
System.out.print("HATA 2: " + e);
} catch (JSONException e) {
e.printStackTrace();
System.out.print("HATA 3: " + e);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
System.out.println("girdi");
Log.i("onPostExecute","GIRDI");
GetSinglePatient.mTextViewResult.setText(myObject.toString());
}
}
And the logs are like below with two different input, 1) jajaja and 2) hehehe
2018-12-01 22:38:12.360 7470-7470/project.android.mapd713.college.centennial.com.mapd713application D/XX: DEGERjajaja
2018-12-01 22:38:12.816 7470-
7497/project.android.mapd713.college.centennial.com.mapd713application D/XX2: DEGE2Rfafafa
2018-12-01 22:43:05.644 7470-7470/project.android.mapd713.college.centennial.com.mapd713application D/XX: DEGERhehehe
2018-12-01 22:43:05.815 7470-7547/project.android.mapd713.college.centennial.com.mapd713application D/XX2: DEGE2Rfafafa
Thank you very much!
You're using two different ways to obtain a SharedPreferences object. First you use the Context.getSharedPreferences() method that takes a preference file name. Then you use the static method PreferenceManager.getDefaultSharedPreferences(). This will result in two different SharedPreference files being used. Just pick one way or the other and be consistent and it should work much better.
for solving this problem , use a shared preference with define name and mode. for
example:
SharedPreferences SharedPreference = context.getSharedPreferences("defined
name" , Context.MODE_PRIVATE);
for inserting data in shared preference without any delay use commit() instead of apply()
editor.commit();
and send ApplicationContext to your asynctask class
I resolved my problem with changing my code below:
SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);
with
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
It is true that I used two different SharedPreference method and therefore, I couldn't get the Patient id. However, changing
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
with
SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);
does not work since getSharedPreferences() needs a context to be accessed.
In my opinion, this is a little bit tricky with Android. I suggest those posts:
post1 post2
I want to share a mp3 file to whatsapp.
I found this question on Stack Overflow, but the accepted answer does not work for me. If I try to share it with whatsapp it says "Sharing failed, please try again":
File dest = Environment.getExternalStorageDirectory();
InputStream in = getResources().openRawResource(R.raw.sound);
try
{
OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch (Exception e) {
e.printStackTrace();}
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/sound.mp3"));
share.setType("audio/mp3");
startActivity(Intent.createChooser(share, "Shared"));
Here is the full MainActivity.java:
package com.example.aaron.sharetest;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
Button shareBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "Android/data/com.example.aaron.sharetest/files");
File sharefile= new File(FILES_PATH, "sound.mp3") ;
putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sharefile));
shareBtn = (Button)findViewById(R.id.shareBtn);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w("error", "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG).show();
finish();
}
File dest = Environment.getExternalStorageDirectory();
InputStream in = getResources().openRawResource(R.raw.bibikurz);
try
{
OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/sound.mp3"));
share.setType("audio/mp3");
startActivity(Intent.createChooser(share, "Shared"));
}
});
}
}
Of course I wrote this line in my Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
What do I have to do to share the mp3 file to whatsapp, etc?
I tried so many accepted answers, but no one of them worked for me.
This is what I get in my LogCat:
06-23 02:41:17.589 23924-23924/? W/Bundle: Key android.intent.extra.STREAM expected ArrayList but value was a android.net.Uri$StringUri. The default value <null> was returned.
06-23 02:41:17.659 23924-23924/? W/Bundle: Attempt to cast generated internal exception:
java.lang.ClassCastException: android.net.Uri$StringUri cannot be cast to java.util.ArrayList
at android.os.Bundle.getParcelableArrayList(Bundle.java:838)
at android.content.Intent.getParcelableArrayListExtra(Intent.java:5481)
at com.whatsapp.ContactPicker.k(ContactPicker.java:623)
at com.whatsapp.ContactPicker.onCreate(ContactPicker.java:338)
at android.app.Activity.performCreate(Activity.java:6367)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2511)
at android.app.ActivityThread.access$900(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1375)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5621)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
Android 6.0 Marshmallow (API 23) or later. If this is the case, you mustimplement runtime permissions
Use file path and check memory card
File FILES_PATH = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.examples(your package )/files");
File sharefile= new File(
FILES_PATH,
"demo.mp3") ;
putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sharefile))
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w(TAG, "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(this, R.string.need_external_storage, Toast.LENGTH_LONG).show();
finish();
}
My "sound.mp3" file is located in the raw folder.
Your first two samples will not work, as they have nothing to do with a raw resource. They share a file that does not exist, from a directory that might also not exist.
But here I dont know what "ContextID" or "ResouceID" is.
If this code is going where your first two code snippets went, ContextID can be replaced with this. If you are trying to share res/raw/sound.mp3, then ResourceID is R.raw.sound.
thanks for taking the time to read this. I am experiencing a very strange 'NoSuchMethodError' in a project I'm working on involving Android. I can't figure this out as it defies all of my logic.
package com.project.qrcode
import android.security.KeyStore;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import jim.h.common.android.lib.zxing.config.ZXingLibConfig;
import jim.h.common.android.lib.zxing.integrator.IntentIntegrator;
import jim.h.common.android.lib.zxing.integrator.IntentResult;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ZXingLibConfig zxingLibConfig;
private Handler handler = new Handler();
private TextView txtScanResult;
KeyStore ks = KeyStore.getInstance();
SecretKeyStore secretKeyStore = new SecretKeyStore();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
byte[] hashedBytes;
String decoded;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
startActivity(new Intent("android.credentials.UNLOCK"));
} else {
startActivity(new Intent("com.android.credentials.UNLOCK"));
}
} catch (ActivityNotFoundException e) {
Log.e(getPackageName(), "No UNLOCK activity: " + e.getMessage(), e);
}
zxingLibConfig = new ZXingLibConfig();
zxingLibConfig.useFrontLight = true;
txtScanResult = (TextView) findViewById(R.id.scan_result);
Button scanButton = (Button) findViewById(R.id.scan_button);
//Set a listener on the scan button
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!checkIfKeyStored()) {
Toast keyerror = Toast.makeText(getBaseContext(), "You need to complete setup first", Toast.LENGTH_SHORT);
keyerror.show();
return;
}
IntentIntegrator.initiateScan(MainActivity.this, zxingLibConfig);
}
});
Log.v(getPackageName(), "Listener set on scan button");
Button setupButton = (Button) findViewById(R.id.setup_button);
// Set a listener on the setup button
setupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkIfKeyStored()) {
Log.v(getPackageName(), "Key is already stored");
Toast keyerror = Toast.makeText(getBaseContext(), "You have already completed setup", Toast.LENGTH_SHORT);
keyerror.show();
return;
}
Log.v(getPackageName(), "Key not stored, proceeding with setup");
IntentIntegrator.initiateScan(MainActivity.this, zxingLibConfig);
}
});
Log.v(getPackageName(), "Listener set on setup button");
}
protected boolean checkIfKeyStored() {
String[] keyNames = ks.saw("");
if( keyNames.length == 0 ) {
return false;
}
return true;
}
// IF setup is done i.e. key is stored send to server
// Otherwise store on phone
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v(getPackageName(), "Scanned QRCode");
if (requestCode == IntentIntegrator.REQUEST_CODE) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult == null) {
Log.v(getPackageName(), "Scanned nothing");
return;
}
//Contents of the QRCode
Log.v(getPackageName(), "Scan complete, getting result");
final String result = scanResult.getContents();
Log.v(getPackageName(), "Scanned the following code "+ result);
//If there is already a secret key stored i.e. setup already done
if (checkIfKeyStored()) {
Log.v(getPackageName(), "Key already stored, encrypting");
try {
MessageDigest digest = MessageDigest.getInstance("SHA1PRNG");
Log.v(getPackageName(), "Got SHA1PRNG instance");
byte[] keyBytes = ks.get("twofactorkey");
byte[] resultBytes = result.getBytes("UTF-8");
Log.v(getPackageName(), "Got Bytes");
outputStream.write( resultBytes );
outputStream.write( keyBytes );
Log.v(getPackageName(), "Wrote Bytes to output stream");
byte[] bytesToEncrypt = outputStream.toByteArray( );
Log.v(getPackageName(), "Wrote to Byte array");
hashedBytes = digest.digest(bytesToEncrypt);
decoded = new String(hashedBytes, "UTF-8");
Log.v(getPackageName(), "Coverted bytes to String");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
txtScanResult.setText(decoded);
Log.v(getPackageName(), "Set TextView");
}
});
}
else //This is the first time scanning a QRCode, i.e. Setup
{
Log.v(getPackageName(), "Key not stored, first time setup");
byte[] resultBytes;
try {
resultBytes = result.getBytes("UTF-8");
Log.v(getPackageName(), "Result byte array: " + resultBytes);
boolean success = ks.put("twofactorkey", resultBytes);
if (!success) {
int errorCode = ks.getLastError();
throw new RuntimeException("Keystore error: " + errorCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.v(getPackageName(), "Stored in keystore");
Toast setupComplete = Toast.makeText(getBaseContext(), "You have completed setup", Toast.LENGTH_SHORT);
setupComplete.show();
}
}
}
}
package android.security;
public class KeyStore {
private boolean put(byte[] key, byte[] value) {
execute('i', key, value);
return mError == NO_ERROR;
}
public boolean put(String key, byte[] value) {
Log.v("KEYSTORE", "Attempting put");
return put(getBytes(key), value);
}
}
The error I am getting is..
02-24 15:25:55.689: E/AndroidRuntime(11016): java.lang.NoSuchMethodError: android.security.KeyStore.put which occurs in the onActivityResult() method.
If you need the full logcat I can post that too.
You can see I have some Log messages planted throughout the code. The one inside put never prints out.
EDIT 24/02/14:
The above NoMethod exception has been solved by moving KeyStore.java into the same package as MainActivity.java - Thank you Lars
However I now have a new problem. Any time I try using ks.state() or ks.put() I get back a response back of AssertError: 5 - Which, according to KeyStore.java is a protocol error.
Final Edit
I figured out the above problem. Turns out the version of the KeyStore I am using from AOSP is for versions of Android below 4.2 only.
what is the reason for java.lang.NoSuchMethodError
java doc says
Thrown if an application tries to call a specified method of a class
(either static or instance), and that class no longer has a definition
of that method. Normally, this error is caught by the compiler; this
error can only occur at run time if the definition of a class has
incompatibly changed.
in your code you call put method here
boolean success = ks.put("twofactorkey", resultBytes);
and you have a required method is in the KeyStore class
public boolean put(String key, byte[] value) {
Log.v("KEYSTORE", "Attempting put");
return put(getBytes(key), value);
}
but the problem is your compiled KeyStore(KeyStore.class file) has no required put method. I assume you have mistakenly altered the above put method and compiled both classes alone and ran MainActivity class. that's why you get that error
that kind of error appear when you are running some code on a older virtual machine.
in general thisd appen when your bitcode call a function that does not exist.
As far as i know android.security; does not exist, but java.security; does.
If that your custom class, i don't think you can put it into android's path, but i exoect a compiling error
Now I have to download a file whose url has known. I need to save it to SD card when download action finished. The problem is I should know whether the file is existed before downloading. So I plan to save the file with a identified filename which is generated from url. So when I get the url I can calculate his corresponding filename. Which algorithm should I use?
BTW, JAVA is what I'm using.
Maybe, I have not told my requirement clearly. Fetch the filename "abc.png" from url "www.yahoo.com/abc.png" is not what I need. Because "www.google.com/abc.png" results the same filename. I need to generate a unique filename from url.
full example working ...i tried myself some days ago..
im sure it will help..
package com.imagedownloader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class ImageDownloaderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap=DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
ImageView img =(ImageView)findViewById(R.id.imageView1);
img.setImageBitmap(bitmap);
}
private Bitmap DownloadImage(String URL) {
// TODO Auto-generated method stub
Bitmap bitmap=null;
InputStream in=null;
try {
in=OpenHttpConnection(URL);
bitmap=BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String stingurl) throws IOException {
// TODO Auto-generated method stub
InputStream in=null;
int response=-1;
URL url = new URL(stingurl);
URLConnection conn=url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("not and http exception");
try{
HttpURLConnection httpconn=(HttpURLConnection)conn;
httpconn.setAllowUserInteraction(false);
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect();
response=httpconn.getResponseCode();
if(response==HttpURLConnection.HTTP_OK)
{
in=httpconn.getInputStream();
}
}
catch(Exception ex)
{throw new IOException("Error connecting"); }
return in;
}
}
I am attempting to use java FileInputStream to write some strings to a text file that will be stored on the android internal storage. However my virtual device keeps throwing an exception and I am not sure what or where I should be looking as the DDMS log cat function does not give me any useful information. I am using a try/catch structure with a stack trace print as shown below. I am not very familiar with the debug function in relation to android and I am not sure where else I can look to find out what is going on. Code is below.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText textBox;
private static final int READ_BLOCK_SIZE = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textBox = (EditText)findViewById(R.id.textView1);
Button saveBtn = (Button)findViewById(R.id.button1);
Button loadBtn = (Button)findViewById(R.id.button2);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = textBox.getText().toString();
try{
FileOutputStream fOut =
openFileOutput("textfile.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
osw.write(str);
osw.flush();
osw.close();
//---display file saved message---
Toast.makeText(getBaseContext(), "File saved successfully!!", Toast.LENGTH_SHORT).show();
//---clears the EditText---
textBox.setText("");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
FileInputStream fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[]inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer))>0){
//---convert the char to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//---set the EditText to the text that has been read---
textBox.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully!!", Toast.LENGTH_SHORT).show();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
}
}
did you set your permissions in your manifest for writing?
and is your device a droidx (which when you plug in the USB cable, unmounts the external storage, making it inaccessible).
Why not run the debugger and put in debug points and see how far it gets before it crashes?