1

I'm trying to permanently store three strings as user preferences for my Android application. These three strings are a url, username, and password. I don't really understand SharedPreferences, so I tried to use internal file storage. I'm not able to retrieve the three strings from the file, and I get a runtime error. I know I probably coded something wrong, but I'm just not proficient enough in Android to understand data storage. Could somebody help me out?

Preferences activity:

package com.amritayalur.mypowerschool;



import java.io.File;
import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
 import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
FileOutputStream fos;
String url = "";
String FILENAME = "InternalStrings";
 String str;
 String username;
 String password;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
    textViewTitle = (TextView) findViewById(R.id.textViewTitle);
    textViewDesc = (TextView) findViewById(R.id.textViewDesc);

    editTextURL = (EditText) findViewById(R.id.editTextURL);
    editTextUser = (EditText) findViewById(R.id.editTextUser);
    editTextPass = (EditText) findViewById(R.id.editTextPass);
    //Start TextView
    textViewTitle.setText("MyPowerSchool");
    try {
        fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    //button listener
    buttonSubmit.setOnClickListener(new View.OnClickListener() {

         @Override
            public void onClick(View v) 
            {
                if (  ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) ) 
                {
                     url = editTextURL.getText().toString();
                     username = editTextUser.getText().toString();
                     password = editTextPass.getText().toString();
                    //Saving data via File
                    /* File f = new File(FILENAME);
                     try {
                        fos = new FileOutputStream(f);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                        */
                     try {
                     fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

                        fos.write(url.getBytes());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                     try {
                        fos.write(username.getBytes());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                     try {
                        fos.write(password.getBytes());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                   try {
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }



                    // TODO Auto-generated method stub
                    Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);    
                    //i.putExtra("pschoolurl", editTextURL.getText().toString());
                    //i.putExtra("pschooluser", editTextUser.getText().toString());
                    //i.putExtra("pschoolpass", editTextPass.getText().toString());
                   // get the text here
                   final int result = 1;
                   startActivityForResult(i, result); 
                }
            };




});}}

Activity in which I am trying to retrieve credentials:

package com.amritayalur.mypowerschool;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;



public class creds extends Activity {

String url;
String username;
String password;
TextView TextViewTest;

    String FILENAME = "InternalStrings";
;
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);




    Intent intent = getIntent();
    //String url = intent.getExtras().getString("pschoolurl");
    //String username = intent.getExtras().getString("pschooluser");
    //String password = intent.getExtras().getString("pschoolpass");
    String collected = null;
    FileInputStream fis = null;
    try {
        fis = openFileInput(FILENAME);
        byte[] dataArray = new byte[fis.available()];
        while (fis.read(dataArray) != -1 ){
            collected = new String(dataArray);

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            fis.close();
            TextViewTest.setText(collected);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }






}
}

The commented text is a result of me trying to mess around with different aspects of the code.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Slicekick
  • 2,119
  • 5
  • 24
  • 35
  • I'm using these tutorials to kick me off with Android, he may have something. http://www.vogella.de/articles/Android/article.html –  Feb 19 '12 at 15:21

1 Answers1

5

SharedPreferences is not too difficult.

To add something to the preferences:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
Editor edit = prefs.edit(); //Needed to edit the preferences

edit.putString("name", "myname");  //add a String
edit.putBoolean("rememberCredentials", true); //add a boolean

edit.commit();  // save the edits.

To read something:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
String name = prefs.getString("name", "defaultName"); //get a String
boolean rememberCredentials = prefs.getBoolean("rememberCredentials", true); //get a boolean. 
//When the key "rememberCredentials" is not present, true is returned.
nhaarman
  • 98,571
  • 55
  • 246
  • 278
  • SharedPreferences is great, but I would worry about security implications if the phone is rooted and the phone gets stolen. Technically they could get access to the stored preferences? – Knossos Feb 19 '12 at 15:30
  • I don't think saving to a file will make any difference. Either way, you probably don't want to store the password in plaintext, I'd rather use a hash or something. – nhaarman Feb 19 '12 at 15:39
  • I'm not worried about storing the password in plaintext, it isn't something that would reveal personal data or anything. When I try to get the preferences, it says the method getString in the type SharedPreferences is not applicable for the arguments (string). Any advice?\ – Slicekick Feb 19 '12 at 16:25
  • Oh, I'm sorry, I made a mistake. A `get` command from the preferences needs a default value. So when the key is not in the preference, the defaultValue is returned. Edited the answer. – nhaarman Feb 19 '12 at 17:04
  • Thanks, it should work but my app is force closing now. Do I need to edit the AndroidManifest.xml in any way? – Slicekick Feb 19 '12 at 17:46
  • What is the exception that occurs? You should find it in the logcat. – nhaarman Feb 19 '12 at 17:47
  • @C_B Since when? I cannot find any documentation about it being deprecated. – nhaarman Apr 08 '14 at 12:05
  • ah you're right, `apply()` is simply newer. It was added after the return statement for `commit()` was rarely looked at. [SO question](http://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-shared-preference). I thought I read that somewhere, my bad. – C_B Apr 08 '14 at 12:14
  • Ah yes, indeed. Perhaps we all should move to `apply()` :) – nhaarman Apr 08 '14 at 12:15