Home » Android » Insert and update Database to last shown activity

Insert and update Database to last shown activity

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a simple problem (I think), that I cannot solve, even after much research. So for the first time I decided to post. I apologize if this is basic, or I cannot explain well. I’m a beginner.

I am devoloping a project, where I must connect to a database of movies, and get information through json.
At this point, I have my app running a list of playing now movies as other lists.
My goal (and problem) now is: When offline, show the last list displayed on the screen.
For that, I must somehow save that list to a database (I’ve never worked with db), and delete and update to a new one whenever i change screens on my app, so that the last list is displayed when online.
After that, I must show that last saved list (updated db).
Questions: where to code for insert (update) database?
How to convert that list into a db class? I think I must do that…
How to do the otherwise to insert that in a listview?
I use the same xml for that ListView? Since have the same params I think so…

So, here part of my code for this:

Fragment

public class NowPlayingMoviesFragment extends BaseFragment{
private ListView listMovies;
private Button buttonGetMore;
private List<Movie> movieList;
private int currentPage=1;
private MovieAdapter movieAdapter;
private ListView listOfflineMovies;
public static NowPlayingMoviesFragment newInstance() {
Bundle args = new Bundle();
NowPlayingMoviesFragment fragment = new NowPlayingMoviesFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.now_playing_movies_fragment, container, false);
findViews(v);
executeNowPlayingMoviesRequest();
addListeners();
return v;
}
private void executeNowPlayingMoviesRequest() {
new GetNowPlayingMoviesAsyncTask(getActivity(), String.valueOf(currentPage), getResources().getString(R.string.language)) {
@Override
protected void onResponseSuccess(MoviesResponse moviesResponse) {
DLog.d(tag, "onResponseSuccess " + moviesResponse);
// create the adapter
if (movieAdapter != null) {
List<Movie> movies = moviesResponse.getMovies();
for (int i = 0; i < movies.size(); i++) {
movieList.add(movies.get(i));
}
movieAdapter.notifyDataSetChanged();
**//is it here i save into db??**
} else {
movieList = moviesResponse.getMovies();
movieAdapter = new MovieAdapter(getActivity(), movieList);
listMovies.setAdapter(movieAdapter);
}
}
@Override
protected void onNetworkError () {
DLog.d(tag, "onNetworkError ");
// Here i now that some error occur when processing the request,
// possible my internet connection if turned off
//OfflineMovieDbEntity();
//MoviesItemDbEntity offlineMovies = new MoviesItemDbEntity(getActivity(),Movie.getOriginalTitle());
// MoviesItemDbEntity offlineMovies = offlineMovies.findById(offLineMovies.class,1)
}
}.execute();
}
private void findViews(View v) {
listMovies = (ListView) v.findViewById(R.id.now_playing_movies_list_view);
buttonGetMore = (Button) v.findViewById(R.id.get_more_button_movies_now);
listOfflineMovies = (ListView) v.findViewById(R.id.offline_movies_screen_list_view);
}
private void addListeners() {
buttonGetMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentPage=currentPage+1;
executeNowPlayingMoviesRequest();
}
});
}
}
---------------------------------------------------------------
# Movie Adapter #
public class MovieAdapter extends ArrayAdapter<Movie> {
public MovieAdapter(@NonNull Context context, @NonNull List<Movie> objects) {
super(context, 0, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View v;
final ViewHolder holder;
final Movie item = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.movie_item, parent, false);
holder = new ViewHolder(v);
v.setTag(holder);
} else {
v = convertView;
holder = (ViewHolder) v.getTag();
}
holder.movieTitle.setText(item.getTitle());
//See movie details onclick
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), MovieDetailsScreen.class);
intent.putExtra("Movie", item);
getContext().startActivity(intent);
}
});
return v;
}
static class ViewHolder {
private TextView movieTitle;
public ViewHolder(View v) {
movieTitle = (TextView) v.findViewById(R.id.movie_item_title);
}
}
}
------------------------------------------------------------------------
#movie entitie#
public class Movie implements Parcelable {
@SerializedName("poster_path")
private String posterPath;
@SerializedName("overview")
private String overview;
@SerializedName("release_date")
private String releaseDate;
@SerializedName("original_title")
private String originalTitle;
@SerializedName("original_language")
private String originalLanguage;
@SerializedName("title")
private String title;
@SerializedName("backdrop_path")
private String backdropPath;
@SerializedName("popularity")
private Double popularity;
@SerializedName("vote_count")
private Integer voteCount;
@SerializedName("vote_average")
private Double voteAverage;
public String getPosterPath() {
return posterPath;
}
public String getOverview() {
return overview;
}
public String getReleaseDate() {
return releaseDate;
}
public String getOriginalTitle() {
return originalTitle;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public String getTitle() {
return title;
}
public String getBackdropPath() {
return backdropPath;
}
public Double getPopularity() {
return popularity;
}
public Integer getVoteCount() {
return voteCount;
}
public Double getVoteAverage() {
return voteAverage;
}
public Movie() {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.posterPath);
dest.writeString(this.overview);
dest.writeString(this.releaseDate);
dest.writeString(this.originalTitle);
dest.writeString(this.originalLanguage);
dest.writeString(this.title);
dest.writeString(this.backdropPath);
dest.writeValue(this.popularity);
dest.writeValue(this.voteCount);
dest.writeValue(this.voteAverage);
}
protected Movie(Parcel in) {
this.posterPath = in.readString();
this.overview = in.readString();
this.releaseDate = in.readString();
this.originalTitle = in.readString();
this.originalLanguage = in.readString();
this.title = in.readString();
this.backdropPath = in.readString();
this.popularity = (Double) in.readValue(Double.class.getClassLoader());
this.voteCount = (Integer) in.readValue(Integer.class.getClassLoader());
this.voteAverage = (Double) in.readValue(Double.class.getClassLoader());
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
@Override
public Movie createFromParcel(Parcel source) {
return new Movie(source);
}
@Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
-----------------------------------------------------------------
#movies response#
public class MoviesResponse {
@SerializedName("page")
private Integer page;
@SerializedName("results")
private List<Movie> movies = new ArrayList<>();
@SerializedName("total_pages")
private Integer totalPages;
public Integer getPage() {
return page;
}
public Integer getTotalPages() {
return totalPages;
}
public List<Movie> getMovies() {
return movies;
}
}
-----------------------------------------------------------
MovieAsyncTask
public abstract class GetNowPlayingMoviesAsyncTask extends ExecuteRequestAsyncTask<MoviesResponse> {
private static final String PATH = "/movie/now_playing";
private static final String LANGUAGE_KEY = "language";
private static final String PAGE_KEY = "page";
private String page;
private String language;
public GetNowPlayingMoviesAsyncTask(Context context, String page, String language) {
super(context);
this.page=page;
this.language=language;
}
@Override
protected String getPath() {
return PATH;
}
@Override
protected void addQueryParams(StringBuilder sb) {
addQueryParam(sb, LANGUAGE_KEY, language);
addQueryParam(sb, PAGE_KEY, page);
}
@Override
protected Class<MoviesResponse> getResponseEntityClass() {
return MoviesResponse.class;
}
}
-----------------------------------------
#Movie Database#
public class MoviesItemDbEntity extends SugarRecord {
public static final String TITLE_COLUMN_NAME = "movie_title_column";
private String title;
public MoviesItemDbEntity() {
}
public MoviesItemDbEntity(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String setTitle() {
return title;
}
}
---------------------------------------------------------
#Movie Item xml#
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center_horizontal">
<TextView
android:id="@+id/movie_item_title"
style="@style/ItemListStyle"
android:text="lalalala"/>
</LinearLayout>
---------------------------------------------------------------
#now playing ListView xml#
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="@+id/now_playing_movies_title"
style="@style/TitleStyle"
android:text="@string/movies"/>
<Button
android:id="@+id/get_more_button_movies_now"
style="@style/ButtonMoreStyle"/>
<ListView
android:id="@+id/now_playing_movies_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/now_playing_movies_title">
</ListView>
</RelativeLayout>
Answers: