简体   繁体   中英

Cant get from Activity to Activity

This is my first activity

public class  MainActivity extends SampleActivityBase {

private boolean mLogShown;
public static final String TAG = "MainActivity";
private SharedPreferences pref;

EditText cardnumber;
TextView foodorders;
Button buttonorder, addsub;
private static final int REQUEST_CODE = 10;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    pref = getPreferences(0);
    setContentView(R.layout.activity_main);
    cardnumber = (EditText) findViewById(R.id.card_account_field);
    cardnumber.setText(AccountStorage.GetAccount(getBaseContext()));
    cardnumber.addTextChangedListener(new AccountUpdater());
    foodorders = (TextView) findViewById(R.id.foodordershow);
    buttonorder = (Button) findViewById(R.id.buttonorder);
    addsub = (Button) findViewById(R.id.buttonregister);

    addsub.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), MainActivity1.class);
            startActivity(intent);
        }
    });

    buttonorder.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String strcardnumber = cardnumber.getText().toString();
            Intent intent = new Intent(getApplicationContext(), activityresult1.class);
            intent.putExtra("Card Number", strcardnumber);
            startActivityForResult(intent, REQUEST_CODE);
        }
    });


}


private class AccountUpdater implements TextWatcher {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Not implemented.
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // Not implemented.
    }

    @Override
    public void afterTextChanged(Editable s) {
        String account = s.toString();
        AccountStorage.SetAccount(getBaseContext(), account);
    }
}

This is my second activity

public class MainActivity1 extends AppCompatActivity {

private SharedPreferences pref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);
    pref = getPreferences(0);
    initFragment();
}

private void initFragment(){
    Fragment fragment;
    if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){
        fragment = new ProfileFragment();
    }else {
        fragment = new LoginFragment();
    }
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame,fragment);
    ft.commit();
}

Profile fragment

public class ProfileFragment extends Fragment implements View.OnClickListener {

private TextView tv_name,tv_email,tv_message;
private SharedPreferences pref;
private AppCompatButton btn_change_password,btn_logout;
private EditText et_old_password,et_new_password;
private AlertDialog dialog;
private ProgressBar progress;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_profile,container);
    initViews(view);
    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    pref = getActivity().getPreferences(0);
    tv_name.setText("Welcome : "+pref.getString(Constants.NAME,""));
    tv_email.setText(pref.getString(Constants.EMAIL,""));

}

private void initViews(View view){

    tv_name = (TextView)view.findViewById(R.id.tv_name);
    tv_email = (TextView)view.findViewById(R.id.tv_email);
    btn_change_password = (AppCompatButton)view.findViewById(R.id.btn_chg_password);
    btn_logout = (AppCompatButton)view.findViewById(R.id.btn_logout);
    btn_change_password.setOnClickListener(this);
    btn_logout.setOnClickListener(this);

}

private void showDialog(){

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.dialog_change_password, null);
    et_old_password = (EditText)view.findViewById(R.id.et_old_password);
    et_new_password = (EditText)view.findViewById(R.id.et_new_password);
    tv_message = (TextView)view.findViewById(R.id.tv_message);
    progress = (ProgressBar)view.findViewById(R.id.progress);
    builder.setView(view);
    builder.setTitle("Change Password");
    builder.setPositiveButton("Change Password", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    dialog = builder.create();
    dialog.show();
    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String old_password = et_old_password.getText().toString();
                String new_password = et_new_password.getText().toString();
                if(!old_password.isEmpty() && !new_password.isEmpty()){

                    progress.setVisibility(View.VISIBLE);
                    changePasswordProcess(pref.getString(Constants.EMAIL,""),old_password,new_password);

                }else {

                    tv_message.setVisibility(View.VISIBLE);
                    tv_message.setText("Fields are empty");
                }
            }
        });
}

@Override
public void onClick(View v) {
    switch (v.getId()){

        case R.id.btn_chg_password:
            showDialog();
            break;
        case R.id.btn_logout:
            logout();
            break;
    }
}

private void logout() {
    SharedPreferences.Editor editor = pref.edit();
    editor.putBoolean(Constants.IS_LOGGED_IN,false);
    editor.putString(Constants.EMAIL,"");
    editor.putString(Constants.NAME,"");
    editor.putString(Constants.UNIQUE_ID,"");
    editor.apply();
    goToLogin();
}

private void goToLogin(){

    Fragment login = new LoginFragment();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame,login);
    ft.commit();
}

private void changePasswordProcess(String email,String old_password,String new_password){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    com.example.android.cardemulation.RequestInterface requestInterface = retrofit.create(com.example.android.cardemulation.RequestInterface.class);

    User user = new User();
    user.setEmail(email);
    user.setOld_password(old_password);
    user.setNew_password(new_password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.CHANGE_PASSWORD_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();
            if(resp.getResult().equals(Constants.SUCCESS)){
                progress.setVisibility(View.GONE);
                tv_message.setVisibility(View.GONE);
                dialog.dismiss();
                Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();

            }else {
                progress.setVisibility(View.GONE);
                tv_message.setVisibility(View.VISIBLE);
                tv_message.setText(resp.getMessage());

            }
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

            Log.d(Constants.TAG,"failed");
            progress.setVisibility(View.GONE);
            tv_message.setVisibility(View.VISIBLE);
            tv_message.setText(t.getLocalizedMessage());


        }
    });
}

LOGIN fragment

public class LoginFragment extends Fragment implements View.OnClickListener{

private AppCompatButton btn_login;
private EditText et_email,et_password;
private TextView tv_register;
private ProgressBar progress;
private SharedPreferences pref;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_login,container,false);
    initViews(view);
    return view;
}

private void initViews(View view){

    pref = getActivity().getPreferences(0);

    btn_login = (AppCompatButton)view.findViewById(R.id.btn_login);
    tv_register = (TextView)view.findViewById(R.id.tv_register);
    et_email = (EditText)view.findViewById(R.id.et_email);
    et_password = (EditText)view.findViewById(R.id.et_password);

    progress = (ProgressBar)view.findViewById(R.id.progress);

    btn_login.setOnClickListener(this);
    tv_register.setOnClickListener(this);
}

@Override
public void onClick(View v) {

    switch (v.getId()){

        case R.id.tv_register:
            goToRegister();
            break;

        case R.id.btn_login:
            String email = et_email.getText().toString();
            String password = et_password.getText().toString();

            if(!email.isEmpty() && !password.isEmpty()) {

                progress.setVisibility(View.VISIBLE);
                loginProcess(email,password);

            } else {

                Snackbar.make(getView(), "Fields are empty !", Snackbar.LENGTH_LONG).show();
            }
            break;

    }
}
private void loginProcess(String email,String password){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    com.example.android.cardemulation.RequestInterface requestInterface = retrofit.create(com.example.android.cardemulation.RequestInterface.class);

    User user = new User();
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.LOGIN_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();
            Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();

            if(resp.getResult().equals(Constants.SUCCESS)){
                SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean(Constants.IS_LOGGED_IN,true);
                editor.putString(Constants.EMAIL,resp.getUser().getEmail());
                editor.putString(Constants.NAME,resp.getUser().getName());
                editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
                editor.apply();
                goToProfile();

            }
            progress.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

            progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG,"failed");
            Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();

        }
    });
}

private void goToRegister(){

    Fragment register = new com.example.android.cardemulation.RegisterFragment();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame,register);
    ft.commit();
}

private void goToProfile(){

    Fragment profile = new com.example.android.cardemulation.ProfileFragment();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame,profile);
    ft.commit();
}

When i press the button register addsub it crashed and this message pops out :

04-22 14:35:04.384 10045-10045/com.example.android E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.android, PID: 10045
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android/com.example.android.cardemulation.MainActivity1}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2484) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2544) at android.app.ActivityThread.access$900(ActivityThread.java:150) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:168) at android.app.ActivityThread.main(ActivityThread.java:5845) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687) Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at android.view.ViewGroup.addViewInner(ViewGroup.java:4315) at android.view.ViewGroup.addView(ViewGroup.java:4151) at android.view.ViewGroup.addView(ViewGroup.java:4092) at android.view.ViewGroup.addView(ViewGroup.java:4065) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:985) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148) at android.app.BackStackRecord.run(BackStackRecord.java:793) at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535) at android.app.FragmentController.execPendingActions(FragmentController.java:325) at android.app.Activity.performStart(Activity.java:6263) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2447) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2544) at android.app.ActivityThread.access$900(ActivityThread.java:150) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394) at android.os.Handler.dispatchMessage(Handler.java: 102) at android.os.Looper.loop(Looper.java:168) at android.app.ActivityThread.main(ActivityThread.java:5845) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)

Don't use getApplicationContext() in your Intent . Use "local" Context

Intent intent = new Intent(MainActivity.this, MainActivity1.class);

//or
Intent intent = new Intent(v.getContext(), MainActivity1.class);

//or, define a global variable in your Activity, outside the onClick:
Context context;
//in onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pref = getPreferences(0);
    setContentView(R.layout.activity_main);
    context = this;
    //your other code...

// in onClick:
addsub.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(context, MainActivity1.class);
        startActivity(intent);
    }
});

Edit:

It seems that you are missing a parameter in onCreateView in your ProfilFragment .

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_profile,container, false); //<--- Added false!
    initViews(view);
    return view;
}

The standard is to attach the view to the parent, so you need to tell the inflater not to attach it.

In your fragment you need to change the following line:

**View mView = inflater.inflate(R.layout.yourfragment, parent, false);**

or do it like below:

if (mView == null) {
    mView = inflater.inflate(R.layout.yourfragment, container, false);
} else {
    ((ViewGroup) mView .getParent()).removeView(mView );
}

The problem is with inflating layout in the fragment.

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