0

I have developed an android app that enable the user to register by his/her mobile phone number. I want my app to save the phone number so that next time the user open the app, there will be no need to enter the phone number again, analogous to Whatsapp.. Here is my code, but it doesn't work and I still have to enter the phone number each time I open the app, besides, after adding this code to my app, the app became so heavy and slow.

  if (android.os.Build.VERSION.SDK_INT > 9) 
  {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    try {
        TelephonyManager tMgr = (TelephonyManager) getApplicationContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
        mPhoneNumber = tMgr.getLine1Number().toString();
    } catch (Exception e) {
        String EE = e.getMessage();
    }
    if (mPhoneNumber == null) {
    try {
        fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);

        fIn = openFileInput("textfile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);
        char[] inputBuffer = new char[50];
        if (isr.read(inputBuffer) == 0) {

        }

    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Warrning");
    alert.setMessage("Please Set Your Phone number");
    final EditText input = new EditText(this);
    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            mPhoneNumber = input.getText().toString();
            try {
                fIn = openFileInput("textfile.txt");
                InputStreamReader isr = new InputStreamReader(fIn);
                char[] inputBuffer = new char[50];
                if (isr.read(inputBuffer) == 0) {
                    OutputStreamWriter osw = new OutputStreamWriter(fOut);
                    // ---write the string to the file---
                    osw.write(mPhoneNumber);
                    osw.flush();
                    osw.close();
                    // ---display file saved message---
                    Toast.makeText(getBaseContext(),
                            "Phone number saved successfully!",
                            Toast.LENGTH_SHORT).show();
                    // ---clears the EditText---
                    input.setText("");
                } else {
                    int charRead;
                    while ((charRead = isr.read(inputBuffer)) > 0) {
                        // ---convert the chars to a String---
                        String readString = String.copyValueOf(inputBuffer,
                                0, charRead);
                        mPhoneNumber = readString;
                        inputBuffer = new char[50];
                    }
                    // ---set the EditText to the text that has been
                    // read---

                    Toast.makeText(getBaseContext(),
                            "Phone number read successfully!",
                            Toast.LENGTH_SHORT).show();
                }

            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            int UserServiceId = CallLogin(mPhoneNumber);
            if (UserServiceId > 0) {
                Intent Service = new Intent(MainScreeen.this,
                        RecipeService.class);
                Service.putExtra("UserId", UserServiceId);
                startService(Service);
            } else {
                Intent Reg = new Intent(MainScreeen.this,
                        Regsteration.class);
                Reg.putExtra("PhoneNumber", mPhoneNumber);
                startActivity(Reg);
            }
        }
    });
    alert.show();
    } else {

        int UserServiceId = CallLogin(mPhoneNumber);
        if (UserServiceId > 0) {
            Intent Service = new Intent(MainScreeen.this,
                    RecipeService.class);
            Service.putExtra("UserId", UserServiceId);
            startService(Service);
        } else {
            Intent Reg = new Intent(MainScreeen.this, Regsteration.class);
            Reg.putExtra("PhoneNumber", mPhoneNumber);
            startActivity(Reg);
        }
    } 

Please help me to figure it out !!

4

2 回答 2

0

好吧,在这段代码中:

if (mPhoneNumber == null) {
try {
    fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);
    fIn = openFileInput("textfile.txt");

您打开文件进行输出,这将破坏您已经写入其中的任何内容。稍后,当您尝试从该文件中读取时,一切都为时已晚。

另外,这里的代码太多了。不要重新发明轮子。您不需要一次读取一个字符的文件。如果您只想将字符串写入文件,然后再次将其读回,请使用DataInputStreamand ,您可以使用andDataOutputStream直接读取/写入字符串。这是一个读取文件的简单示例:readUTF()writeUTF()

    DataInputStream in = new DataInputStream(openFileInput("textfile.txt"));
    String contents = in.readUTF();

编写文件使用:

    DataOuputStream out = new DataOutputStream(openFileOutput("textfile.txt", 0));
    out.writeUTF(phoneNumber);

显然,您需要添加 try/catch 块并处理异常并确保关闭 finally块中的流,但如果您这样做,您最终会得到更少的代码。

于 2013-05-13T20:06:11.260 回答
0

为了帮助你,我给你我的活动示例,以便在文件中读取和写入数据:

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class StoreDataActivity extends Activity {

    private static final String TAG = "ExerciceActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);

        writeFileOnDisk("toto.txt", "Bienvenue chez Android");

        String content = readFileOnDisk("toto.txt");
        Log.v(TAG, "content=" + content);
    }

    private void writeFileOnDisk(String filename, String data) {

        try {
            FileOutputStream fos = openFileOutput(filename, this.MODE_PRIVATE);
            fos.write(data.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private String readFileOnDisk(String filename) {

        int inChar;
        StringBuffer buffer = new StringBuffer();

        try {
            FileInputStream fis = this.openFileInput(filename);
            while ((inChar = fis.read()) != -1) {
                buffer.append((char) inChar);
            }
            fis.close();

            String content = buffer.toString();

            return content;

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
于 2013-05-13T20:15:15.643 回答