将数据库插入并更新到上次显示的活动

时间:2017-10-22 17:42:08

标签: android database list listview offline

我有一个简单的问题(我认为),即使经过大量研究,我也无法解决。所以我第一次决定发帖。如果这是基本的,或者我无法解释,我道歉。我是初学者。

我正在开发一个项目,我必须连接到电影数据库,并通过json获取信息。 此时,我的应用程序正在运行一个现在正在播放电影的列表作为其他列表。 我现在的目标(和问题)是:离线时,显示屏幕上显示的最后一个列表。 为此,我必须以某种方式将该列表保存到数据库(我从未使用过数据库),并且每当我更改我的屏幕时删除并更新为新的应用程序,以便在线时显示最后一个列表。 之后,我必须显示上次保存的列表(更新的数据库)。 问题:插入(更新)数据库的代码在哪里? 如何将该列表转换为db类?我想我必须这样做...... 如何在列表视图中插入? 我为ListView使用相同的xml?既然有相同的参数,我想是这样......

所以,这是我的代码的一部分:

片段

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>

0 个答案:

没有答案