如何从本地 sqlite 糖数据库检索数据 android

How to retrieve data from local sqlite sugar database android

我一直在开发一个应用程序,它使用 sugar ORM 将数据存储在本地 sqlite 数据库中,并将其发布到列表视图中,所以我的任务是从来自 [=30= 的直接数据发布列表视图] 当互联网连接可用但如果连接不可用时,我必须检索数据库中已保存的数据并填充到列表视图中,我已经能够下载并保存数据但是当网络不可用时我必须在没有发生的 getdatafromlocal 方法中检索它

MainActivity.java 文件

public class MainActivity extends AppCompatActivity {

private List<Movie> movieList;
private RecyclerView.Adapter adapter;
JSONObject jsonObject;
List<Note> note;
CursorAdapter c;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RecyclerView mList = findViewById(R.id.main_list);

    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);
   // getData();

    if (isNetworkAvailable()) {
        getData();

    }

    else
    {
        getDataFromLocal();
        Toast.makeText(getApplicationContext(),"no internet",Toast.LENGTH_SHORT).show();
        Toast.makeText(getApplicationContext(),"populating from local data",Toast.LENGTH_SHORT).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 < 20; i++) {
                try {
                     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");

                    note = new ArrayList<>();
                    note.add(new Note(Title,Image,Album,Thumbnail));

                    SugarRecord.saveInTx(note);

                    note.size();

                    copydatabase();
                    Toast.makeText(getApplicationContext(), "Rows Inserted 
        into local storage too", Toast.LENGTH_SHORT).show();


                    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);


                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            try {
                copydatabase();
            } catch (IOException e) {
                e.printStackTrace();
            }

            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 void getDataFromLocal() {

    //what to do next

}


public void copydatabase() throws IOException {

    //File actualFile = null;

    File actualFile= new File(new 
   SugarDb(MainActivity.this).getDB().getPath()); //actual file
    File curentfile  = new File(actualFile.toString()); //new file generated
    Log.e("actualPath", actualFile.toString());


    File newFile = createTempFile("SugarImagesList",".db", 
  Environment.getExternalStorageDirectory());
    newFile.mkdirs();
    if(!newFile.mkdirs()){
        Toast.makeText(MainActivity.this, "file exists", 
 Toast.LENGTH_SHORT).show();
    }

    Log.e("newPath", newFile.toString());

    boolean yes= FileUtils.copyFile(curentfile,newFile);

    if(yes) {
        Log.e("result", "" + true);
        Toast.makeText(getApplicationContext(), "Database Copied to SD card", 
   Toast.LENGTH_SHORT).show();
    }
    }

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

}

Movie.java 文件

public class Movie  {


public String title;
public String albumid;
public String thumbnailurl;

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 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, String albumid, String 
     thumbnailurl ) {
       this.title = title;
       this.image = image;
       this.id = id;
       this.albumid = albumid;
       this.thumbnailurl = thumbnailurl;
   }

public String getTitle() {
    return title;
}

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

 }

Note.java 文件

public class Note extends SugarRecord {

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;


String getImage() {
    return image;
}

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

private String image;

public Note(String title ,String image,String albumid, String thumbnailurl) 

   {
       this.title = title;
       this.image = image;
       this.albumid = albumid;
       this.thumbnailurl = thumbnailurl;
   }

  public String getTitle() {
     return title;
   }

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

    }

MovieAdapter.java class

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();
        }




   }

  }
}

经过几次尝试和错误后,我已经能够通过 Sugar ORM 检索存储在本地数据库中的数据,我稍微更改了 MainActivity 以获得所需的结果

public class MainActivity extends AppCompatActivity {

EditText firstname;
EditText lastname;
Button button;
Note note;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    firstname=findViewById(R.id.edit1);
    lastname=findViewById(R.id.edit2);
    button=findViewById(R.id.button);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    return id == R.id.action_settings || super.onOptionsItemSelected(item);

}


public void click(View view) {

    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 <1 ; i++) {
                try {
                    JSONObject jsonObject;
                    jsonObject = response.getJSONObject(i);

                    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.i("title",Title);
                    Log.i("album",Album);

                    Toast.makeText(getApplicationContext(), Title, Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(), Album, Toast.LENGTH_SHORT).show();

                    note = new Note(Title, Album);
                    note.save();

                   // copydatabase();
                   // Toast.makeText(getApplicationContext(), "Rows Inserted into local storage too", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();

                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }

            }

           /* try {
                copydatabase();
            } catch (IOException e) {
                e.printStackTrace();
            }*/


        }



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


}

public void show(View view) {

        String myTitle = note.getTitle();
        String myAlbumid=note.getAlbumId();

    Log.e("title",myTitle);
    Log.e("album",myAlbumid);
}

 public void deletedatabase(View view) {

    boolean check=  MainActivity.this.deleteDatabase("notes.db");

    if(check){
        Toast.makeText(getApplicationContext(),"database deleted",Toast.LENGTH_SHORT).show();
    }

}

public void copydatabase(View view) throws IOException {

    File actualFile = null;

    actualFile= new File(new SugarDb(MainActivity.this).getDB().getPath()); //actual file
    File curentfile  = new File(actualFile.toString()); //new file generated
    Log.e("actualPath", actualFile.toString());


    File newFile = createTempFile("NewSugarAppFiles",".db",Environment.getExternalStorageDirectory());

    Log.e("newPath", newFile.toString());

    boolean yes=FileUtils.copyFile(curentfile,newFile);

    if(yes) {

        Log.e("result", "" + true);
        Toast.makeText(getApplicationContext(), "Database Copied to SD card", Toast.LENGTH_SHORT).show();
    }
  }
}

这里的 click 方法会调用 API 并将数据存储在本地数据库中,show 方法会检索存储的 data.Other 类 保持不变,我删除了 Recyclerview 以简化除了数据之外,还可以按照上述相同的方式从 Recyclerview 存储和检索数据。