Использование внутреннего хранилища для хранения учетных данных Android - PullRequest
1 голос
/ 19 февраля 2012

Я пытаюсь сохранить три строки в качестве пользовательских настроек для моего приложения Android.Эти три строки - это URL, имя пользователя и пароль.Я не очень понимаю SharedPreferences, поэтому я попытался использовать внутреннее хранилище файлов.Я не могу получить три строки из файла, и я получаю ошибку во время выполнения.Я знаю, что я, вероятно, что-то неправильно написал, но я не достаточно опытен в Android, чтобы понимать хранение данных.Может ли кто-нибудь мне помочь?

Предпочтения:

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); 
                }
            };




});}}

Активность, в которой я пытаюсь получить учетные данные:

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();
        }
    }






}
}

Текст комментарияя пытаюсь возиться с различными аспектами кода.

1 Ответ

4 голосов
/ 19 февраля 2012

SharedPreferences не так уж сложно.

Чтобы добавить что-то в настройки:

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.

Чтобы прочитать что-то:

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.
...