iT邦幫忙

0

怎麼讀取到內部儲存資料.txt

各位高手好,我想問關於android studio要如何讀取到內部儲存資料.txt,因為裡面程式碼都是照著書打的,但卻沒有說如何從其中一個ativity FileOutputStream 輸入資料到我設的login.txt後從另一個ativity FileInputStream讀取資料出來

然後由於我也是剛觸碰android studio 所以很多地方不是很清楚,也有可能是別的地方出錯,請各位幫我看一下程式碼,這已經困擾我好多天了,試了一堆方法結果都會閃退

package com.example.projecttest;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

public class user3 extends AppCompatActivity {
    private Button registerok, cancel;
    private EditText id,pwd,edtContent;
    private static final String FILENAME="login.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user3);
        id = (EditText)findViewById(R.id.id);
        pwd = (EditText)findViewById(R.id.pwd);
        edtContent = (EditText)findViewById(R.id.edtContent);
        registerok = (Button) findViewById(R.id.registerok);
        cancel = (Button) findViewById(R.id.cancel);
        registerok.setOnClickListener(listener);
        cancel.setOnClickListener(listener);
    }

    private Button.OnClickListener listener = new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.registerok:
                    if(id.getText().toString().equals("") ||pwd.getText().toString().equals("")){
                        Toast.makeText(getApplicationContext(), "帳號及密碼都必須輸入!", Toast.LENGTH_LONG) .show();
                        break;
                    }
                    //FileOutputStream fout=null; //建立寫入資料流
                    BufferedOutputStream buffout=null;
                    try {
                        FileOutputStream fout=openFileOutput(FILENAME,MODE_APPEND);
                        //fout=openFileOutput(FILENAME, MODE_APPEND);
                        buffout=new BufferedOutputStream(fout);
                        //寫入帳號及密碼
                        buffout.write(id.getText().toString().getBytes());
                        buffout.write("\n".getBytes());
                        buffout.write(pwd.getText().toString().getBytes());
                        buffout.write("\n".getBytes());
                        buffout.close();
                    }	catch(Exception e)	{
                        e.printStackTrace();
                    }
                    Intent intent = new Intent();
                    intent.setClass(user3.this, MainActivity.class);
                    startActivity(intent);
                    break;
                case R.id.cancel:  //結束
                    finish();


            }
        }

    };
}
package com.example.projecttest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
    private EditText et_account, et_password;
    private Button sign_up,login;
    private String[] loginall;
    private File filename;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_account = (EditText)findViewById(R.id.et_account);
        et_password= (EditText)findViewById(R.id.et_password);
        sign_up = (Button) findViewById(R.id.sign_up);
        login = (Button) findViewById(R.id.login);
        sign_up.setOnClickListener(listener);
        login.setOnClickListener(listener);
    }
    private void load() {
        try {
            FileInputStream fin = openFileInput("login.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(fin);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fin, "utf-8"));
            String line="",data="";
            while ((line = reader.readLine()) != null) {
                data=data+line+"\n";
            }
            loginall=data.split("\n");
            fin.close();
            inputStreamReader.close();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "error!", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
    private Button.OnClickListener listener = new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.sign_up:
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, user3.class);
                    startActivity(intent);
                    break;
                case R.id.login:
                    if(et_account.getText().toString().equals("") || et_password.getText().toString().equals("")){
                        Toast.makeText(getApplicationContext(), "帳號及密碼都必須輸入!", Toast.LENGTH_LONG) .show();
                        break;
                    }
                    Boolean flag=false;
                    for(int i=0;i<loginall.length;i+=2){
                        if(et_account.getText().toString().equals(loginall[i])){ //帳號存在
                            flag=true;
                            if(et_password.getText().toString().equals(loginall[i+1])){ //密碼正確
                                new AlertDialog.Builder(MainActivity.this)
                                        .setTitle("登入")
                                        .setMessage("登入成功!\n歡迎使用本應用程式!")
                                        .setPositiveButton("確定", new DialogInterface.OnClickListener()
                                        {
                                            public void onClick(DialogInterface dialoginterface, int i) {
                                                Intent intent1=new Intent();
                                                intent1.setClass(MainActivity.this,user8.class);
                                                startActivity(intent1);
                                            }
                                        })
                                        .show();
                            } else {
                                Toast.makeText(getApplicationContext(), "密碼不正確!", Toast.LENGTH_LONG) .show();
                                et_password.setText("");
                                break;
                            }
                        }
                    }
                    if(!flag) {
                        Toast.makeText(getApplicationContext(), "帳號不正確!", Toast.LENGTH_LONG) .show();
                        et_account.setText("");
                        et_password.setText("");
                    }
                    break;





            }
        }

    };
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.projecttest.MainActivity">


    <TextView
        android:id="@+id/tv_login"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_marginTop="125dp"
        android:layout_marginBottom="76dp"
        android:text="登入"
        android:textSize="40dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="331dp"
        android:layout_height="157dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.437">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp">

            <TextView
                android:id="@+id/login_account"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:gravity="center"
                android:text="帳號:"
                android:textColor="@color/black"
                android:textSize="17sp" />

            <EditText
                android:id="@+id/et_account"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"
                android:layout_toRightOf="@+id/login_account"
                android:gravity="left|center"
                android:hint="请输入帳號"
                android:inputType="text"
                android:maxLength="12"
                android:textColor="@color/black"
                android:textSize="17sp" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp">

            <TextView
                android:id="@+id/login_password"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:gravity="center"
                android:text="密碼:"
                android:textColor="@color/black"
                android:textSize="17sp" />

            <EditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"
                android:layout_toRightOf="@+id/login_password"
                android:gravity="left|center"
                android:hint="请输密碼"
                android:inputType="textPassword"
                android:textColor="@color/black"
                android:textSize="17sp" />

        </RelativeLayout>


    </LinearLayout>

    <Button
        android:id="@+id/sign_up"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="107dp"
        android:layout_marginLeft="107dp"
        android:layout_marginTop="22dp"
        android:layout_marginEnd="99dp"
        android:layout_marginRight="99dp"
        android:layout_marginBottom="274dp"
        android:text="註冊"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/forget"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout2" />

    <TextView
        android:id="@+id/forget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="22dp"
        android:layout_marginEnd="87dp"
        android:layout_marginRight="87dp"
        android:layout_marginBottom="274dp"
        android:text="忘記密碼"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout2"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="155dp"
        android:layout_marginLeft="155dp"
        android:layout_marginTop="106dp"
        android:layout_marginEnd="168dp"
        android:layout_marginRight="168dp"
        android:layout_marginBottom="169dp"
        android:text="登入"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout2" />

</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="25dp"
    tools:context="com.example.projecttest.user3"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="帳號 : " />
        <EditText
            android:id="@+id/id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密碼 : " />
        <EditText
            android:id="@+id/pwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="性別 : "/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="男"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名 : " />
        <EditText
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
        <Button
            android:id="@+id/registerok"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="確定" />
        <Button
            android:id="@+id/cancel"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="取消" />
    </LinearLayout>

    <EditText
        android:id="@+id/edtContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:textSize="24sp" />

</LinearLayout>

https://ithelp.ithome.com.tw/upload/images/20210519/20137625ovrTUWnjNr.pnghttps://ithelp.ithome.com.tw/upload/images/20210519/20137625WC4Kst5PYU.png

1 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2021-05-20 11:03:57
最佳解答

https://ithelp.ithome.com.tw/upload/images/20210520/20001787xNIgV8bofI.png
https://ithelp.ithome.com.tw/upload/images/20210520/20001787x9NVUm2jGS.png
https://ithelp.ithome.com.tw/upload/images/20210520/20001787MllvyMldcq.png

總共改了以下幾個地方:

1.res/values/colors.xml
裡面要定義 <color name="black">#000000</color>

2.登入成功後把底下的 user8 改成 user3
intent1.setClass(MainActivity.this,user8.class);

3.讀文字檔改成寫死在程式裡,用以下這段取代原本的 load
private void load() {
    String data = "id1\npassword1\nid2\npassword2\n";
    loginall = data.split("\n");
    Log.d("HERE",loginall.toString());
}

4.在 onCreate 裡最後加 load(); 變成如下
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et_account = (EditText)findViewById(R.id.et_account);
    et_password= (EditText)findViewById(R.id.et_password);
    sign_up = (Button) findViewById(R.id.sign_up);
    login = (Button) findViewById(R.id.login);
    sign_up.setOnClickListener(listener);
    login.setOnClickListener(listener);
    load();
}

再囉嗦一句
比起讀文字檔
你有許多更重要的 Android 設計基礎要先學好

您好謝謝你幫助我~我有個問題想問是load裡面的程式碼的id1,id2是甚麼?我這樣全取代後去跑,雖然沒閃退但是註冊帳號後回登入頁面按登入會一直顯示我帳號錯誤耶

我自己的想法是:
使用者可以註冊很多帳號(user3),在登入頁面確認使用者登入的帳號有沒有在.txt裡,(MAinAtivity),確認有這帳號登入後會跳到ativity(user8)顯示剛剛登入的帳號密碼,然後這頁可以更改密碼,更改的地方.txt裡面也會被更改

小聲說一下我知道我基礎薄弱,但是借的書我看完了還是很多地方不懂QQ,學校的老師也沒有教,老師只教whimsical跟invisionapp做介面但成品卻要我們寫出app來

public class MainActivity extends AppCompatActivity {
    private EditText et_account, et_password;
    private Button sign_up,login;
    private String[] loginall;
    private File filename;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_account = (EditText)findViewById(R.id.et_account);
        et_password= (EditText)findViewById(R.id.et_password);
        sign_up = (Button) findViewById(R.id.sign_up);
        login = (Button) findViewById(R.id.login);
        sign_up.setOnClickListener(listener);
        login.setOnClickListener(listener);
        load();

    }
    private void load() {
        String data = "id1\npassword1\nid2\npassword2\n";
        loginall = data.split("\n");
        Log.d("HERE",loginall.toString());
    }

private Button.OnClickListener listener = new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.sign_up:
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, user3.class);
                    startActivity(intent);
                    break;
                case R.id.login:
                    if(et_account.getText().toString().equals("") || et_password.getText().toString().equals("")){
                        Toast.makeText(getApplicationContext(), "帳號及密碼都必須輸入!", Toast.LENGTH_LONG) .show();
                        break;
                    }
                    Boolean flag=false;
                    for(int i=0;i<loginall.length;i+=2){
                        if(et_account.getText().toString().equals(loginall[i])){ //帳號存在
                            flag=true;
                            if(et_password.getText().toString().equals(loginall[i+1])){ //密碼正確
                                new AlertDialog.Builder(MainActivity.this)
                                        .setTitle("登入")
                                        .setMessage("登入成功!\n歡迎使用本應用程式!")
                                        .setPositiveButton("確定", new DialogInterface.OnClickListener()
                                        {
                                            public void onClick(DialogInterface dialoginterface, int i) {
                                                Intent intent1=new Intent();
                                                intent1.setClass(MainActivity.this,user8.class);
                                                startActivity(intent1);
                                            }
                                        })
                                        .show();
                            } else {
                                Toast.makeText(getApplicationContext(), "密碼不正確!", Toast.LENGTH_LONG) .show();
                                et_password.setText("");
                                break;
                            }
                        }
                    }
                    if(!flag) {
                        Toast.makeText(getApplicationContext(), "帳號不正確!", Toast.LENGTH_LONG) .show();
                        et_account.setText("");
                        et_password.setText("");
                    }
                    break;
           }
        }
    };
}

修改一點
上面的第3點不要,用你原來的 private void load() 就好
但是第4點還是要保留

這樣試試看
更接近你要的結果

啊哈可以了!!謝謝你

我要發表回答

立即登入回答