如何从SQLite数据库填充recyclerview

时间:2018-06-14 04:06:50

标签: android sqlite android-recyclerview recycler-adapter

我想问一下,如何在我的Android应用程序中填充来自SQLite数据库的recyclerview。实际上,数据来自远程服务器通过json,我的任务是填充recyclerview,当Internet可用时填充API调用,如果它不可用,那么我必须将该远程服务器响应保存到本地SQLite数据库,以便我可以获取保存的结果,并在没有互联网的情况下填充列表

public class SQLiteHandler extends SQLiteOpenHelper {

private static final String TAG = SQLiteHandler.class.getSimpleName();

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "image_api";

// Login table name
private static final String TABLE_LIST = "images";

// Login Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_ALBUMID = "albumid";
public static final String KEY_THUMBNAILURL = "thumbnailurl";
public static final String KEY_IMAGE = "image";

SQLiteHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LIST + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
            + KEY_ALBUMID + " TEXT UNIQUE," + KEY_THUMBNAILURL + " TEXT,"
            + KEY_IMAGE + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);

    Log.d(TAG, "Database tables created");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST);

    // Create tables again
    onCreate(db);

}

/**
 * Storing user details in database
 * */
void addUser(String Id, String title, String albumid, String thumbnailurl, String image) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_ID, Id); // Name
    values.put(KEY_TITLE, title); // Email
    values.put(KEY_ALBUMID, albumid); // Email
    values.put(KEY_THUMBNAILURL, thumbnailurl);
    values.put(KEY_IMAGE, image);// Created At

    // Inserting Row
    long id = db.insert(TABLE_LIST, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "New user inserted into sqlite: " + id);
}

/**
 * Getting user data from database
 * */
public HashMap<String, String> getUserDetails() {
    HashMap<String, String> user = new HashMap<String, String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LIST;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        user.put("Id", cursor.getString(1));
        user.put("title", cursor.getString(2));
        user.put("albumid", cursor.getString(3));
        user.put("thumbnailurl", cursor.getString(4));
        user.put("image", cursor.getString(5));
    }
    cursor.close();
    db.close();
    // return user
    Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

    return user;
}

long getProfilesCount() {
    SQLiteDatabase db = this.getReadableDatabase();
    long count = DatabaseUtils.queryNumEntries(db, TABLE_LIST);
    db.close();
    return count;
}


public Cursor getAllPersons() {
    SQLiteDatabase db = this.getReadableDatabase();
    return db.rawQuery( "SELECT * FROM " + TABLE_LIST, null );
}


 }

这是我的mainActivity

public class MainActivity extends AppCompatActivity {

private List<Movie> movieList;
private RecyclerView.Adapter adapter;
private SQLiteHandler db;
long profile_counts;
//private ArrayList noList;


@Override
protected void onDestroy() {
    super.onDestroy();
    if (db != null)
        db.close();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RecyclerView mList = findViewById(R.id.main_list);
    db = new SQLiteHandler(getApplicationContext());
    profile_counts = db.getProfilesCount();

    movieList = new ArrayList<>();
    adapter = new MovieAdapter(getApplicationContext(), movieList);


    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());

    mList.setHasFixedSize(true);
    mList.setLayoutManager(linearLayoutManager);
    mList.addItemDecoration(dividerItemDecoration);
    mList.setAdapter(adapter);

    if (isNetworkAvailable()) {
        getData();
    }

    else

        {

            Toast.makeText(MainActivity.this,"No Internet",Toast.LENGTH_LONG).show();



    }


}


private void getData() {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMax(100);
    progressDialog.setMessage("Its loading....");
    progressDialog.setTitle("Imageview Example");
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.show();

    String url = "http://jsonplaceholder.typicode.com/photos";
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject jsonObject = response.getJSONObject(i);

                    Movie movie = new Movie();
                    movie.setTitle(jsonObject.getString("title"));
                    movie.setId(jsonObject.getInt("id"));
                    movie.setImage(jsonObject.getString("url"));
                    movie.setAlbumid(jsonObject.getString("albumId"));
                    movie.setThumbnailurl(jsonObject.getString("thumbnailUrl"));


                    movieList.add(movie);

                    String Title = jsonObject.getString("title");
                    String Id = jsonObject.getString("id");
                    String Image = jsonObject.getString("url");
                    String Album = jsonObject.getString("albumId");
                    String Thumbnail = jsonObject.getString("thumbnailUrl");


                    Log.e("List Loaded", "imagesList");
                    Log.i("Title", Title);
                    Log.i("Id", Id);
                    Log.i("Image", Image);
                    Log.i("Album", Album);
                    Log.i("Thumbnail", Thumbnail);

                    db.addUser(Id, Title, Album, Thumbnail, Image);
                    Log.d("number of elements", String.valueOf(profile_counts));


                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
            adapter.notifyDataSetChanged();
            progressDialog.dismiss();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
            progressDialog.dismiss();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}


private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = null;
    if (connectivityManager != null) {
        activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    }
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

 }

现在我只想知道如何从SQLite数据库填充recyclerview,到目前为止我已经能够从远程服务器获取数据并在SqliteHandler类的帮助下将其保存在SQLite数据库中。这是我的适配器类

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {

private Context context;
private List<Movie> list;
private String link;
private imageDownload image;

MovieAdapter(Context context, List<Movie> list) {
    this.context = context;
    this.list = list;

}


@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(context).inflate(R.layout.list, parent, false);
    return new ViewHolder(v);

}

@Override
public void onBindViewHolder(@NonNull final MovieAdapter.ViewHolder holder,  int position) {

    Movie movie = list.get(position);


    holder.textTitle.setText(movie.getTitle());
    holder.textId.setText(String.valueOf(movie.getId()));
    holder.textThumb.setText(movie.getThumbnailurl());
    holder.textAlbum.setText(String.valueOf(movie.getAlbumid()));

    Picasso.with(context).load(movie.getImage())
            .into(holder.photo);


    holder.photo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            link = list.get(holder.getAdapterPosition()+1).getImage();
            image = new imageDownload(context, holder.photo);
            image.execute(link);
            Log.e("image link", link);
            Toast.makeText(context, "image clicked: " + holder.getAdapterPosition(), Toast.LENGTH_LONG).show();
        }
    });

}


@Override
public int getItemCount() {
    return list.size();
}


class ViewHolder extends RecyclerView.ViewHolder {
    TextView textTitle, textId, textThumb, textAlbum;
    ImageView photo;

    ViewHolder(View itemView) {
        super(itemView);

        textTitle = itemView.findViewById(R.id.title_1);
        textId = itemView.findViewById(R.id.id_1);
        textThumb = itemView.findViewById(R.id.thumbnailurl_1);
        textAlbum = itemView.findViewById(R.id.albumid_1);
        photo = itemView.findViewById(R.id.imageview);


    }
}


class imageDownload extends AsyncTask<String, Integer, Bitmap> {
    Context context;
    ImageView imageView;
    Bitmap bitmap;
    InputStream in = null;

    //constructor.
    imageDownload(Context context, ImageView imageView) {
        this.context = context;
        this.imageView = imageView;
    }

    @Override
    protected void onPreExecute() {


    }

    @Override
    protected Bitmap doInBackground(String... params) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(params[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.connect();


            in = httpURLConnection.getInputStream();
            BufferedInputStream bufferedInputStream = new 
            BufferedInputStream(in);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap data) {

        imageView.setImageBitmap(data);
        try {
            try {
                saveImage(data);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // System.out.print(Log.e("Image Data",data.toString()));
    }

    private void saveImage(Bitmap data) throws FileNotFoundException, MalformedURLException {

        File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test");

        File saveImage = new File(createFolder, "downloadedImage.jpg");
        try {
            OutputStream outputStream = new FileOutputStream(saveImage);
            data.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }




}

}
 }

Movie.class

public class Movie {


public String title;

public String getAlbumid() {
    return albumid;
}

public void setAlbumid(String albumid) {
    this.albumid = albumid;
}

public String getThumbnailurl() {
    return thumbnailurl;
}

public void setThumbnailurl(String thumbnailurl) {
    this.thumbnailurl = thumbnailurl;
}

public String albumid;
public String thumbnailurl;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

private int id;
private String image;

public  Movie() {

}

public Movie(String title, String image, int id) {
    this.title = title;
    this.image = image;
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}



}

1 个答案:

答案 0 :(得分:2)

以下代码是从Sqlite DB获取数据并在Recycler视图中显示数据的简单示例

private List<Movie> movieList;
private RecyclerView mRecyclerView;
private MovieAdapter adapter;
private SQLiteHandler db;


     Cursor cursor = db.getUserDetails();

                    if (cursor.moveToFirst()) {
                        do {
                            movieList.add(new Movie(
                                    cursor.getInt(0),
                                    cursor.getString(1),
                                    cursor.getString(2),
                                    cursor.getString(3),
                                    cursor.getDouble(4)
                            ));
                        } while (cursor.moveToNext());


                        MovieAdapter adapter = new MovieAdapter(this, movieList);
                        mRecyclerView.setAdapter(adapter);
    }