Favorite functions [Bagian 12]

In this section, the author will continue the discussion of adding preferred features to the project being worked on. If you followed the previous tutorial, you have managed to create a SQLite database where the database is internal and resides on each user’s smartphone.

For those of you new to this tutorial, you can view a project and try building it from the link below:

Alright, for this discussion the author will explain how to create a favorites function where the favorite data is stored in sqlite and displayed on Recycler view. Here are the stages:

1. Open the project, then click DetialStudio.java add the following script:

private DBDataSource db;private boolean favorite;

Declare the data type for DbDataSource as “db” and “favorite” with the type boolean.

Next add the following script onCreate :

//Set favorite dan Insert data dari API ke Sqlite databasedb = new DBDataSource(ContentStudio.this);db.open();//Cek favfavorite = db.isFavorite(Integer.valueOf(id));buttonf = (ImageView) findViewById(R.id.favbuttonwhite);if (favorite) {    buttonf.setImageResource(R.drawable.starred);}else {    buttonf.setImageResource(R.drawable.starwhite);}buttonf.setOnClickListener(new Button.OnClickListener() {    public void onClick(View v) {        Log.i("CEK", String.valueOf(favorite));        if (favorite) {            buttonf.setImageResource(R.drawable.starwhite);            db.deleteStudioMusik(Integer.valueOf(id));            favorite = false;        }        else {            buttonf.setImageResource(R.drawable.starred);            favorite = true;            if (db.insertStudioMusik(id,namaStudio,alamat,harga,gambar,                    jam,callSave,alatmusik,lastUpdate,ratingAlat,ratingRec,ratingTmpt,                    latitude,longitude)) {            }            else {            }        }    }});

Then add the above script which is useful to open the sqlite DBDataSource to DetailStudio.java, then call the isFavorite function and use the id which should be stored in a variable named favorite. Then create a branch to change the color of the preferred ImageView in DetailStudio.

Next, use the setOnClick event on the imageView variable “buttonf” which contains the preferred test command. If the color of the image view is R.drawable.starwhite, the function is called delete StudioMusic and delete the ID of the selected music studio and buy the value Favorite = false, otherwise the function will be carried out Insert StudioMusic and given parameters, namely the names of the fields that were defined in the previous DBHelper.

2. Create a favorites list view, open activity_favorites.xml then add the following script:

                                                                                                                                                            

And below for drawable / click_see_studio (choose the color of your choice):

               

3. Create a new layout for Recycler view by name “Activity_list_favorite.xml“And enter the following script:

                        

The above layout is used to accommodate the list that appears and to display / design the list itself, which was previously created in the activity_favorites.xml.

4. Next, create a new Java file named ListAdapter.java. Then add the following script:

public class ListAdapter extends RecyclerView.Adapter  {    private ArrayList> data_list ;    Context context;    public static String id;    public ListAdapter (Context context, ArrayList> data_list){        Log.d("DEBUG_", "Container ListAdapter");        this.data_list = data_list;        this.context = context;    }    @Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        Log.d("DEBUG_", "View Holder");        View v = LayoutInflater.from( parent.getContext()).inflate(R.layout.activity_favorites, parent, false);        return new ViewHolder(v);    }    @Override    public void onBindViewHolder(final ViewHolder holder, final int position) {        setAnimation(holder.itemView,position);        Log.d("DEBUG_", "Bind ViewHolder");        final HashMap data = data_list.get(position);        holder.namaStudio.setText(data.get("nama"));        holder.alamatStudio.setText(data.get("alamat"));        holder.hargaStudio.setText(data.get("harga"));        Picasso.with(context).load(data.get("gambar")).fit().into(holder.backimage);        Log.i("CEK_GAMBAR", "http://cloudofoasis.com/api/Ivan/slider_studio/"+data.get("gambar"));        holder.container.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View v){                DetailStudio.id = data.get("id");                DetailStudio.namaStudio = data.get("nama");                DetailStudio.alamat = data.get("alamat");                DetailStudio.harga = data.get("harga");                DetailStudio.gambar = data.get("gambar");                DetailStudio.jam = data.get("jam");                DetailStudio.callSave = data.get("call");                DetailStudio.alatmusik = data.get("alatmusik");                DetailStudio.lastUpdate = data.get("lastupdate");                DetailStudio.ratingAlat = data.get("ratingalatmusik");                DetailStudio.ratingRec = data.get("ratingrecording");                DetailStudio.ratingTmpt = data.get("ratingtempat");                DetailStudio.latitude = Double.parseDouble(data.get("latitude"));                DetailStudio.longitude = Double.parseDouble(data.get("longitude"));                Intent i = new Intent(context, DetailStudio.class);                context.startActivity(i);            }        });    }    @Override    public int getItemCount() {        return data_list.size();    }    public class ViewHolder extends RecyclerView.ViewHolder {        private final Button container;        private ImageView backimage, unfavbutton;        private TextView namaStudio, alamatStudio, hargaStudio;        public ViewHolder(View itemView) {            super(itemView);            container = (Button) itemView.findViewById(R.id.container);            backimage = (ImageView) itemView.findViewById(R.id.image_judul);            namaStudio = (TextView) itemView.findViewById(R.id.namastudiofav);            alamatStudio = (TextView) itemView.findViewById(R.id.alamatstudiofav);            hargaStudio = (TextView) itemView.findViewById(R.id.hargastudiofav);        }    }    private  int lastPosition=-1;    private void setAnimation(View viewToAnimate,int position){        //if the bound view wasn't previously displayed on screen,its animated        if(position>lastPosition){            ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);            anim.setDuration(new Random().nextInt(501));            // to make duration random            viewToAnimate.startAnimation(anim);            lastPosition=position;        }    }}

onCreateViewHolder is used to determine the view for the selected list design. activity_favorites.xml.

onBindViewHolder is used to set the data to be printed in the list Recycler view. In this class there is also a setOnClick event to send some data from sqlite to DetailActivity, as well as an Intent command.

ViewHolder serves to initialize the items in the Activity_favorites.xml list design

Then class setAnimation is the animation when the list is displayed.

5. Next open Favorites.java and add the following script:

public class Favorites extends AppCompatActivity {    RecyclerView list_item;    ArrayList> array_list;    Button button;    ProgressBar progressBar;    private DBDataSource db;    public static String id;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_list_favorites);        getSupportActionBar().setDisplayHomeAsUpEnabled(true);        getSupportActionBar().setHomeButtonEnabled(true);        db = new DBDataSource(Favorites.this);        db.open();        array_list = new ArrayList<>();        list_item = (RecyclerView) findViewById(R.id.list_item);        list_item.setLayoutManager(new LinearLayoutManager(this));        list_item.setItemAnimator(new DefaultItemAnimator());        progressBar = (ProgressBar) findViewById(R.id.list_item_progress);        button = (Button) findViewById(R.id.refresh_list_item);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                getData();            }        });        getData();    }    public void getData() {        list_item.setVisibility(View.INVISIBLE);        button.setVisibility(View.INVISIBLE);        progressBar.setVisibility(View.VISIBLE);        Log.d("DEBUG_", "Set data to Adapter");        for (int i = 0; i < db.getStudioMusik().size(); i++) {            HashMap data = new HashMap<>();            data.put("id", String.valueOf(db.getStudioMusik().get(i).getId()));            data.put("nama", db.getStudioMusik().get(i).getNama());            data.put("alamat", db.getStudioMusik().get(i).getAlamat());            data.put("harga", db.getStudioMusik().get(i).getHarga());            data.put("gambar", db.getStudioMusik().get(i).getGambar());            data.put("jam", db.getStudioMusik().get(i).getJam());            data.put("calllite", db.getStudioMusik().get(i).getCall());            data.put("alatmusik", db.getStudioMusik().get(i).getAlatmusik());            data.put("lastupdate", db.getStudioMusik().get(i).getLastupdate());            data.put("ratingalatmusik", db.getStudioMusik().get(i).getRatingalat());            data.put("ratingrecording", db.getStudioMusik().get(i).getRatingrecording());            data.put("ratingtempat", db.getStudioMusik().get(i).getRatingtempat());            data.put("latitude", db.getStudioMusik().get(i).getLatitude());            data.put("longitude", db.getStudioMusik().get(i).getLongitude());            array_list.add(data);        }        progressBar.setVisibility(View.INVISIBLE);        list_item.setVisibility(View.VISIBLE);        ListAdapter adapter = new ListAdapter(Favorites.this, array_list);        list_item.setAdapter(adapter);    }    @Override    public void onBackPressed() {        Intent intent = new Intent(this, MainActivity.class);        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        startActivity(intent);        finish();    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        switch (item.getItemId()) {            case android.R.id.home:                // app icon in action bar clicked; go home                finish();            default:                return super.onOptionsItemSelected(item);        }    }}

The above script for onCreate contains several object declarations for array_list to hold the data received from the adapter, then initializes the list_item variable as Recyclerview and also a progressBar variable that uses the onClick event that executes the getData () method.

The content of the getData () method is to put the required data from SQLite into the adapter and store it in the previously defined array_list.

6. Here are some previews of the layouts created:

activity_favorites.xml

Activity_Favorites

Activity_list_favorites

Activity_list_favorites

7. In MainActivity.java, add the following script in onCreate:

   ImageView favBtn = (ImageView) findViewById(R.id.favBtn);    favBtn.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View v) {                Intent i = new Intent(MainActivity.this, Favorites.class);                startActivity(i);        }    });}

The above script is added to initialize the image view with the ID favBtn and receives a setOnClick event that contains the intent command or changes to the Favorites.class layout.

8. The final step is to run the project, here is the output display:

Studio ridge favorite view

Soundgraph Studio favorites view

The above is an example for 2 studios that have been assigned a favorite, then the star symbol will automatically turn red.

Show recycler list view

The above display is a Recyclerview favorite list display of 2 music studios that have favorites assigned. Then when the button “Show this studio” is clicked, the studio details will be shown again.

That’s the whole tutorial on building GIS applications on Android Studio, hopefully it can be useful for loyal readers Inwepo. If you have any questions about the tutorial, feel free to leave a comment on any post. Thanks very much…






Leave a Reply

Your email address will not be published.