Getting error in saving data in Internal Storage in android - android

I am making an app that takes two strings through edittext. I want to store these strings in Internal Storage but I am getting error: "java.io.FILENOTFOUNDEXCEPTION".
public class MyActivity extends Activity {
public Button save;
public EditText user;
public EditText pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
save = (Button) findViewById(R.id.button);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String un = (String) user.getText().toString();
String pw = (String) pass.getText().toString();
//Creating file for saving username and passwords
String PRONTO = "PrivateData";
FileOutputStream fos = openFileOutput(PRONTO, Context.MODE_PRIVATE);
fos.write(un.getBytes());
fos.close();
}
});
}
}

Replace
FileOutputStream fos = openFileOutput(PRONTO, Context.MODE_PRIVATE);
with
FileOutputStream fos;
try {
fos = openFileOutput(PRONTO, Context.MODE_PRIVATE);
fos.write(un.getBytes());
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

Related

Storing user credential at local storage of android device (Internal memory) which should be hidden from user or unaccessible

I have an registration layout with its java file to store the user's credential locally to its app directory. But i need to store those credentials somewhere user can't access or make any change.
Is there a way to do. If so kindly help.
My .java file.
public class screen_25 extends Activity {
EditText searchBox;
EditText searchBox1;
EditText searchBox2;
EditText searchBox3;
EditText searchBox4;
EditText searchBox5;
TextView response;
Button save;
Button read;
private String fileName = "SampleFile2.pdf";
private String filePath = "MyFileStorage";
File myExternalFile;
String myData="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_25);
save=(Button)findViewById(R.id.save_user);
response=(TextView)findViewById(R.id.response);
searchBox=(EditText) findViewById(R.id.searchBox);
searchBox1=(EditText) findViewById(R.id.searchBox1);
searchBox2=(EditText) findViewById(R.id.searchBox2);
searchBox3=(EditText) findViewById(R.id.searchBox3);
searchBox4=(EditText) findViewById(R.id.searchBox4);
searchBox5=(EditText) findViewById(R.id.searchBox5);
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
try{
FileOutputStream fos =new FileOutputStream(myExternalFile);
fos.write(searchBox.getText().toString().getBytes());
fos.write(searchBox1.getText().toString().getBytes());
fos.write(searchBox2.getText().toString().getBytes());
fos.write(searchBox3.getText().toString().getBytes());
fos.write(searchBox4.getText().toString().getBytes());
fos.write(searchBox5.getText().toString().getBytes());
fos.close();
}
catch (IOException e )
{
e.printStackTrace();
}
searchBox .setText("");
searchBox1.setText("");
searchBox2.setText("");
searchBox3.setText("");
searchBox4.setText("");
searchBox5.setText("");
Toast.makeText(getApplicationContext(), "Registered", Toast.LENGTH_SHORT).show();
}
});
read = (Button) findViewById(R.id.read);
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
searchBox.setText(myData);
searchBox1.setText(myData);
searchBox2.setText(myData);
searchBox3.setText(myData);
searchBox4.setText(myData);
searchBox5.setText(myData);
response.setText("SampleFile.txt data retrieved from Internal Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
save.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filePath), fileName);
}
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}}
I have created a sample file to save those credentials. i need to store those somewhere safe where user cant access or modify those files.
What you're searching for are SharedPreferences.
Here's a tutorial on how to use it: https://developer.android.com/training/data-storage/shared-preferences
As it was mentioned by #Pascal - you can use shared preferences. I would clarify such topic. I think that using file for such data has some bad sides:
So huge actions with data
Easy to get it - one the other hand when a user will have root access he will be able to see SP (shared prefereces) data too.
So, as I see you would like to save some string data to apps storage. For writing data you need firstly to define global SP variable:
SharedPreferences mSettings;
than inside onCreate() method assign value:
mSettings = getSharedPreferences("app_data", Context.MODE_PRIVATE);
After it you can read/write some data. General types are mentioned here. So data writing you have to set key-value info into app storage:
mSettings = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key_name", "some string data");
editor.apply();
and to read written data use such code:
String dataString = mSettings.getString("key_name", "default string value");
you can get such variables from any screen of your app. So, you can see that such method is lighter that files writing.

SharedPreferences to save login data

In my application a user starts the application and try to logs in , the application checks whether there is in the Shared Set < User> with the list of credentials for all users , if it does not exist create it from scratch .... Here's my question is how do I check in the shared existence of this Set < User>?
Here, have a look at my code for shared preferences. This code will save your login data.
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is simple login code we can store data by putString method of Editor class
SharedPreferences.Editor editor = sp.edit();
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
full code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
btn = (Button) findViewById(R.id.button);
btn3 = (Button) findViewById(R.id.button3);
btn3 = (Button) findViewById(R.id.button3);
ct = (Button) findViewById(R.id.ct);
final SQLiteDatabase db = openOrCreateDatabase("DemoDb",MODE_ENABLE_WRITE_AHEAD_LOGGING,null);
ct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.execSQL("create table login(LoginId varchar(10) primary key,Password varchar(10),Name varchar(10));");
}
});
sp = getSharedPreferences("myLogin", MODE_PRIVATE);
if(!sp.getBoolean("LogInMode",false)) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( et1.getText().toString().length()==0 || et2.getText().toString().length()==0){
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}else {
String data = "content://com.example.maity.dbdemo.123/DemoDb";
Uri uri = Uri.parse(data);
ContentResolver resolver = getContentResolver();
String[] ar = {"", ""};
ar[0] = et1.getText().toString().trim();
ar[1] = et2.getText().toString().trim();
final Cursor c = resolver.query(uri, null, null, ar, null);
if (c.moveToNext()) {
if ((et1.getText().toString().trim().equals(c.getString(c.getColumnIndex("LoginId")).toString())) &&
(et2.getText().toString().trim().equals(c.getString(c.getColumnIndex("Password")).toString()))) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("LogInMode", true);
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}else {
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}
}
}
});
}
else{
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}
If your login api response is like below
{
"status": true,
"message": "Login Success",
"data": {
"user_id": "1",
"first_name": "Ketan",
"last_name": "Ramani",
"username": "ketanramani"
}
}
Then you can save all login response by dynamically using below code
SharedPreferences preferences = getApplicationContext().getSharedPreferences("LoginPref", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(dataObject.toString());
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
editor.putString(key, jsonObject.optString(key)).apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
Your data will save in sharedpreferences like below
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="user_id">1</string>
<string name="first_name">Ketan</string>
<string name="last_name">Ramani</string>
<string name="username">ketanramani</string>
</map>

How do i use Internal storage for different activity

Below page is the one having data i want to save from user.
How do I make this data to be read on next activity having a editText of text view?
And is this Code correct?
AddMoney.class
public class AddMoney extends AppCompatActivity {
Button b1;
EditText et;
enter code here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_money);
b1 = (Button) findViewById(R.id.b1);
et = (EditText) findViewById(R.id.et);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
AlertDialog.Builder b = new AlertDialog.Builder(AddMoney.this);
b.setIcon(R.mipmap.ic_launcher);
int val = Integer.parseInt(et.getText().toString());
b.setTitle("MONEY ADDED");
String msg = "₹" + val + " has been added in your wallet";
b.setMessage(msg);
b.setCancelable(false);
b.setPositiveButton("OK",null);
AlertDialog d = b.create();
d.show();
}
});
}
public void saveData() {
try {
FileOutputStream fileOutputStream = openFileOutput("Expenses.txt", MODE_PRIVATE);
fileOutputStream.write(et.getText().toString().getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As a better approach you can make use of SharedPreference as SripadRaj suggested.
on the first activity,where you save the data:
SharedPreference sp =getSharedPreferences("app_package_name", Context.MODE_PRIVATE);
sp.putString("expense",et.getText().toString());
sp.apply();
On another activity:
SharedPreference sp =getSharedPreferences("app_package_name", Context.MODE_PRIVATE);
String expense = sp.getString("expense","0.0");

store edited values in edittext fields after changed paramaters

public class ActivityEditParent extends AppCompatActivity {
private static final String TAG="ActivityEditParent";
CustomEditText etFirstName,etLastName,etEmail,etPhone;
public static ConnectionDetector detector;
private static final String URL = "http://hooshi.me.bh-in-13.webhostbox.net/index.php/parents/editprofile";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private CustomButton btnSave;
private String parentFirstName,parentLastName,parentPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_parent);
getSupportActionBar().hide();
detector = new ConnectionDetector(ActivityEditParent.this);
getUIComponents();
}
private void getUIComponents(){
etFirstName = (CustomEditText) findViewById(R.id.edit_first_name);
etLastName = (CustomEditText) findViewById(R.id.edit_last_name);
etEmail = (CustomEditText) findViewById(R.id.edit_email_address);
etPhone = (CustomEditText) findViewById(R.id.edit_phone_number);
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editParent();
}
});
TextView title = (TextView) findViewById(R.id.toolbar_title);
ImageButton back = (ImageButton) findViewById(R.id.toolbar_back);
title.setText("Edit parent");
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goBack();
}
});
sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
String fName = sharedPreferences.getString(AppConstants.PARENT_FNAME,AppConstants.fName);
String lName = sharedPreferences.getString(AppConstants.PARENT_LNAME,AppConstants.lName);
String email = sharedPreferences.getString(AppConstants.PARENT_EMAIL,AppConstants.email);
String phone = sharedPreferences.getString(AppConstants.PARENT_MOBILE,AppConstants.mobile);
etFirstName.setText(fName);
etLastName.setText(lName);
etPhone.setText(phone);
etEmail.setText(email);
}
private void goBack() {
startActivity(new Intent(getApplicationContext(), ActivityEditDetails.class));
finish();
}
private void editParent(){
SharedPreferences preferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonParam = null;
parentFirstName = etFirstName.getText().toString().trim();
parentLastName = etLastName.getText().toString().trim();
parentPhone = etPhone.getText().toString().trim();
if (detector.checkInternet()){
jsonParam = new JSONObject();
JSONObject header = new JSONObject();
try {
jsonParam.put("parentId",preferences.getString(AppConstants.PARENT_ID,""));
jsonParam.put("parentFN",parentFirstName);
jsonParam.put("parentLN",parentLastName);
jsonParam.put("parentPhone",parentPhone);
jsonParam.put("apiAccessKey",preferences.getString(AppConstants.API_ACCESS_KEY,""));
header.put("parent",jsonParam);
Log.d("POST PARAMETERS:",""+header);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, header, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response:",""+response);
String json_status = null;
try {
json_status = response.getString("status");
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
}
}
In the response After getting success message I want save the edited details in in respective edit text fields please help.After success message I am moving to home screen through intent and again I get back to this screen it is showing the previous details only.
all happens here :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
once you have a success response save the edited values on the preferences, for example etFirstName, save it is new value to the corresponding preference :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
editor.putString(AppConstants.PARENT_FNAME, parentFirstName);
editor.apply(); //don't forget this
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
any way you're creating the editor but not using it.
you want to save data after download from network or after an edit in edit text fields was made??
if from network add some save method execution statement in code where you download data was successful
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
// here you have successful received data so u can map them to edit text or save in shared prefs
// add method to save data here
saveData(response);
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
private void saveData(JSONObject response) {
// use JSon response object save here to shared preferences
// see how to load data from json object
// https://processing.org/reference/JSONObject_getString_.html
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
sharedPreferences.putString(....).apply;
// or set edit text controls with JSon data
}
to save edit text changes you have two choices :
add to layout save button (you have one) button and set on click listener with method to save data:
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData(v);
}
});
private void saveData(View view) {
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// get string from edit text widget
String firstName = etFirstName.getString.toString();
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// save to shared prefs firstName wher NAME_KEY is string to identified your saved data for later use - to load
sharedPreferences.putString(NAME_KEY,firstName).apply;
}
private void loadDataFromSharedPredferences(View view) {
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// load data from shared prefs firstName wher NAME_KEY is string to identified data to load
String firstName = sharedPreferences.getString(NAME_KEY,firstName);
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// set string to edit text widget
etFirstName.setText(firstName);
}
add on text change listener for edittext widgets
ps. you need to clarify - write a exactly steps of what you want to do achieve
load data from network ? then save ?
or save request date ?
or save result data ?

obtaining the value of an EditText inside Asynctask

I am trying to make an app which uses FTP and changes the filename to a combination of 2 EditTexts. to properly upload it i am uploading it inside a 'asynctask' ,this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
String week = "w" + week_text.getText().toString() + "_";
String pagina = "p" + pagina_text.getText().toString() + ".jpg";
Button foto_keuze = (Button)findViewById(R.id.foto_keuze_button);
Button upload_button = (Button)findViewById(R.id.upload_button);
Typeface Impact = Typeface.createFromAsset(getAssets(), "fonts/Impact.ttf");
foto_keuze.setTypeface(Impact);
upload_button.setTypeface(Impact);
targetImage = (ImageView)findViewById(R.id.imageView);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public void upload_klik (View view) {
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
upload_task.execute(week_text, pagina_text);
}
protected class upload_task extends AsyncTask<EditText, Object, String> {
#Override
protected String doInBackground(EditText... params) {
EditText w = params[0];
EditText p = params[1];
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String ret = "Done!";
if(!bundle.isEmpty()) {
String afdeling_url = bundle.getString("afdeling_url", "DKW/");
String afdeling_preFix = bundle.getString("afdeling_preFix", "dkw");
String locatie_url = bundle.getString("locatie_url", "delf_wend");
String new_fileName = afdeling_preFix + w + p;
File f = new File(foto_path);
File sdcard = Environment.getExternalStorageDirectory();
File to = new File(sdcard, new_fileName);
f.renameTo(to);
if(f == null){
Toast.makeText(upload.this, "Geen foto geselecteerd", Toast.LENGTH_SHORT).show();
}
if(f != null) {
try{
Toast.makeText(getApplicationContext(), afdeling_url + afdeling_preFix, Toast.LENGTH_SHORT).show();
client.setPassive(true);
client.setAutoNoopTimeout(30000);
client.connect(FTP_HOST, 21);
client.login(FTP_USER, FTP_PASS);
client.setType(FTPClient.TYPE_BINARY);
client.changeDirectory(locatie_url + afdeling_url);
client.upload(to, new FTP_LISTENER());
restart();
}
catch (Exception e){
e.printStackTrace();
try {
client.disconnect(true);
Toast.makeText(getApplicationContext(), "Upload voltooid", Toast.LENGTH_SHORT);
}
catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
return ret;
}
}
My problem is as follows: i want to use the values of week_text.getText().toString(); and pagina_text.getText().toString(); in my Asynctask, but i cant find a way to achieve this.
i also have zero clue on what to do with the parameters behind Asynchtask, i have looked it up multiple times but it just doesnt make sense when using it for a FTP upload.
Help please ._.
Just pass String values to execute method like below
new upload_task().execute(edtText1.getText.toString,edtText2.getText.toString);
then
#Override
protected String doInBackground(String... params) {
String editText1Value = params[0];
String editText2Value = params[1];
///then do what ever you want
}
Just add the EditText` as parameter:
protected class upload_task extends AsyncTask<EditText, Object, String> {
#Override
protected String doInBackground(EditText... params) {
EditText editText1 = params[0];
EditText editText2 = params[1];
///rest of code:
}
}
And call it:
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
new upload_task().execute(week_text, paging_text);

Categories

Resources