简体   繁体   中英

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

Here is my Java code. My problem is when I add some code to OnPostExecute to open another activity. I'm new to Android Studio so I'm facing this problem for first time.

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

Start Activity error

Cannot resolve constructor

I'm trying to add some simple code and my Android does not recognize it.

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

Bro, your problem is that you're passing this in the Intent, and this is currently the AsyncTask which is NOT derived from anything that has Context (Activities have Context). Just replace that line with this:

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

And this'll work. I know you have probably found somewhere that this is the correct way to start the activity:

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

Which it is, when it is from another Activity , because the first parameter of the Intent() constructor is Context , which activities do have. Fragments , AsyncTasks , etc. are not derived from Context and therefore you cannot just call this when you're trying to startActivity from them.

Try this

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

In above statement this point to the current class object not, activity or context of application. You must give the context of application. Because the current class is not an activity. Above statement should become like this

Try this statement

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

Replace above statement in your onPostExecute() method.

In onPostExecute method do the following:-

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

It will surely work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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