繁体   English   中英

无法从 Android 中的 onPostExecute 方法启动新活动

[英]Can't able to start new activity from onPostExecute method in Android

这是我的 Java 代码。 我的问题是当我向OnPostExecute添加一些代码以打开另一个活动时。 我是 Android Studio 的新手,所以我第一次遇到这个问题。

package com.example.gonalo.meu;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import static android.support.v4.app.ActivityCompat.startActivity;
import static android.support.v4.content.ContextCompat.startActivities;

 /**
* Created by Gonçalo on 23/03/2016.
*/

public class BackGroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackGroundWorker (Context ctx) {
    context = ctx;
}

@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "http://192.168.1.79/login.php";
    String register_url = "http://192.168.1.79/register.php";
    //String verifyuserpass_url = "http://192.168.0.102/verifyuserpass.php";
    //String verifypass_url = "http://192.168.0.102/verifyuserpass.php";
    if(type.equals("login")) {
        try {
            String user_name = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            String user = URLEncoder.encode(user_name, "UTF-8");//guarda o nome de utilizador introduzido
            String pass = URLEncoder.encode(password, "UTF-8");//guarda a pass introduzido
            System.err.println("------------------------------------------");
             /*/  if(user.equals("Nome de Utilizador")){
                   if(pass.equals("Password")) {
                       System.err.println("Entrou no if");
                       startActivity(new Intent(this, Pagina1.class));}
 /*/
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null) {
                result +=line;

            }

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else if(type.equals("register")) {
        try {
            String name = params[1];
            String surname = params[2];
            String age = params[3];
            String username = params[4];
            String password = params[5];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(name, "UTF-8")+"&"
                    + URLEncoder.encode("surname", "UTF-8")+"="+URLEncoder.encode(surname, "UTF-8")+"&"
                    + URLEncoder.encode("age", "UTF-8")+"="+URLEncoder.encode(age, "UTF-8")+"&"
                    + URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"
                    +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");

            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null) {
                result += line;

                }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return null;
}



@Override
 protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");

}

@Override
protected void onPostExecute(String result) {
    alertDialog.setMessage(result);
    alertDialog.show();
    if (result.equals("Login Success"));
    Intent myIntent = new Intent(this, Pagina1.class); // Im facing problem here
    startActivity(myIntent); // Im facing problem here

}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}

开始活动错误

无法解析构造函数

我正在尝试添加一些简单的代码,但我的 Android 无法识别它。

尝试重新启动您的android studio.And还检查您是否已添加清单。

兄弟,你的问题是,你传递this在意图, this是目前AsyncTask 没有从任何具有衍生Context (活动上下文)。 只需用以下内容替换该行:

startActivity(new Intent(context, Pagina1.class));}
//context being the field you initialize in the constructor

这样就可以了。 我知道您可能在某处发现这是开始活动的正确方法:

    startActivity(new Intent(this, YourClass.class));

当它来自另一个Activity时,它是哪个,因为Intent()构造函数的第一个参数是Context ,所以哪个活动确实具有。 FragmentsAsyncTasks等不在源自Context ,所以你不能只是调用this当你试图startActivity从他们。

尝试这个

意图myIntent =新意图(this,Pagina1.class);

在上面的声明中, 不是当前类对象,活动或应用程序上下文。 您必须提供应用程序的上下文。 因为当前类不是活动。 以上声明应该变成这样

试试这个陈述

Intent myIntent = new Intent(getApplicationContext(), Pagina1.class);

在您的onPostExecute()方法中替换以上语句。

在onPostExecute方法中,执行以下操作:

Intent intent = new Intent(context,SecondActivity.class);
context.startActivity(intent);

它肯定会工作!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM