Как сохранить профиль Google после входа в Google в другой активности - PullRequest
0 голосов
/ 10 сентября 2018

Я новичок в программировании Android.Я успешно интегрировал вход в Google и успешно передал данные в другое действие.Но когда я возвращаюсь к активности через навигационный ящик, где я передавал данные, он высевает пустой экран.Я хочу сохранить профиль пользователя в этой деятельности.Я хочу сохранить информацию о пользователе, нажав кнопку «Сохранить» в приложении, чтобы отобразить его как профиль пользователя.Пожалуйста, помогите мне в решении этой проблемы.Спасибо, заранее за решение.

Вот мои java-файлы и XML-файлы.

activity_main3.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main3Activity">


<LinearLayout
    android:id="@+id/prof_section"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="50dp"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/prof_pic"
        android:layout_width="90dp"
        android:layout_height="125dp"
        android:src="@drawable/profilep" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="28dp"
        android:layout_marginTop="20dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Disply Name Here"
            android:textSize="18dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="Disply Email Here"
            android:textSize="18dp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/butn_logout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Logout"

            />

    </LinearLayout>


</LinearLayout>

<com.google.android.gms.common.SignInButton
    android:id="@+id/butn_login"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="50dp"
    android:layout_marginRight="50dp"
    android:layout_marginTop="60dp"  >
</com.google.android.gms.common.SignInButton>

activity_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Detail">

<ImageView
    android:id="@+id/dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp" />

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp" />

<TextView
    android:id="@+id/email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp" />

<Button
    android:id="@+id/button_save"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="SAVE" />

Detail.Java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    dp = (ImageView) findViewById(R.id.dp);
    name = (TextView) findViewById(R.id.name);
    email = (TextView) findViewById(R.id.email);


    Intent i = getIntent();
    final String i_name, i_email, i_url;
    i_name = i.getStringExtra("p_name");
    i_email = i.getStringExtra("p_email");
    i_url = i.getStringExtra("p_url");

    name.setText(i_name);
    email.setText(i_email);


    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(i_url);
                InputStream is = url.openConnection().getInputStream();
                final Bitmap bmp = BitmapFactory.decodeStream(is);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dp.setImageBitmap(bmp);
                    }
                });

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


}    

Main3Activity.Java

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


    preferenceConfig = new SharedPreferenceConfig(getApplicationContext());

    if (preferenceConfig.readLoginStatus()) {
        startActivity(new Intent(this, Main2Activity.class));
        finish();

    }


    Prof_Section = (LinearLayout) findViewById(R.id.prof_section);
    SignOut = (Button) findViewById(R.id.butn_logout);
    SignIn = (SignInButton) findViewById(R.id.butn_login);
    Name = (TextView) findViewById(R.id.name);
    Email = (TextView) findViewById(R.id.email);
    Prof_Pic = (ImageView) findViewById(R.id.prof_pic);
    SignIn.setOnClickListener(this);
    SignOut.setOnClickListener(this);
    Prof_Section.setVisibility(View.GONE);
    GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestProfile().build();
    googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();


}


@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.butn_login:
            signIn();
            break;

        case R.id.butn_logout:
            signOut();
            break;


    }

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}


private void signIn() {
    Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
    startActivityForResult(intent, REQ_CODE);


}

private void signOut() {
    Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            updateUI(false);
        }
    });

}


private void updateUI(boolean isLogin) {

    if (isLogin) {
        Prof_Section.setVisibility(View.VISIBLE);
        SignIn.setVisibility(View.GONE);


    } else {
        Prof_Section.setVisibility(View.GONE);
        SignIn.setVisibility(View.VISIBLE);

    }


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQ_CODE) {
        GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        GoogleSignInAccount account = googleSignInResult.getSignInAccount();


        String name = account.getDisplayName();
        String email = account.getEmail();
        String img_url = account.getPhotoUrl().toString();
        Name.setText(name);
        Email.setText(email);
        Glide.with(this).load(img_url).into(Prof_Pic);
        updateUI(true);
        preferenceConfig.writeLoginStatus(true);


        try {
            Intent sendData = new Intent(Main3Activity.this, Detail.class);

            name = account.getDisplayName();
            email = account.getEmail();


            img_url = account.getPhotoUrl().toString();
            sendData.putExtra("p_name", name);
            sendData.putExtra("p_email", email);
            sendData.putExtra("p_url", img_url);

            startActivity(sendData);

        } catch (Exception e) {
            Toast.makeText(Main3Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }


    } else {
        Toast.makeText(Main3Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
    }

}

1 Ответ

0 голосов
/ 10 сентября 2018

Используйте общие настройки для ваших целей.Вы можете прочитать больше об этом здесь .

Пример представлен здесь sharedPreferences

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...