androidandroid-sqlitesugarorm

How to retrieve data from local sqlite sugar database android


I have been developing an application which is storing data in the local sqlite database using sugar ORM, and publishing it in the listview also, so my task is to publish the listview from direct data which comes from json when the internet connection is available but if the connection is not available then I have to retrieve the already saved data inside the database and populate in the listview, i have been able to download and saved the data but when the net is not available then i have to retrieve it inside getdatafromlocal method which is not happening

MainActivity.java file

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 file

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 file

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




   }

  }
}

Solution

  • After few trials and errors , i have been able to retrieve the data which was stored in the local database through Sugar ORM, I changed my MainActivity a bit to get the desired results

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

    Here click method would call an API and store the data in the local database and show method would retrieve the stored data.Other classes remain same, I have dropped Recyclerview to simplify things but the data can be stored and retrieved from the Recyclerview also in the same manner as written above.