Search code examples
javaandroidandroid-studiosharedpreferences

Android Studio - How to implement this in an own class? (Shared Preferences)


I have a Class named "Movie" which has attributes like "title" and "length" etc. I managed to insert the wanted values using an user interface into some Editboxes. I wrote a function addMovie which created the Movie-Object which i added into a Movie-ArrayList.

After that i wanted to make the ArrayList Data persistent. I searched a little and have found this video : https://www.youtube.com/watch?v=jcliHGR3CHo The creator used SharedPreferences to store the data inside the App-Storage. However he wrote the save- and load-methods directly into the Class where he used them. I wanted to create a class specifically for Saving and Loading purposes.

So i made this(DataManger.java):

package com.example.watchassistant;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class DataManager {

public void saveData(ArrayList movieList) {

    SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(movieList);
    editor.putString("movie list", json);
    editor.apply();
}

public ArrayList<Movie> loadData() {
    SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString("movie list", null);
    Type type = new TypeToken<ArrayList<Movie>>() {
    }.getType();
    ArrayList<Movie> movieList;
    movieList = gson.fromJson(json, type);

    if (movieList == null) {
        movieList = new ArrayList<>();
    }
    return movieList;
}

The Movies are created here (AddMovie.java):

package com.example.watchassistant;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;


public class AddMovie extends AppCompatActivity {

    //Filmliste
    static ArrayList<Movie> movieList = new ArrayList<Movie>();
    static DataManager dm = new DataManager();

    //Variablen um Film zu erstellen
    String title = "";
    String releaseDate = "";
    String genre = "";
    String watchedAt = "";
    String ratingConv ="";
    double rating = 0.0;
    String comment = "";
    String lengthMinutes = "";
    String stream = "";
    String test = "";

    //Buttons
    Button addMovieBtn;

    //Inputboxen
    private EditText inputTitle;
    private EditText inputGenre;
    private EditText inputWatchedAt;
    private EditText inputStream;
    private EditText inputReleased;
    private EditText inputRating;
    private EditText inputLength;
    private EditText inputComment;

    //Outputboxen
    private TextView outputTest;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_movie);
        //dm.loadData();

        //Zuweisen der Elemente zu den Objekten
        addMovieBtn = (Button) findViewById(R.id.addMovieButton);
        inputTitle = (EditText) findViewById(R.id.titleInput);
        inputGenre = (EditText) findViewById(R.id.genreInput);
        inputWatchedAt = (EditText) findViewById(R.id.watchedInput);
        inputStream = (EditText) findViewById(R.id.streamingInput);
        outputTest = (TextView) findViewById(R.id.outputView);

        //Button Event Film Hinzufügen
        addMovieBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                movieList.add(addMovie());
                outputTest.setText(movieList.toString());
                dm.saveData(movieList);
            }
                });
    }
    public Movie addMovie() {
        //Needed
        title = inputTitle.getText().toString();
        genre = inputGenre.getText().toString();
        watchedAt = inputWatchedAt.getText().toString();
        stream = inputStream.getText().toString();
        //Optional
        //releaseDate = inputReleased.getText().toString();
        //ratingConv = inputRating.getText().toString();
        //rating = Double.parseDouble(ratingConv);
        //comment = inputComment.getText().toString();
        //lengthMinutes = inputLength.getText().toString();


        Movie m1 = new Movie(title, releaseDate, genre, stream, watchedAt, rating, comment, lengthMinutes);
        return m1;
    }
    }
 

Inside the DataManger.java i have the following problems:

Cannot resolve method 'getSharedPreferences' in 'DataManager'
Cannot resolve symbol 'MODE_PRIVATE'
Cannot resolve method 'getSharedPreferences' in 'DataManager'
Cannot resolve symbol 'MODE_PRIVATE'

Could anybody tell me a solution please? Or at least tell me if its possible to achieve what i'm trying. Thanks!

EDIT: In eclipse i used something like this:

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;


//Zuständig für das Speichern der Daten für die Wiederbenutzung nachdem das Programm beendet wurde 
public class ResourceManager {

    //Speichern
    public static void saveList(Serializable data, String filename) throws Exception
    {   
        try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(Paths.get(filename))))
        {
            oos.writeObject(data);
        }
    }
    
    //Laden
    public static ArrayList loadList(String filename) throws Exception
    {   
        ArrayList<Movie> movieList;
        try (ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(Paths.get(filename))))
        {
            movieList = (ArrayList<Movie>) ois.readObject(); // casting object
            return movieList;
        }
    }

}

How to implement it for android?


Solution

  • You need a context to call getSharedPreferences on. You could pass it in to your methods like this

    public void saveData(Context ctx, ArrayList movieList) {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences("shared preferences", MODE_PRIVATE);
        //...
    }
    
    public ArrayList<Movie> loadData(Context ctx) {
        SharedPreferences ctx.sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
        //...
        return movieList;
    }
    
    

    Then call it with a context (Activity or application context)

    addMovieBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            movieList.add(addMovie());
            outputTest.setText(movieList.toString());
            dm.saveData(AddMovie.this, movieList);
        }
    });
    
    dm.loadData(this);
    

    As noted in the comments though, if this is a large set of data using a Room database or other option like SQL might make more sense. However, your immediate problem is just a lack of a context object to call that method on.