无法在改造成功回调函数内调用intent

时间:2015-11-16 15:26:39

标签: android android-intent android-studio retrofit

我是Android和改造的新手。当我点击登录时,如果回调返回"成功登录"然后我应该被重定向到主页,但似乎我不允许在回调函数中调用intent。

public void loginUser() {
    //Here we will handle the http request to insert user to mysql db
    //Creating a RestAdapter
    RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_URL) //Setting the Root URL
            .build(); //Finally building the adapter

    //Creating object for our interface
    LoginAPI api = adapter.create(LoginAPI.class);

    api.loginUser(

            //Passing the values by getting it from editTexts
            editTextUsername.getText().toString(),
            editTextPassword.getText().toString(),

            //Creating an anonymous callback
            new Callback<Response>() {
                @Override
                public void success(Response result, Response response) {
                    //On success we will read the server's output using bufferedreader
                    //Creating a bufferedreader object
                    BufferedReader reader = null;

                    //An string to store output from the server
                    String output = "";

                    try {
                        //Initializing buffered reader
                        reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

                        //Reading the output in the string
                        output = reader.readLine();

                        if(output == "Successful login") {
                            Intent i = new Intent(this, Home.class);
                            startActivity(i);
                        }
                        //Log.d(TAG, output);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //Displaying the output as a toast
                    Toast.makeText(Login.this, output, Toast.LENGTH_LONG).show();

                    /*SharedPreferences mSettings = getSharedPreferences("data", 0);
                    SharedPreferences.Editor editor = mSettings.edit();
                    editor.putString("callback", output);
                    editor.commit();*/

                }

                @Override
                public void failure(RetrofitError error) {
                    //If any error occured displaying the error as toast
                    Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
                }
            }

    );
}

1 个答案:

答案 0 :(得分:1)

你使用了错误的this-pointer。

Intent i = new Intent(this, Home.class);

您应该使用活动的this-pointer,而不是您的匿名内部类。例如。如果您的活动名为Login,您应该以这种方式建立您的意图:

Intent i = new Intent(Login.this, Home.class);