package com.example.myapplication;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 0;
private ImageView imageView;
EditText et_name, et_age;
AppCompatButton bt_save;
SharedPreferences sp;
Gson gson;
String contact_person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.image);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_CODE);
}
});
et_name = findViewById(R.id.et_name);
et_age = findViewById(R.id.et_age);
bt_save = findViewById(R.id.bt_save);
imageView = findViewById(R.id.image);
sp = getSharedPreferences("shared", MODE_PRIVATE);
gson = new GsonBuilder().create();
contact_person = sp.getString("contact_person", "");
if (!contact_person.equals("")) {
Person person = gson.fromJson(contact_person, Person.class);
et_name.setText(person.getName());
et_age.setText(person.getAge() + "");
}
bt_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contact_person = "";
String name = et_name.getText().toString();
int age = Integer.parseInt(et_age.getText().toString());
Person person = new Person(name, age);
contact_person = gson.toJson(person, Person.class);
SharedPreferences.Editor editor = sp.edit();
editor.putString("contact_person", contact_person);
editor.commit();
Toast.makeText(MainActivity.this, "저장되었습니다", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
try {
InputStream in = getContentResolver().openInputStream(data.getData());
Bitmap img = BitmapFactory.decodeStream(in);
in.close();
imageView.setImageBitmap(img);
} catch (Exception e) {
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "사진 선택 취소", Toast.LENGTH_LONG).show();
}
SharedPreferences test = getSharedPreferences("test", MODE_PRIVATE);
test.edit();
}
}
}
버튼을 클릭해서 갤러리에서 불러온 사진값이 에뮬레이터에서 앱을 종료하고 다시실행시 초기화 됩니다. 앱 재실행시 값을 유지하고싶은데 코딩을 어떻게 해야할까요?