2015-04-30 2 views
0

У меня возникли проблемы с созданием метода, который работает в фоновом режиме. Я использую Android studio java и хочу создать метод, который загружает текстовый файл в array-list. Я попытался сделать это в открытом методе в отдельном классе из класса активности. Когда я запускаю приложение, у меня возникают проблемы с указанием проблем с основным потоком, поэтому я хочу сделать asynctask. Я смотрел по всему Интернету, но я не могу найти ничего подходящего. Пожалуйста, спросите, если что-то неясно, так как я новичок. Любая помощь приветствуется!Проблемы с созданием AsyncTask. текстовый файл в arraylist

Это из класса, который будет посылать переменную public void CreateQuestion(), которая находится ниже первого кода:

protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_game_action); 

    Intent callingIntent = getIntent(); 
    int index = callingIntent.getIntExtra("INDEX",0);  


    if(index==0){ 
     mQuestionBox = new QuestionBox(); 
     try { 
      mQuestionBox.createQuestions("hogskoleprovet.txt"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 
    else if(index==1){ 
     mQuestionBox = new QuestionBox(); 
     try { 
      mQuestionBox.createQuestions("hogskoleprovet.txt"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 


    } 
    else if(index==2){ 
     mQuestionBox = new QuestionBox(); 
     try { 
      mQuestionBox.createQuestions("hogskoleprovet.txt"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 

Я хочу, чтобы этот код как AsyncTask, но я не знаю, как это сделать ,

public void createQuestions(String hogskoleprovet) throws IOException { 


    InputStream iS = sContext.getAssets().open(hogskoleprovet); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(iS)); 

    mQuestions = new ArrayList<Question>(); 


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



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

    reader.close(); 


} 

ответ

0

Попробуйте изменить свой метод createQuestions так:

public void createQuestions(final String hogskoleprovet) throws IOException { 

new AsyncTask<Integer, Integer, Boolean>() 
    { 

     @Override 
     protected void onPreExecute() 

     { 

     } 

     @Override 
     protected Boolean doInBackground(Integer… params) 
     { 

      InputStream iS = sContext.getAssets().open(hogskoleprovet); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(iS)); 

     mQuestions = new ArrayList<Question>(); 


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



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

    reader.close(); 


      return true; 
     } 

     @Override 
     protected void onPostExecute(Boolean result) 
     { 




     } 
    }.execute(); 
} 
0

AsyncTask класс для чтения данных из файла

public class FileReader_async extends AsyncTask{ 
private Context context; 
private Callback callback; 
private List<Question> mQuestions; 
    public FileReader_async(Context context,Callback callback) 
    { 
     this.callback=callback; 
    } 
    @Override 
    protected Object doInBackground(Object... params) { 
     InputStream iS = null; 
     try { 
      iS = context.getAssets().open("filename"); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     BufferedReader reader = new BufferedReader(new InputStreamReader(iS)); 

     mQuestions = new ArrayList<Question>(); 


     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(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return 0; 
    } 
    @Override 
    protected void onPostExecute(Object result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
     callback.notify_result(mQuestions); 
    } 



} 

обратного вызова интерфейса для уведомления, когда asnyctask закончена

public interface Callback { 

    public void notify_result(List<Question> question_list); 


} 

, вызывающее асинтез для считывания данных из файла.

public class MainActivity extends ActionBarActivity implements Callback{ 
private FileReader_async fileReader_async; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     //invoke the asynctask when you want to read the question.. to invoke asynctask code 

     fileReader_async=new FileReader_async(getApplicationContext(), this); 
     fileReader_async.execute(); 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.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(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 


    @Override 
    public void notify_result(List<Question> question_list) { 
     //you can use the question_list from here 

    } 
} 
Смежные вопросы