【问题标题】:InputStream does not want to read from a textfile android studioInputStream 不想从文本文件 android studio 中读取
【发布时间】:2015-07-25 05:46:01
【问题描述】:

我在 java 中使用 android 编程时遇到问题,因为它不想从文本文件中读取。问题是按钮没有添加我试图在异步类中执行的文本。此外,显示文本的按钮不起作用,因为当我按下按钮时,应用程序停止工作。

节目简介:

应用程序从一个从微调器发送到 gameAction 的值开始,然后它将调用文本文件上的名称,该名称将加载到数组列表中的字符串中,即 QuestionBox 类。最后它将在 GameAction 类中提出问题。

如果有不清楚的地方,请发表评论。任何帮助表示赞赏!请原谅我添加了很多代码,但由于不知道该怎么做,我添加了它。

public class QuestionBox extends AsyncTask<Object, Void, Object>{

private Context context;
private Callback callback;
private List<Question> mQuestions;
public QuestionBox(Context context,Callback callback)
{
    mQuestions = new ArrayList<Question>();
    this.callback=callback;
    this.context= context;

}
public  Callback getCallback(){

    return callback;
}


@Override
protected Object doInBackground(Object... params) {

InputStream iS = null;
    try {
        iS = context.getAssets().open("hogskoleprovet.txt");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //System.out.println("Hit kom du");
    BufferedReader reader = new BufferedReader(new InputStreamReader(iS));




    String question, answer, answerOne, answerTwo, answerThree, answerFour;



    try {
        while (reader.readLine() != null) {

            //reading some lines from resource file
            question = reader.readLine();
            answer = reader.readLine();
            answerOne = reader.readLine();
            answerTwo = reader.readLine();
            answerThree = reader.readLine();

            answerFour = reader.readLine();
            Question q = new Question(question, answer, answerOne, answerTwo, answerThree, answerFour);
            mQuestions.add(q);

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

    try {
        reader.close();
        System.out.println("Hit kom du3");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return 0;
}

public interface Callback{
    public void notify_result(List<Question> question_list);





    }





@Override
protected void onPostExecute(Object result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);


}






public int getQuestionsLeft() {
    return mQuestions.size();
}

public Question getRandomQuestion() {

    Random random = new Random();
    int index = random.nextInt(mQuestions.size());
    Question newQuestion = mQuestions.get(index);
    mQuestions.remove(index);
    return newQuestion;
}

}

这是字符串将被发送到的另一种方法:

公共类 gameAction 扩展 ActionBarActivity 实现 QuestionBox.Callback{

private QuestionBox mQuestionBox;
private Question mCurrentQuestion;
private Context context;
private Callback callback;

@Override
public void notify_result(List<Question> question_list) {

}



 protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_action);
    //Kod som kollar vad som skickades med när aktiviteten startades
    Intent callingIntent = getIntent();
    int index = callingIntent.getIntExtra("INDEX",0);

    //Bestäm filnamn beroende på vad som skickades med


    if(index==0){


        mQuestionBox =new QuestionBox(getApplicationContext(), this);
        mQuestionBox.execute("hogskoleprovet.txt");

    }
    else {
        if (index == 1 ) {
            mQuestionBox =new QuestionBox(getApplicationContext(), this);
            mQuestionBox.execute("hogskoleprovet.txt");



        } else if (index == 1) {
            mQuestionBox =new QuestionBox(getApplicationContext(), this);
            mQuestionBox.execute("hogskoleprovet.txt");



        } else if (index == 2) {
            mQuestionBox =new QuestionBox(getApplicationContext(), this);
            mQuestionBox.execute("hogskoleprovet.txt");



        }
    }







}


public void setNewQuestion()
{

    //Hämta en slumpmässig fråga från vår QuestionBox
    //och lagra den i mCurrentQuestion
    mCurrentQuestion = mQuestionBox.getRandomQuestion();


    //Se till så att textfält och knappar visar den aktuella
    //frågan

    TextView questionTextView = (TextView) findViewById(R.id.questionTextView);
    questionTextView.setText(mCurrentQuestion.getQuestion());


    Button buttonOne = (Button) findViewById(R.id.buttonOne);
    buttonOne.setText(mCurrentQuestion.getOptionOne());


    Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
    buttonTwo.setText(mCurrentQuestion.getOptionTwo());


    Button buttonThree = (Button) findViewById(R.id.buttonThree);
    buttonThree.setText(mCurrentQuestion.getOptionThree());

    Button buttonFour = (Button) findViewById(R.id.buttonFour);
    buttonFour.setText(mCurrentQuestion.getOptionFour());

    Button buttonNew = (Button) findViewById(R.id.buttonNew);

    buttonOne.setEnabled(true);
    buttonTwo.setEnabled(true);
    buttonThree.setEnabled(true);
    buttonFour.setEnabled(true);


    buttonNew.setVisibility(View.INVISIBLE);

    buttonOne.setText(mCurrentQuestion.getOptionOne());
    buttonTwo.setText(mCurrentQuestion.getOptionTwo());
    buttonThree.setText(mCurrentQuestion.getOptionThree());
    buttonFour.setText(mCurrentQuestion.getOptionFour());


}
public void quitTheGame(View v){

    Intent intent = new Intent (this, MainActivity.class);
    Button butttonQuit =  (Button) findViewById(R.id.buttonFive);
    startActivity(intent);

}




public void answerClick(View V)
{
    Button answerButton = (Button)V;
    Button buttonOne = (Button) findViewById(R.id.buttonOne);
    buttonOne.setText(mCurrentQuestion.getOptionOne());


    Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
    buttonTwo.setText(mCurrentQuestion.getOptionTwo());


    Button buttonThree = (Button) findViewById(R.id.buttonThree);
    buttonThree.setText(mCurrentQuestion.getOptionThree());

    Button buttonFour = (Button) findViewById(R.id.buttonFour);
    buttonFour.setText(mCurrentQuestion.getOptionFour());

    Button buttonNew = (Button) findViewById(R.id.buttonNew);



    buttonOne.setEnabled(false);
    buttonTwo.setEnabled(false);
    buttonThree.setEnabled(false);
    buttonFour.setEnabled(false);


    buttonNew.setVisibility(View.VISIBLE);



}


public void newClick(View v){

    if(mQuestionBox.getQuestionsLeft()>0){
        setNewQuestion();

    }


    else
    {
        Context context = getApplicationContext();
        String text = "Slut på frågor!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();

    }

}






@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

这里是给正确选项提供答案的类:

包 com.example.arnpet.ultimatehogskoleprovet;

public class Question {

private String question;//Lagrar frågan

private String optionOne; //Lagrar svarsalternativ

private String optionTwo;

private String optionThree;

private String optionFour;

private String correctAnswer; //Lagrar det korrekta svaret

//控制者

public Question (String question, String optionOne, String optionTwo,
                 String optionThree, String optionFour, String correctAnswer)
{
    this.question = question;
    this.optionOne = optionOne;
    this.optionTwo = optionTwo;
    this.optionThree = optionThree;
    this.optionFour = optionFour;





}

public String getQuestion() {
    return question;
}

public String getOptionOne() {
    return optionOne;
}

public String getOptionTwo() {
    return optionTwo;
}

public String getOptionThree() {
    return optionThree;
}

public String getOptionFour() {
    return optionFour;
}

}

【问题讨论】:

  • 您的代码墙对任何人都没有帮助 - 请搜索“如何提出一个好问题”并重试。

标签: java android inputstream bufferedreader


【解决方案1】:
while (reader.readLine() != null)

在这里,您正在读取文件的一行并将其丢弃。不是你想要的,除非你的文件结构很奇怪,经常带有可忽略的垃圾行。

通常的循环如下所示:

while ((line = reader.readLine()) != null)

然后在受控块中使用line

其次,这是您检查 null 的唯一地方,但您还有其他几个 readLine() 调用,其中任何一个都可以返回 null。因此,您稍后会在代码中冒一些 NPE 风险。

【讨论】:

  • 受控块是什么意思?我应该如何避免 NPES?
  • 我不应该启动 line 或将其创建为变量,因为我的 android studio 说它没有解析为符号?
  • “受控块”是while 控制的块。显然,您可以通过测试 null 来避免 NPE。显然,您需要在使用之前声明 line,就像任何其他变量一样。
  • 对不起,我真的不明白这个,我应该把例如 question = line;或者其他方式
  • 拜托,你能帮我做这部分吗,因为我不明白你所说的“” 其次,这是你检查 null 的唯一地方,但是你还有其他几个 readLine() 调用,任何其中一个可以返回 null。因此,您稍后会在代码中冒 NPE 的风险”?
猜你喜欢
  • 2010-12-25
  • 2018-08-17
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多