0

J'essaie de lire à partir d'un fichier txt situé apps/main/src/asset. Le texte contient des cookies de fortune qui commencent par%. Mais mon problème principal c'est l'ouverture du fichier. Quelle est la bonne façon d'ouvrir un fichier dans Android Studio. J'ai créé le dossier des ressources et y ai placé mon fichier texte. Mais je continue à avoir des erreurs. Si quelqu'un peut regarder le code/les erreurs et me dire la bonne façon d'accéder au fichier. J'ai aussi ajouté < ceci est mon codeimpossible d'accéder au fichier texte dans le dossier des ressources

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

erreur journal

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. 

en plus je ces 3 lignes dans mon fichier 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" /> 

et celui-ci dans mon Fichier "Fortune Cookie.iml"

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

Répondre

0

N'appelez pas les méthodes héritées de Activity ou de ses superclasses jusqu'à onCreate(), et généralement après super.onCreate().

, remplacez:

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

avec:

AssetManager assetManager; 
InputStream is; 
BufferedReader br; 

et mettre ces lignes après super.onCreate():

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

vous pouvez donc déclarer, mais pas initialiser quoi que ce soit jusqu'à ce que onCreate() méthode? – miatech

+0

@miatech: Vous pouvez initialiser des choses, n'utilisant pas beaucoup de méthodes héritées. La plupart des méthodes dont vous héritez ne fonctionneront qu'après la configuration complète de 'Activity', et votre premier point de contrôle après cela est la méthode' onCreate() '. – CommonsWare