0

apps/main/src/asset에있는 txt 파일에서 읽으려고합니다. 텍스트에는 %로 시작하는 포춘 쿠키가 들어 있습니다. 하지만 내 주요 문제는 파일을 여는 중입니다. Android Studio에서 파일을 여는 올바른 방법은 무엇입니까? 자산 폴더를 만들고 거기에 텍스트 파일을 넣었습니다. 그러나 나는 오류가 계속 발생합니다. 누군가가 코드/오류를보고 파일에 액세스하는 올바른 방법을 말해 줄 수 있다면. 나는이 내 코드입니다 < 을 추가자산 폴더에있는 텍스트 파일에 액세스 할 수 없습니다.

package com.example.jorge.whatsyourname; 

import android.content.res.AssetManager; 
import android.net.Uri; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

import com.google.android.gms.appindexing.Action; 
import com.google.android.gms.appindexing.AppIndex; 
import com.google.android.gms.appindexing.Thing; 
import com.google.android.gms.common.api.GoogleApiClient; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.Scanner; 

import static java.lang.System.in; 

public class MainActivity extends AppCompatActivity { 
    //variables declaration 
    EditText nameTxt; 
    EditText lastnameTxt; 
    EditText dobTxt; 
    TextView cookieOutTxt; 

    int random = 0; //generated random number 
    int max = 0; //value to be assign on execution (number of fortunes) 
    ArrayList<String> fortunes; //all fortunes will be stored here 

    //opening text file located in assets directory 
    AssetManager assetManager = getAssets(); 
    InputStream is = assetManager.open("fortuneCookie.txt"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

    public MainActivity() throws IOException { 
    } 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //references 
     nameTxt = (EditText) findViewById(R.id.nameTxt); 
     lastnameTxt = (EditText) findViewById(R.id.lastnameTxt); 
     dobTxt = (EditText) findViewById(R.id.dobTxt); 
     cookieOutTxt = (TextView) findViewById(R.id.cookieOutTxt); 

     final Button cookieBtn = (Button) findViewById(R.id.cookieBtn); 
     cookieBtn.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       //scan file if line contains % count, else add to fortune arraylist 
       boolean flag = false; 
       String phrase = ""; 
       try { 
        while (br.readLine() != null && !br.readLine().isEmpty()) { 
         String line = br.readLine(); 
         //System.out.println(line); 
         if (line.contains("%") && !flag) { 
          flag = true; 
         } 
         else if (line.contains("%") && flag) { 
          max++; 
          phrase = ""; 
         } 
         else { 
          phrase = phrase + line; 
          fortunes.add(max, phrase); 
         } 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       //generating a random fortune 
       random = (int) (Math.random() * max + 1); 
       //printing output to screen 
       cookieOutTxt.setText(fortunes.get(random)); 

      } 
     }); 

    } 


    public Action getIndexApiAction() { 
     Thing object = new Thing.Builder() 
       .setName("Main Page") // TODO: Define a title for the content shown. 
       // TODO: Make sure this auto-generated URL is correct. 
       .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) 
       .build(); 
     return new Action.Builder(Action.TYPE_VIEW) 
       .setObject(object) 
       .setActionStatus(Action.STATUS_TYPE_COMPLETED) 
       .build(); 
    } 
} 

내 app.iml 파일

<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" /> 
    <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" /> 
    <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" /> 
    <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" /> 

이러한 3 개 라인이 하나가 추가

adb shell am start -n "com.example.jorge.whatsyourname/com.example.jorge.whatsyourname.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER 
Client not ready yet..Waiting for process to come online 
Connected to process 1573 on device Nexus_5_API_22 [emulator-5554] 
I/art: Not late-enabling -Xcheck:jni (already on) 
D/AndroidRuntime: Shutting down VM 


        --------- beginning of crash 
E/AndroidRuntime: FATAL EXCEPTION: main 
        Process: com.example.jorge.whatsyourname, PID: 1573 
        java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.jorge.whatsyourname/com.example.jorge.whatsyourname.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference 
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236) 
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) 
         at android.app.ActivityThread.access$800(ActivityThread.java:151) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:135) 
         at android.app.ActivityThread.main(ActivityThread.java:5257) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at java.lang.reflect.Method.invoke(Method.java:372) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference 
         at android.content.ContextWrapper.getAssets(ContextWrapper.java:80) 
         at com.example.jorge.whatsyourname.MainActivity.<init>(MainActivity.java:40) 
         at java.lang.reflect.Constructor.newInstance(Native Method) 
         at java.lang.Class.newInstance(Class.java:1606) 
         at android.app.Instrumentation.newActivity(Instrumentation.java:1066) 
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226) 
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)  
         at android.app.ActivityThread.access$800(ActivityThread.java:151)  
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  
         at android.os.Handler.dispatchMessage(Handler.java:102)  
         at android.os.Looper.loop(Looper.java:135)  
         at android.app.ActivityThread.main(ActivityThread.java:5257)  
         at java.lang.reflect.Method.invoke(Native Method)  
         at java.lang.reflect.Method.invoke(Method.java:372)  
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  
I/Process: Sending signal. PID: 1573 SIG: 9 
Application terminated. 

오류 로그 내 "Fortune Cookie.iml"파일

<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" /> 

답변

0

까지 그리고 super.onCreate() 이후까지 Activity 또는 그 수퍼 클래스에서 상속 한 메소드를 호출하지 마십시오.) (

assetManager = getAssets(); 
is = assetManager.open("fortuneCookie.txt"); 
br = new BufferedReader(new InputStreamReader(is)); 
+0

은 그래서 당신은 선언 할 수 있지만에서 onCreate 때까지 아무것도를 초기화하지 :

AssetManager assetManager = getAssets(); InputStream is = assetManager.open("fortuneCookie.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

로 :

AssetManager assetManager; InputStream is; BufferedReader br; 

를 넣어이 줄을 super.onCreate() 후 그래서

교체 방법? – miatech

+0

@miatech : 상속 된 메서드를 사용하지 않고 그냥 초기화 할 수 있습니다. 당신이 상속받은 많은 메소드들은'Activity'가 완전히 셋업 될 때까지 작동하지 않을 것이고, 그 후의 첫 번째 컨트롤 포인트는'onCreate()'메소드입니다. – CommonsWare

관련 문제