如何从不同的类调用intent

时间:2018-04-23 23:54:34

标签: android android-intent android-handler

我试图从处理程序中调出一个意图而我不知道该怎么做。我尝试了很多不同的方法,但似乎并没有起作用。我想在进度对话框达到最大值时启动PrimeNumbersActivity

public class MyHandler extends Handler {
    ProgressDialog progressDialog;
    Context context;

    public MyHandler(ProgressDialog progressDialog) {
        this.progressDialog = progressDialog;
    }

    public MyHandler(Context context){
        this.context = context;
    }

    @Override
    public void handleMessage(Message msg) {
        findPrimeNumber(Integer.parseInt(msg.obj.toString()));
    }

    public void findPrimeNumber(int number){

        ArrayList<Integer> primeNumbers = new ArrayList<>();
        boolean isPrimeNumber;
        PrimeNumbers primeNumbers1 = new PrimeNumbers();




        for(int i = 2; i <= number; i++){
            isPrimeNumber = true;
            for(int j = 1; j <= i; j++){
                try {
                    sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(j != 1 && j != i){
                    if(i%j == 0){
                        isPrimeNumber = false;
                        break;
                    }
                }
            }
            if(isPrimeNumber){
                primeNumbers.add(i);
                primeNumbers1.primeNumbers.add(i);
            }
            progressDialog.setProgress(i*100/number);
            if(progressDialog.getProgress() == progressDialog.getMax()){
                progressDialog.dismiss();
                Intent intent = new Intent(context.getApplicationContext(),PrimeNumbersActivity.class);
                context.startActivity(intent);
            }
        }

        for (int i :
                primeNumbers) {
            Log.d(TAG, i + "");
        }
    }
}

PrimeNumbersActivity

public class PrimeNumbersActivity extends AppCompatActivity {

    private PrimeNumbers primeNumbers = new PrimeNumbers();
    private ListView listView;

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

        listView = findViewById(R.id.listView);

        if(primeNumbers.primeNumbers.isEmpty()){
            Toast.makeText(getApplicationContext(),"Pas de nombres premiers",Toast.LENGTH_SHORT).show();
        }else{
            ArrayAdapter<Integer> arrayAdapter = new ArrayAdapter<Integer>(getApplicationContext(),android.R.layout.simple_list_item_1,primeNumbers.primeNumbers);
            listView.setAdapter(arrayAdapter);
        }
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

    public static final int number = 20;
    public Button button;
    public EditText editText;
    public ProgressDialog progressDialog;
    public AlertDialog.Builder alertDialog;


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

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMax(100);
        progressDialog.setMessage("Please wait...");
        progressDialog.setTitle("Finding prime numbers");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        final MyThread thread = new MyThread(progressDialog);
        thread.setName("MyThread");
        thread.start();

        button = (Button) findViewById(R.id.afficherNombrePremier);
        editText = (EditText) findViewById(R.id.editText);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editText.getText().toString().isEmpty()){
                    alertDialog = new AlertDialog.Builder(MainActivity.this);
                    alertDialog.setTitle("Warning");
                    alertDialog.setMessage("Veuillez saisir un nombre entier dans la zone de texte");
                    alertDialog.show();
                }
                else{
                    progressDialog.show();
                    Message message = Message.obtain();
                    message.obj = editText.getText().toString();
                    thread.mHandler.sendMessage(message);
                }

            }
        });
    }
}

错误:

04-24 00:45:15.457 4625-4712/com.example.mohammed.tdservicesex1 E/AndroidRuntime: FATAL EXCEPTION: MyThread
                                                                              Process: com.example.mohammed.tdservicesex1, PID: 4625
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                                  at com.example.mohammed.tdservicesex1.MyHandler.findPrimeNumber(MyHandler.java:65)
                                                                                  at com.example.mohammed.tdservicesex1.MyHandler.handleMessage(MyHandler.java:31)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                  at android.os.Looper.loop(Looper.java:154)
                                                                                  at com.example.mohammed.tdservicesex1.MyThread.run(MyThread.java:22)

主题:

public class MyThread extends Thread {
    private static final String TAG = MyThread.class.getSimpleName();
    public MyHandler mHandler;
    ProgressDialog progressDialog;

    public MyThread(ProgressDialog progressDialog) {
        this.progressDialog = progressDialog;
    }

    @Override
    public void run() {
        Looper.prepare();
        mHandler = new MyHandler(progressDialog);
        Looper.loop();
    }
}

3 个答案:

答案 0 :(得分:0)

我相信您无法使用应用程序上下文(以直接的方式)启动活动。你要么

  1. 使用活动上下文
  2. 使用应用程序上下文,但添加此标记FLAG_ACTIVITY_NEW_TASK
  3. 警告FLAG_ACTIVITYNEW_TASK将在历史堆栈中启动新任务

    尝试这样的事情:

    Intent intent = new Intent(context.getApplicationContext(),PrimeNumbersActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
    

答案 1 :(得分:0)

  1. 确保您在Android Manifest中声明了PrimeNumbersActivity
  2. 这应该有效:

    Intent intent = new Intent(context,PrimeNumbersActivity.class);
    context.startActivity(intent);
    
  3. 如果#2不起作用。这意味着这种情况总是错误的:

    if(progressDialog.getProgress() == progressDialog.getMax())
    

答案 2 :(得分:0)

发生错误是因为您没有在MyHandler类中为您的构造函数设置任何上下文。您的构造函数如下所示:

public class MyHandler extends Handler {
  ...

  public MyHandler(ProgressDialog progressDialog) {
    this.progressDialog = progressDialog;
  }

  public MyHandler(Context context){
    this.context = context;
  }

  ...
}

你可以看到你有2个不同的构造函数。在您的代码中,您只使用第一个构造函数,您从不使用第二个构造函数分配上下文。当您为类使用多个构造函数时,这是一个常见错误。

要解决此问题,您需要更改构造函数,以便它需要两个参数:ProgressDialog和Context。将构造函数更改为以下内容:

public class MyHandler extends Handler {
  ...

  public MyHandler(ProgressDialog progressDialog, Context context) {
    this.progressDialog = progressDialog;
    this.context = context;
  }

  ...
}