java.lang.ClassCastException:无法将活动强制转换为MainActivity

时间:2018-11-09 16:20:55

标签: java php android android-volley

我正在尝试使用Volley,PHP,MySQL进行登录会话,但我的登录布局无法加载。我不知道发生了什么,在我的logcat中它说“ java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.merylle.themoneyger / com.example.merylle.themoneyger.activity.LoginActivity}:java.lang .ClassCastException:com.example.merylle.themoneyger.activity.LoginActivity无法转换为com.example.merylle.themoneyger.activity.MainActivity“

这是由于“原因:java.lang.ClassCastException:com.example.merylle.themoneyger.activity.LoginActivity无法转换为com.example.merylle.themoneyger.activity.MainActivity”

有人可以帮助我识别我的错误吗?这是我的代码

SessionManager.java

public class SessionManager {

    SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;
    public Context context;
    int PRIVATE_MODE=0;

    private static final String PREF_NAME = "MONEYGER";
    private static final String LOGIN = "IS_LOGIN";
    public static final String FIRSTNAME = "NAME";
    public static final String EMAIL = "EMAIL";
    public static final String USERID = "USERID";

    public SessionManager(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = sharedPreferences.edit();
    }

    public void createSession(String firstname, String email) {
        editor.putBoolean(LOGIN, true);
        editor.putString(FIRSTNAME, firstname);
        editor.putString(EMAIL, email);

/*editor.putString(USERID, userid);*/

        editor.apply();
    }

    public boolean isLoggin(){
        return sharedPreferences.getBoolean(LOGIN, false);
    }

    public void checkLogin() {
        if (!this.isLoggin()) {
            Intent i = new Intent(context, LoginActivity.class);
            context.startActivity(i);
            ((MainActivity)context).finish();
        }
    }

    public HashMap<String, String> getUserDetail() {
        HashMap<String, String> user = new HashMap<>();
        user.put(FIRSTNAME, sharedPreferences.getString(FIRSTNAME, null));
        user.put(EMAIL, sharedPreferences.getString(EMAIL, null));

/*user.put(USERID, sharedPreferences.getString(USERID, null));*/

        return user;
    }

    public void logout() {
        editor.clear();
        editor.commit();
        Intent i = new Intent(context, LoginActivity.class);
        context.startActivity(i);
        ((MainActivity)context).finish();
    }
}

LoginActivity.java

public class LoginActivity extends Activity {
    TextView title;
    Typeface marcellus;
    private EditText emailuser, passworduser;
    TextView forgot;
    private Button login, register;
    private ProgressBar progressBar;
    private static String HttpURL = "http://10.0.2.2:63343/TheMoneyger/api/user-login.php?";
    SessionManager sessionManager;


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

        sessionManager = new SessionManager(this);
        sessionManager.checkLogin();

        title = (TextView) findViewById(R.id.txtTitle);
        marcellus = Typeface.createFromAsset(getAssets(), "marcellus.ttf");
        title.setTypeface(marcellus);

        emailuser = (EditText) findViewById(R.id.txtEmail);
        passworduser = (EditText) findViewById(R.id.txtPassword);
        login = (Button) findViewById(R.id.btnLogin);
        forgot = (TextView) findViewById(R.id.txtForgotPW);
        register = (Button) findViewById(R.id.btnRegister);
        progressBar = (ProgressBar)findViewById(R.id.progressBar3);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String mEmail = emailuser.getText().toString().trim();
                String mPass = passworduser.getText().toString().trim();

                if(!mEmail.isEmpty() || !mPass.isEmpty()) {
                    Login(mEmail, mPass);
                }
                else {
                    emailuser.setError("Please insert email");
                    passworduser.setError("Please insert password");
                }
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent registration = new Intent(LoginActivity.this, RegistrationActivity.class);
                startActivity(registration);
            }
        });

        forgot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent forgot = new Intent(LoginActivity.this, ForgotPassword.class);
                startActivity(forgot);
            }
        });
    }

    private void Login(final String emailuser, final String passworduser) {
        progressBar.setVisibility(View.VISIBLE);
        login.setVisibility(View.GONE);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpURL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String success = jsonObject.getString("success");
                            JSONArray jsonArray = jsonObject.getJSONArray("login");

                            if (success.equals("1")) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject object = jsonArray.getJSONObject(i);

                                    String firstname = object.getString("firstname").trim();
                                    String email = object.getString("email").trim();
                                    String id = object.getString("userid").trim();

                                    sessionManager.createSession(firstname, email);

                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    intent.putExtra("firstname", firstname);
                                    intent.putExtra("email", email);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(LoginActivity.this, "Something went wrong.. " + e.toString(), Toast.LENGTH_SHORT).show();
                            login.setVisibility(View.VISIBLE);
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this, "Something went wrong.. " + error.toString(), Toast.LENGTH_SHORT).show();
                        login.setVisibility(View.VISIBLE);
                        progressBar.setVisibility(View.GONE);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("email", emailuser);
                params.put("password", passworduser);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
}

Home2.java

public class Home2 extends Fragment {
    private TextView profileName, profileEmail;
    CardView cv1, cv2, cv3, cv4, cv5, cv6;
    SessionManager sessionManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        sessionManager = new SessionManager(getActivity().getApplicationContext());
        sessionManager.checkLogin();

        cv1 = (CardView)view.findViewById(R.id.cv1); //settings
        cv2 = (CardView)view.findViewById(R.id.cv2); //profile
        cv3 = (CardView)view.findViewById(R.id.cv3); //expenses summary
        cv4 = (CardView)view.findViewById(R.id.cv4); //budget summary
        cv5 = (CardView)view.findViewById(R.id.cv5); //report
        cv6 = (CardView)view.findViewById(R.id.cv6); //logout

        profileName = (TextView)view.findViewById(R.id.txtProfileName); //display profilename
        profileEmail = (TextView)view.findViewById(R.id.txtProfileEmail); //display profileemail

        HashMap<String, String> user = sessionManager.getUserDetail();
        String mName = user.get(sessionManager.FIRSTNAME);
        String mEmail = user.get(sessionManager.EMAIL);

        profileName.setText(mName);
        profileEmail.setText(mEmail);
return view;
}
}

user-login.php

<?php    
if ($_SERVER['REQUEST_METHOD']=='POST') {
        $email = $_POST['email'];
        $password = $_POST['password'];

        require_once 'config.php';

        $sql = "SELECT * FROM users WHERE email='$username'";

        $response = mysqli_query($db, $sql);

        $result = array();
        $result['login'] = array();

        if ( mysqli_num_rows($response) === 1 ) {
            $row = mysqli_fetch_assoc($response);

            if ( password_verify($password, $row['password']) ) {
                $index['firstname'] = $row['firstname'];
                $index['email'] = $row['email'];

                array_push($result['login'], $index);

                $result['success'] = "1";
                $result['message'] = "success";
                echo json_encode($result);

                mysqli_close($db);
            } else {
                $result['success'] = "0";
                $result['message'] = "error";
                echo json_encode($result);

                mysqli_close($db);
            }
        }
    }
    ?>

1 个答案:

答案 0 :(得分:0)

您已使用sessionManager的上下文初始化LoginActivity

sessionManager = new SessionManager(this);

,然后在SessionManager类中,您可以使用以下代码:

((MainActivity)context).finish();

这将引发错误。
您无法将LoginActivity的上下文转换为MainActivity
更改为此:

((LoginActivity)context).finish();

毕竟是LoginActivity,您想结束吗?