Newer
Older
NemophilaClient / app / src / main / java / com / example / nemophila / MyPageEditorActivity.java
package com.example.nemophila;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.nemophila.entities.Account;
import com.example.nemophila.viewmodels.AccountViewModel;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyPageEditorActivity extends AppCompatActivity {
    //フィールド
    private String icon;
    private Nemophila nemophila;
    private String uid;
    private String token;
    private ImageButton iconButton;
    private ExecutorService executor;
    private Handler handler;
    private String iconUrlString;
    private boolean iconFlag;
    //マイページ編集画面の作成
    private ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.OpenDocument(), new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            if(uri == null)return;
            ImageButton changeIconButton = findViewById(R.id.changeIconButton);
            changeIconButton.setImageURI(uri);
            try {
                InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(uri);
                Bitmap bitmap = BitmapFactory.decodeStream(new BufferedInputStream(inputStream));
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                icon = Base64.getEncoder().encodeToString(byteArray);
                iconFlag = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    });

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

        // 初期化
        AccountViewModel accountViewModel = new ViewModelProvider(this).get(AccountViewModel.class);
        nemophila = (Nemophila) getApplication();
        uid = nemophila.getUid();
        token = nemophila.getToken();
        iconButton = findViewById(R.id.changeIconButton);
        executor = Executors.newSingleThreadExecutor();
        handler = new Handler();
        iconUrlString = "http://nitta-lab-www.is.konan-u.ac.jp/nemophila-data/icon"+uid+".jpg";
        iconFlag = false;

        // アカウントのアイコンを表示
        iconButton.setImageBitmap(nemophila.getIcon());

        //MyPageに戻るボタン
        ImageButton backButton = findViewById(R.id.backMyPage);
        backButton.setOnClickListener(v -> {
            Intent intent = new Intent(MyPageEditorActivity.this, MyPageActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        });

        iconButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                launcher.launch(new String[] {"image/*"});
            }
        });
        Button changeDefaultButton = findViewById(R.id.changeDefaultButton);
        changeDefaultButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iconUrlString = "http://nitta-lab-www.is.konan-u.ac.jp/nemophila-data/test01.jpg";
                setIcon(iconButton);
                iconFlag = true;
            }
        });
        //変更確定ボタンを押した場合の動き
        Button changeDecisionButton = findViewById(R.id.changeConfirm);
        changeDecisionButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //名前とパスワードを取り込む
                EditText editName = findViewById(R.id.editName);
                String newName = editName.getText().toString();
                EditText editOldPw = findViewById(R.id.editOldPw);
                String oldPw = editOldPw.getText().toString();
                EditText editNewPw = findViewById(R.id.editNewPw);
                String newPw = editNewPw.getText().toString();

                // 名前が入力されているとき通信を行う
                if(newName.length() > 0) {
                    System.out.println(newName);
                    nemophila.setName(newName);
                    accountViewModel.changeName(uid, newName, token);
                }
                // パスワードが入力されているとき通信を行う
                if(oldPw.length() > 0 && newPw.length() > 0) {
                    accountViewModel.changePw(uid, oldPw, newPw, token);
                }
                // アイコンが入力されているとき通信を行う
                if(iconFlag){
                    Bitmap iconBitmap = ((BitmapDrawable) iconButton.getDrawable()).getBitmap();
                    nemophila.setIcon(iconBitmap);
                    accountViewModel.changeIcon(uid, icon, token);
                }

            }
        });

        // ログアウトボタンを押したときの処理
        Button logoutButton = findViewById(R.id.logoutButton);
        logoutButton.setOnClickListener(v -> {
            new AlertDialog.Builder(this)
                    .setTitle("本当にログアウトしますか?")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            nemophila.logout();
                            Intent intent = new Intent(MyPageEditorActivity.this, LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }
                    })
                    .setNeutralButton("キャンセル", null)
                    .create()
                    .show();
        });

        // 削除ボタンを押したときの処理
        Button deleteAccountButton = findViewById(R.id.deleteAccount);
        deleteAccountButton.setOnClickListener(v -> {
            new AlertDialog.Builder(this)
                    .setTitle("本当に削除しますか?")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
//                            accountViewModel.deleteAccount(uid, token);
                        }
                    })
                    .setNeutralButton("キャンセル", null)
                    .create()
                    .show();
        });

        // ------------------------------ LiveDataへの購読 ------------------------------------------- //
        // アカウントの名前を取得した際のLiveDataの購読
        accountViewModel.getNameLiveData().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String name) {
                TextView myName = findViewById(R.id.editName);
                myName.setText(name);
                nemophila.setName(name);
            }
        });

        // アカウントのパスワードを取得した際のLiveDataの購読
        accountViewModel.getPwLiveData().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String Pw) {
                finish();
            }
        });

        // パスワードのエラーが発生した際のLiveDataの購読
        accountViewModel.getPwErrorLiveData().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String name) {
                Toast ts = Toast.makeText(MyPageEditorActivity.this, "パスワードが間違っています", Toast.LENGTH_SHORT);
                ts.setGravity(Gravity.CENTER, 0, 0);
                ts.show();
            }
        });

        // アカウントの削除をした際のLiveDataの購読
        accountViewModel.getSuccessDeleteAccountLiveData().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean isSuccess) {
                Intent intent = new Intent(MyPageEditorActivity.this, SignUpActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);startActivity(intent);
            }
        });

        // アカウントの削除をした際のエラーのLiveDataの購読
        accountViewModel.getDelAcErrorLiveData().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast ts = Toast.makeText(MyPageEditorActivity.this, s, Toast.LENGTH_SHORT);
                ts.setGravity(Gravity.CENTER, 0, 0);
                ts.show();
            }
        });
    }

    // アイコンに画像を設定
    private void setIcon(ImageView iv) {
        executor.execute(() -> {
            try{
                URL url = new URL(iconUrlString);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.connect();

                InputStream is = con.getInputStream();

                Bitmap bitmap = BitmapFactory.decodeStream(is);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                icon = Base64.getEncoder().encodeToString(byteArray);
                handler.post(() -> iv.setImageBitmap(bitmap));
                is.close();
                con.disconnect();
            }catch (Exception e){
                e.printStackTrace();
            }
        });
    }
}