한 걸음 두 걸음

android SharedPreferences 사용하기~ getSharedPreference 사용불가 해결 본문

FrontEnd/Android

android SharedPreferences 사용하기~ getSharedPreference 사용불가 해결

언제나 변함없이 2019. 3. 16. 14:59
반응형

SharedPreferences를 사용하기 위해서는
SharedPreferences pref = getSharedPreferences("파일명",MODE_PRIVATE);
방식으로 사용하는데,
여기서 getSharedPreferences가 빨간 줄이 생길 수 있다. 이는 원래
context.getSharedPreferences로 하는 것이기 때문에
SharedPreference를 사용하는 java코드(저같은 경우는 MainActivity)에서
Context mContext = getApplicationContext();함수로 mContext를 받아다가 매개변수로 전달해준 후,

public class BookItem {
    String txt;
    Context mContext;

    public BookItem(String txt, int count, Context context) {
        this.txt = txt;
        mContext = context;

    }

처럼 context를 받아와서 아래 보이는 것 처럼

 // 값 불러오기
    public int getReadCount(){
        SharedPreferences pref = mContext.getSharedPreferences("pref", MODE_PRIVATE);
        return pref.getInt("count", 0);
        //return pref;
    }

    // 값 저장하기
    public void setReadCount(int count){
        SharedPreferences pref = mContext.getSharedPreferences("pref", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putInt("count", count);
        editor.commit();
    }

mContext.getSharedPreferences함수를 무사히 사용할 수 있었습니다.

SharedPreferences는 Int같은 정수가 아니라 객체인 점, 주의해주세요~

putInt / putString
getInt / getString
(저장할수 있는 데이터 종류 : boolean, int, float, long, string )

이용("Name",Value);로 사용.

참고, 삭제할 때 editor.remove("Name");

//////////////////////////////////////////////////////////////////

임시저장코드
BookItem.java

package com.gkskfhdlstmapk.hanpinetree.bookapp;

import android.content.Context;
import android.content.SharedPreferences;

import static android.content.Context.MODE_PRIVATE;

public class BookItem {
    String txt;
    Context mContext;

    public BookItem(String txt, int count, Context context) {
        this.txt = txt;
        mContext = context;

    }

    public String getTxt() {
        return txt;
    }

    public void setTxt(String txt) {
        this.txt = txt;
    }

    @Override
    public String toString() {
        return "BookItem{" +
                "txt='" + txt + '\'' +
                '}';
    }

    //SharedPreferences 사용함수

    // 값 불러오기
    public int getReadCount(){
        SharedPreferences pref = mContext.getSharedPreferences("pref", MODE_PRIVATE);
        return pref.getInt("count", 0);
        //return pref;
    }

    // 값 저장하기
    public void setReadCount(int count){
        SharedPreferences pref = mContext.getSharedPreferences("pref", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putInt("count", count);
        editor.commit();
    }


}

MainActivity.java

package com.gkskfhdlstmapk.hanpinetree.bookapp;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    BookAdapter adapter;
    EditText editText;
    Context mContext;

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

        editText = (EditText)findViewById(R.id.editText);
        ListView listView = (ListView)findViewById(R.id.listView);
        mContext = getApplicationContext();

        adapter = new BookAdapter();


        try {
            //파일 있는지 확인들어갑니다~
            File f = new File(getFilesDir() + "test.txt");
            if(!f.isFile()) {
                //파일이 없으면 다음과 같이 실행해줍니다.
                BufferedWriter bw = new BufferedWriter(new FileWriter(getFilesDir() + "test.txt", true));
                PrintWriter pw = new PrintWriter(bw, true);
                pw.write(allTxt());
                pw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "예외발생", Toast.LENGTH_LONG).show();
        }
        String alltxt = readTxt();

        String[] word = alltxt.split("@@@");

        ///

        for(int i = 0 ; i < word.length; i++){
            adapter.addItem(new BookItem(word[i],0, mContext)); //mContext 수정해주었습니다~
        }

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BookItem item = (BookItem)adapter.getItem(position);
                show(item.getTxt(), item);

            }
        });

        Button btn_plus = (Button)findViewById(R.id.btn_plus);
        btn_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String plus_content = editText.getText().toString();
                adapter.addItem(new BookItem(plus_content,0,mContext));

                try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(getFilesDir() + "test.txt",true));
                    PrintWriter pw = new PrintWriter(bw,true);
                    pw.write(plus_content);
                    pw.close();
                }catch (IOException e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"1. 예외발생",Toast.LENGTH_LONG).show();
                }
                adapter.notifyDataSetChanged();
                try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(getFilesDir() + "test.txt",true));
                    PrintWriter pw = new PrintWriter(bw,true);
                    pw.write("@@@");
                    pw.close();
                }catch (IOException e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"2. 예외발생",Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    private String allTxt(){
        String data = null;
        InputStream inputStream = getResources().openRawResource(R.raw.test);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int i;
        try {
            i = inputStream.read();
            while (i != -1) {
                //if(i == 64) {byteArrayOutputStream.write('\n');byteArrayOutputStream.write('\n');}
                //else
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            data = new String(byteArrayOutputStream.toByteArray(),"MS949");

            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    //editText로 반환되는 텍스트를 추가하는 함수입니다.
    private String readTxt() {
        String readStr = "";
        String str = null;

        try{
        BufferedReader br = new BufferedReader(new FileReader(getFilesDir()+"test.txt"));

        while ((str = br.readLine()) != null) readStr += str+"\n";
        br.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"파일이 없습니다.",Toast.LENGTH_LONG).show();
        }catch (IOException e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"IO예외발생",Toast.LENGTH_SHORT).show();
        }
        return readStr;
    }

    //자세히보기 Dialog창 설정함수입니다.
    void show(String txt, final BookItem item){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("자세히보기"); //타이틀설정
        builder.setMessage(txt); //내용설정

        builder.setPositiveButton("읽음",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        item.setReadCount(item.getReadCount()+1);
                        Toast.makeText(getApplicationContext(),"현재 Count : "+item.getReadCount(),Toast.LENGTH_LONG).show();
                        adapter.notifyDataSetChanged();
                    }
                });

        builder.setNegativeButton("취소",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"취소완료",Toast.LENGTH_LONG).show();
                    }
                });
        builder.show();
    }

    ///////

    //BookAdater클래스입니다.
    class BookAdapter extends BaseAdapter{
        ArrayList<BookItem> items = new ArrayList<BookItem>();

        public void addItem(BookItem item){
            items.add(item);
        }
        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            BookItemView view = null;
            if(convertView == null){
                view =  new BookItemView(getApplicationContext());
            }else {
                view = (BookItemView)convertView;
            }

            BookItem item = items.get(position);
            view.setTxt(item.getTxt());
            view.setReadCount(item.getReadCount());

            return view;

        }
    }
}

지금은 SharedPreferences FileName = "pref"로 다 연동되어버리는 문제점이 있어서
안드로이드 개발 SharedPreferences 객체와 배열 저장을 위한 gson 사용하는 방법을 찾아보고있음. 그냥 데이터베이스 공부하지않을래?ㅠㅠ 그게 더 쉬울 수 있을 것 같아 엉어유ㅠ
하여튼,,, 해봅시당.
->Gson 으로 변환하는 Class 따로 SharedPreference 관리해주는 Class
따로 만들어서 관리하면 편할 것!
참고 : https://mainia.tistory.com/5602

//local로 저장하지 못했을 때 코드도 첨부함.

package com.gkskfhdlstmapk.hanpinetree.bookapp;

public class BookItem {
    String txt;
    int readCount;

    public BookItem(String txt,int count) {
        this.txt = txt;
        this.readCount = count;
    }

    public String getTxt() {
        return txt;
    }

    public void setTxt(String txt) {
        this.txt = txt;
    }

    public int getReadCount() {
        return readCount;
    }

    public void setReadCount(int readCount) {
        this.readCount = readCount;
    }

    @Override
    public String toString() {
        return "BookItem{" +
                "txt='" + txt + '\'' +
                '}';
    }
}

//BookItem.java
//Main,Context추가한이후
package com.gkskfhdlstmapk.hanpinetree.bookapp;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    BookAdapter adapter;
    EditText editText;
    Context mContext;

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

        editText = (EditText)findViewById(R.id.editText);
        ListView listView = (ListView)findViewById(R.id.listView);
        mContext = getApplicationContext();

        adapter = new BookAdapter();


        try {
            //파일 있는지 확인들어갑니다~
            File f = new File(getFilesDir() + "test.txt");
            if(!f.isFile()) {
                //파일이 없으면 다음과 같이 실행해줍니다.
                BufferedWriter bw = new BufferedWriter(new FileWriter(getFilesDir() + "test.txt", true));
                PrintWriter pw = new PrintWriter(bw, true);
                pw.write(allTxt());
                pw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "예외발생", Toast.LENGTH_LONG).show();
        }
        String alltxt = readTxt();

        String[] word = alltxt.split("@@@");

        ///

        for(int i = 0 ; i < word.length; i++){
            adapter.addItem(new BookItem(word[i],0, mContext)); //mContext 수정해주었습니다~
        }

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BookItem item = (BookItem)adapter.getItem(position);
                show(item.getTxt(), item);

            }
        });

        Button btn_plus = (Button)findViewById(R.id.btn_plus);
        btn_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String plus_content = editText.getText().toString();
                adapter.addItem(new BookItem(plus_content,0,mContext));

                try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(getFilesDir() + "test.txt",true));
                    PrintWriter pw = new PrintWriter(bw,true);
                    pw.write(plus_content);
                    pw.close();
                }catch (IOException e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"1. 예외발생",Toast.LENGTH_LONG).show();
                }
                adapter.notifyDataSetChanged();
                try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(getFilesDir() + "test.txt",true));
                    PrintWriter pw = new PrintWriter(bw,true);
                    pw.write("@@@");
                    pw.close();
                }catch (IOException e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"2. 예외발생",Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    private String allTxt(){
        String data = null;
        InputStream inputStream = getResources().openRawResource(R.raw.test);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int i;
        try {
            i = inputStream.read();
            while (i != -1) {
                //if(i == 64) {byteArrayOutputStream.write('\n');byteArrayOutputStream.write('\n');}
                //else
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            data = new String(byteArrayOutputStream.toByteArray(),"MS949");

            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    //editText로 반환되는 텍스트를 추가하는 함수입니다.
    private String readTxt() {
        String readStr = "";
        String str = null;

        try{
        BufferedReader br = new BufferedReader(new FileReader(getFilesDir()+"test.txt"));

        while ((str = br.readLine()) != null) readStr += str+"\n";
        br.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"파일이 없습니다.",Toast.LENGTH_LONG).show();
        }catch (IOException e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"IO예외발생",Toast.LENGTH_SHORT).show();
        }
        return readStr;
    }

    //자세히보기 Dialog창 설정함수입니다.
    void show(String txt, final BookItem item){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("자세히보기"); //타이틀설정
        builder.setMessage(txt); //내용설정

        builder.setPositiveButton("읽음",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        item.setReadCount(item.getReadCount()+1);
                        Toast.makeText(getApplicationContext(),"현재 Count : "+item.readCount,Toast.LENGTH_LONG).show();
                        adapter.notifyDataSetChanged();
                    }
                });

        builder.setNegativeButton("취소",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"취소완료",Toast.LENGTH_LONG).show();
                    }
                });
        builder.show();
    }

    ///////

    //BookAdater클래스입니다.
    class BookAdapter extends BaseAdapter{
        ArrayList<BookItem> items = new ArrayList<BookItem>();

        public void addItem(BookItem item){
            items.add(item);
        }
        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            BookItemView view = null;
            if(convertView == null){
                view =  new BookItemView(getApplicationContext());
            }else {
                view = (BookItemView)convertView;
            }

            BookItem item = items.get(position);
            view.setTxt(item.getTxt());
            view.setReadCount(item.getReadCount());

            return view;

        }
    }
}

반응형