找到你要的答案

Q:Problems with running AsyncTask in android java

Q:运行于Android java AsyncTask的问题

Sorry, this is a duplicate post because I uploaded a version of this earlier but that one does not have any answers which this one has.

I have problems with asyncTask in android programming. I am trying to load a text file in a background thread which is asyncTask. First of all, in my application I send a variable from a class which is controlled by an array-list which is later controlled by a button in a xml-file to the asyncTask class because it chooses an index throug a spinner. When it comes to background thread class it fails since I do not know that part very well. If something was unclear please ask since I am beginner in android programming. Any help is appreciated!

Here is the code for sending a variable:

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){

        fileReader_async=new FileReader_async(getApplicationContext(), this);
        fileReader_async.execute("hogskoleprovet.txt");

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

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


       }
    }

    setNewQuestion();



}

Here is the async-Class:

package com.example.arnpet.ultimatehogskoleprovet;

import android.content.Context;
import android.os.AsyncTask;
import com.example.arnpet.ultimatehogskoleprovet.Question;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.security.auth.callback.Callback;

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("hogskoleprovet");
    } 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);
}
public interface Callback {

    public void notify_result(List<Question> question_list);


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

}

}

A person asked for another class that could be the problem to this:

public class pagebeforeAction extends Activity {

private Spinner spinnerOne;
private Button btnSubmit;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pagebefore_action);

    spinnerOne = (Spinner) findViewById(R.id.spinnerOne);
    List<String> list = new ArrayList<String>();
    list.add("Nivå 1");
    list.add("Nivå 2");
    list.add("Nivå 3");
    list.add("Nivå 4");
    list.add("Nivå 5");

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
            (this, android.R.layout.simple_spinner_item,list);

    dataAdapter.setDropDownViewResource
            (android.R.layout.simple_spinner_dropdown_item);

    spinnerOne.setAdapter(dataAdapter);

    // Spinner item selection Listener
    addListenerOnSpinnerItemSelection();




}


public void returnOne(View v){
    Intent intent = new Intent(this, MainActivity.class);
    Button button = (Button) findViewById(R.id.buttonTwo);
    startActivity(intent);
}





// Add spinner data

public void addListenerOnSpinnerItemSelection(){

    spinnerOne.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}

//get the selected dropdown list value
public void submit(View v)
{
    Button btnSubmit = (Button) findViewById(R.id.submit);
    Intent intent = new Intent (this, gameAction.class);
    Toast.makeText(pagebeforeAction.this,
            "On Button Click : " +
                    "\n" + String.valueOf(spinnerOne.getSelectedItem()) ,
            Toast.LENGTH_LONG).show();

    int index = Integer.parseInt(btnSubmit.getTag().toString());
    intent.putExtra("INDEX",index);
    startActivity(intent);


}








05-02 09:04:28.823  29549-29549/com.example.arnpet.ultimatehogskoleprovet E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.arnpet.ultimatehogskoleprovet, PID: 29549
java.lang.IllegalStateException: Could not execute method of the activity
        at android.view.View$1.onClick(View.java:3969)
        at android.view.View.performClick(View.java:4637)
        at android.view.View$PerformClick.run(View.java:19422)
            at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5479)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at 

对不起,这是一个重复的帖子,因为我上传了一个版本,这是较早的,但一个没有任何答案,这一个。

我已经在Android编程AsyncTask的问题。我想在一个后台线程是一个文本文件加载AsyncTask。首先,在我的申请我将从由数组列表的XML文件按钮AsyncTask后控制因为它选择一个指标通过微调类变量。当涉及到后台线程类,它失败了,因为我不知道这部分很好。如果有什么不清楚,请问,因为我是初学者在Android编程。任何帮助是赞赏!

这里是发送变量的代码:

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){

        fileReader_async=new FileReader_async(getApplicationContext(), this);
        fileReader_async.execute("hogskoleprovet.txt");

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

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


       }
    }

    setNewQuestion();



}

这里是异步类:

package com.example.arnpet.ultimatehogskoleprovet;

import android.content.Context;
import android.os.AsyncTask;
import com.example.arnpet.ultimatehogskoleprovet.Question;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.security.auth.callback.Callback;

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("hogskoleprovet");
    } 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);
}
public interface Callback {

    public void notify_result(List<Question> question_list);


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

}

}

一个人要求另一个类,可能是这个问题:

public class pagebeforeAction extends Activity {

private Spinner spinnerOne;
private Button btnSubmit;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pagebefore_action);

    spinnerOne = (Spinner) findViewById(R.id.spinnerOne);
    List<String> list = new ArrayList<String>();
    list.add("Nivå 1");
    list.add("Nivå 2");
    list.add("Nivå 3");
    list.add("Nivå 4");
    list.add("Nivå 5");

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
            (this, android.R.layout.simple_spinner_item,list);

    dataAdapter.setDropDownViewResource
            (android.R.layout.simple_spinner_dropdown_item);

    spinnerOne.setAdapter(dataAdapter);

    // Spinner item selection Listener
    addListenerOnSpinnerItemSelection();




}


public void returnOne(View v){
    Intent intent = new Intent(this, MainActivity.class);
    Button button = (Button) findViewById(R.id.buttonTwo);
    startActivity(intent);
}





// Add spinner data

public void addListenerOnSpinnerItemSelection(){

    spinnerOne.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}

//get the selected dropdown list value
public void submit(View v)
{
    Button btnSubmit = (Button) findViewById(R.id.submit);
    Intent intent = new Intent (this, gameAction.class);
    Toast.makeText(pagebeforeAction.this,
            "On Button Click : " +
                    "\n" + String.valueOf(spinnerOne.getSelectedItem()) ,
            Toast.LENGTH_LONG).show();

    int index = Integer.parseInt(btnSubmit.getTag().toString());
    intent.putExtra("INDEX",index);
    startActivity(intent);


}








05-02 09:04:28.823  29549-29549/com.example.arnpet.ultimatehogskoleprovet E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.arnpet.ultimatehogskoleprovet, PID: 29549
java.lang.IllegalStateException: Could not execute method of the activity
        at android.view.View$1.onClick(View.java:3969)
        at android.view.View.performClick(View.java:4637)
        at android.view.View$PerformClick.run(View.java:19422)
            at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5479)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at 
answer1: 回答1:

I solved it by creating a public method in your activity so instead of callback.notify_result(mQuestions) yo will do:

activity.notify_result(mQuestions); in your onPostExecute.

You already have the activity in your Task as context. Just cast it to his name like this:

((ActivityName) context).notify_result(mQuestions);

我的解决方法是通过创建在你的活动的一个公共方法,而不是回调。notify_result(口罩)你会做:

活动。notify_result(口罩);在你的onpostexecute。

您已经将任务中的活动作为上下文。就这样把它丢给他的名字:

((ActivityName) context).notify_result(mQuestions);
java  android  multithreading  android-asynctask