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
Related
I'm an android developer
I have an idea to develop an application that writes on NFC tags data. (Only writing)
I have an Edit Text and a button and when I click on the button I write on the NFC the data written in the field
I searched a lot and tried several codes
The only problem is my NFC tags sticks in the back of the phone and the code i'm using tells me I have to tap/tag the NFC tag to write in it
Is there another way to detect the NFC tag sticked on the back of the phone when clicking the button?
I have two activities main activity that will call methods from my NFCManager
I will share below the NFCManager class
NFCManager class:
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
public class NFCManager {
private Activity activity;
private NfcAdapter nfcAdpt;
public NFCManager(Activity activity) {
this.activity = activity;
}
public void verifyNFC() throws NFCNotSupported, NFCNotEnabled {
nfcAdpt = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdpt == null)
throw new NFCNotSupported();
if (!nfcAdpt.isEnabled())
throw new NFCNotEnabled();
}
public void enableDispatch() {
Intent nfcIntent = new Intent(activity, getClass());
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, nfcIntent, 0);
IntentFilter[] intentFiltersArray = new IntentFilter[] {};
String[][] techList = new String[][] { { android.nfc.tech.Ndef.class.getName() }, { android.nfc.tech.NdefFormatable.class.getName() } };
nfcAdpt.enableForegroundDispatch(activity, pendingIntent, intentFiltersArray, techList);
}
public void disableDispatch() {
nfcAdpt.disableForegroundDispatch(activity);
}
public static class NFCNotSupported extends Exception {
public NFCNotSupported() {
super();
}
}
public static class NFCNotEnabled extends Exception {
public NFCNotEnabled() {
super();
}
}
public void writeTag(Tag tag, NdefMessage message) {
if (tag != null) {
try {
Ndef ndefTag = Ndef.get(tag);
if (ndefTag == null) {
// Let's try to format the Tag in NDEF
NdefFormatable nForm = NdefFormatable.get(tag);
if (nForm != null) {
nForm.connect();
nForm.format(message);
nForm.close();
}
}
else {
ndefTag.connect();
ndefTag.writeNdefMessage(message);
ndefTag.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public NdefMessage createUriMessage(String content, String type) {
NdefRecord record = NdefRecord.createUri(type + content);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
return msg;
}
public NdefMessage createTextMessage(String content) {
try {
// Get UTF-8 byte
byte[] lang = Locale.getDefault().getLanguage().getBytes("UTF-8");
byte[] text = content.getBytes("UTF-8"); // Content in UTF-8
int langSize = lang.length;
int textLength = text.length;
ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + langSize + textLength);
payload.write((byte) (langSize & 0x1F));
payload.write(lang, 0, langSize);
payload.write(text, 0, textLength);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
return new NdefMessage(new NdefRecord[]{record});
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public NdefMessage createExternalMessage(String content) {
NdefRecord externalRecord = NdefRecord.createExternal("com.survivingwithandroid", "data", content.getBytes());
NdefMessage ndefMessage = new NdefMessage(new NdefRecord[] { externalRecord });
return ndefMessage;
}
}
Methods from my MainActivity:
#Override
protected void onResume() {
super.onResume();
try {
nfcMger.verifyNFC();
//nfcMger.enableDispatch();
Intent nfcIntent = new Intent(this, getClass());
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
IntentFilter[] intentFiltersArray = new IntentFilter[] {};
String[][] techList = new String[][] { { android.nfc.tech.Ndef.class.getName() }, { android.nfc.tech.NdefFormatable.class.getName() } };
NfcAdapter nfcAdpt = NfcAdapter.getDefaultAdapter(this);
nfcAdpt.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techList);
}
catch(NFCManager.NFCNotSupported nfcnsup) {
Snackbar.make(v, "NFC not supported", Snackbar.LENGTH_LONG).show();
}
catch(NFCManager.NFCNotEnabled nfcnEn) {
Snackbar.make(v, "NFC Not enabled", Snackbar.LENGTH_LONG).show();
}
}
#Override
protected void onPause() {
super.onPause();
nfcMger.disableDispatch();
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d("Nfc", "New intent");
// It is the time to write the tag
currentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (message != null) {
nfcMger.writeTag(currentTag, message);
dialog.dismiss();
Snackbar.make(v, "Tag written", Snackbar.LENGTH_LONG).show();
} else {
// Handle intent
}
}
There is another and much better way to get notified that a Tag comes in to range especially if you are writing to a Tag, this is called enableReaderMode but you use case is strange.
I'm not sure why you would want an NFC tag stuck on the back of a phone because then it would act like very slow and small sized permanent storage when a file on the phones memory would be far better.
Remember once the Tag comes in to range you get notified via enableForegroundDispatch or enableReaderMode that a Tag has come in to range and get given a Tag object. As long as that Tag does not go out of range and you have stored the Tag object in the global scope of the activity then you can write to it as many times you like and for as long as you like.
Therefore it should be possible if complicated to do what you wand and write (or read) when even the user click a button.
I've not tested whether a Tag object is usable after your App is put in to the background and brought to the foreground again, but I think it is unlikely because a background App might be closed and closure would definitely invalid the Tag object.
But there are 2 problems with your code.
Really calling connect and write to your Tag should never be done on the UI thread as it is IO blocking and could be cancelled which would cause the Tag to be taken out of range and brought back in to range again. Luckily if you use enableReaderMode then you get notified in a separate thread.
You should only call close on the Tag when you no longer want to write to it, at the moment you are calling close after you have written once to it.
So the following will probably work for you but with the limitation that the Tag has to come in to range the first time after the App has started.
Use enableReaderMode to get notified that the Tag initially comes in to range, Store the Tag object in the global Activity scope and connect to it once in the enableReaderMode callback thread.
The from the UI when the button is press, start a new Thread to write to the tag.
Never call close on the Tag Object.
Note I've not tested this as it is a very strange use case.
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
.I followed this tutorial and getting errors "PARSING ERROR THERE IS A PROBLEM PARSING THE PACKAGE". I have check the result in Android Device Samsung Galaxy S3.
package com.mrfs.android.surveyapp.activities;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class ApkFileAsync extends Activity
{
UpdateApp updateAppInstance;
#Override
public void onCreate(Bundle savedBundleInstance)
{
super.onCreate(savedBundleInstance);
updateAppInstance = new UpdateApp();
updateAppInstance.setContext(getApplicationContext());
updateAppInstance.execute("http://demo.ingresssolutions.com/proposalmanagement/services/user/getApkFile");
}
private class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
context = contextf;
}
#Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file,"surveyapp.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
/* Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);*/ // without this flag android returned a intent error!
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
context.startActivity(intent);
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}}
}
I am getting this error after Complete Action using dialog when trying to press either PACKAGE INSTALLER or VERIFY AND INSTALL in both cases same error.
Change your manifes to like
This should work fine i think.. If not worked please post your tutorial link i missed it.. i need to check it.. and i will update answer...
and also mention how you are installing app wether by eclipse or by some other process like importing apk... IF importing apk to real device means please check ur device version, If its s3 mans it has ICS api level includes 14 or 15 so change that.. if its jellly bean means you can use up to 18
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.
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?