【问题标题】:Save mobile number in a file android将手机号码保存在文件中 android
【发布时间】:2013-05-13 19:38:15
【问题描述】:

我开发了一个 android 应用程序,使用户能够通过他/她的手机号码进行注册。我希望我的应用程序保存电话号码,以便下次用户打开应用程序时,无需再次输入电话号码,类似于 Whatsapp.. 这是我的代码,但它不起作用,每次打开应用程序时我仍然需要输入电话号码,此外,在我的应用程序中添加此代码后,应用程序变得如此沉重和缓慢。

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

请帮我弄清楚!!

【问题讨论】:

    标签: android android-intent try-catch fileinputstream fileoutputstream


    【解决方案1】:

    好吧,在这段代码中:

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

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

    另外,这里的代码太多了。不要重新发明轮子。您不需要一次读取一个字符的文件。如果您只想将字符串写入文件,然后再将其读回,请使用DataInputStreamDataOutputStream,您可以直接使用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 块中的流,但如果您这样做,最终代码会少很多。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多