Question

In: Computer Science

Create an app that stores a set of names. The UI should contain a EditText widget...

Create an app that stores a set of names. The UI should contain a EditText widget and two Buttons (one for adding a name and one for editing a name).   When the app starts up, the first name of the set is used to initialize the EditText widget. The app uses ViewPager so that the user can swipe left to visit the previous name in the set, or swipe right to visit the next name in the set, similar to how you can swipe left and right through crimes in the Criminal Intent app.

If the user types a new name in the EditText field and clicks the edit button, the name is updated in the app's list of names.

If the user types a new name in the EditText field and clicks the add button, the name is added to the end of the set.

You can store the names in an ArrayList of Strings and use the onCreate() method initialze the list so there is something to display when the app first starts up, if you wish.

Your app will not display a list, and therefore will not use RecyclerView. This is different than CriminalIntent and uses the ViewPager differently.

I am completely stumped and need help creating and finishing program. Spent hours trying to start and got nowhere.

Solutions

Expert Solution

Structure of Project :

MainActivity.java

package com.exmaple.viewpager;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import static com.exmaple.viewpager.MySharedPreference.SHARED_PREF;

public class MainActivity extends AppCompatActivity {

    private ArrayList<String> arrayList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Getting set of names stored in shared preference
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("STRING_SET",null);
        if(set==null) { //Shared Preference is empty (First time app open)
            arrayList.add("First Item");
        }
        else { // (Set is not empty)
            arrayList.addAll(set);
        }
        //Initializing viewpager and setting a custom adapter.
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new CustomPagerAdapter(this, arrayList));
    }
}

CustomPagerAdapter.java :

package com.exmaple.viewpager;
import android.content.Context;

import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import static com.exmaple.viewpager.MySharedPreference.SHARED_PREF;

//Custom Adapter class for Pager
class CustomPagerAdapter extends PagerAdapter {

    private ArrayList<String> arrayList;
    private Context mContext;

    public CustomPagerAdapter(Context context,ArrayList<String> arrayList) {
        this.arrayList = arrayList;
        mContext = context;
    }

    //Initiate Item
    @Override
    public Object instantiateItem(ViewGroup collection, final int position) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.content_main, collection, false);
        //Getting reference of edit text, add button and remove button from content_main.xml
        final EditText editText = layout.findViewById(R.id.edit_text);
        final Button editBtn = layout.findViewById(R.id.edit_button);
        Button addBtn = layout.findViewById(R.id.add_btn);

        editText.setText(arrayList.get(position).toString()); //Setting first value to edit text

        //Onclick for add button
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(editText.getText())) { //Edit Text is empty
                    Toast.makeText(mContext, "Please Enter Text.", Toast.LENGTH_SHORT).show();
                    return;
                }
                //Add item to array list and notify that data has been changed.
                    arrayList.add(position,editText.getText().toString());
                    notifyDataSetChanged();
                    saveToSharedPreference(); //Saving to shared preference
                Toast.makeText(mContext, "Item Added.", Toast.LENGTH_SHORT).show();
                }
        });

        //Onclick for edit button
        editBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(editText.getText())) { //Edit Text is empty
                    Toast.makeText(mContext, "Please Enter Text.", Toast.LENGTH_SHORT).show();
                    return;
                }
                //Removing array list item at this position and adding again at this position (Updating/Editing value)
                arrayList.remove(position);
                arrayList.add(position,editText.getText().toString());
                notifyDataSetChanged();
                saveToSharedPreference(); //Saving to shared preference
                Toast.makeText(mContext, "Item Updated.", Toast.LENGTH_SHORT).show();
            }
        });

        collection.addView(layout);
        return layout;
    }

    // This method save Set of names to SharedPreference so that when app closes added names are remain available
    public void saveToSharedPreference() {
        Set<String> set = new HashSet<String>();
        set.addAll(arrayList);
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(SHARED_PREF,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putStringSet("STRING_SET",set);
        editor.apply();
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return arrayList.get(position);
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }
}

MySharedPreference.java :

package com.exmaple.viewpager;

public class MySharedPreference {
    public static final String SHARED_PREF = "shared_pref";
}

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

content_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

   <EditText
       android:id="@+id/edit_text"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:textColor="@android:color/black"
       android:layout_margin="10dp"
       android:hint="Enter Text"
       android:padding="6dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="2">
        <Button
            android:id="@+id/edit_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="6dp"
            android:background="@color/colorPrimary"
            android:text="Edit Name"
            android:layout_margin="5dp"
            android:textColor="@android:color/white"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/add_btn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="6dp"
            android:background="@color/colorPrimary"
            android:text="Add Name"
            android:layout_margin="5dp"
            android:textColor="@android:color/white"
            android:layout_weight="1"/>

    </LinearLayout>

</LinearLayout>

build.gradle (Module :app) :

add the following dependency to use viewpager in your project :

implementation 'androidx.viewpager:viewpager:1.0.0'

Sample Output (Screenshots) :

When app launch for the first time the EditText will populate with text "First Item" on onCreate method. if pressed on EDIT NAME Button then item at that position will be change by new name and if click ed on ADD NAME Button then new item will be added at the end of list. more than one item can be added with the same name.


Related Solutions

"swift Create a SwiftUI project named DogBreeds based on the Contacts app. The app should be...
"swift Create a SwiftUI project named DogBreeds based on the Contacts app. The app should be named DogBreeds. The app will display 10 dog images and names in a lis"
Assignment Description: In this assignment, a script file should be created to contain a set a...
Assignment Description: In this assignment, a script file should be created to contain a set a SQL statements for the Pretty Prints Company to better manage their business. Use the database created for Pretty Prints in Assignment 2. Include the SQL statements to satisfy the following queries. The following queries should be included in the script: Create a view named Under_100. It consists of the item_id, title, artist, unit_price and order_qty for every print with a unit_price under 100 dollars....
IN C# lang Write a console app (review Module 5 for console app) that stores 3...
IN C# lang Write a console app (review Module 5 for console app) that stores 3 students test stores in 3 separate arrays as integers. Some did not not take all the tests, so they each have a their own length and we use separate arrays. Declare and initialize each array. Use meaningful names. Print each array as follows: Morgan 98, 72, 65 Bowie 15, 47, 35, 92, 94 Ananya 91, 68, 87, 75 Extra credit: Compute the average for...
Android Programming Create an app called GuessWho. The point of the app will to have the...
Android Programming Create an app called GuessWho. The point of the app will to have the user play a guessing game based on a displayed image. The user will be greeted with a screen that has an image of a person, four buttons and a next button. The four buttons should each have a different name on it. One of the names will be the actual name of the person in the image. Your guess who quiz should consist of...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It...
In C++, create a class to hold a set of strings called setTree. setTrees contain copies...
In C++, create a class to hold a set of strings called setTree. setTrees contain copies of the strings inserted so that the strings cannot be changed due to the fact that changing the strings inside the set could break the binary search tree. The strings are case sensitive. TreeSet implements the following: bool add(const string& s) -- add s to the set, if it's not already there. Return true if the set changed, false otherwise. void clear() -- remove...
Create an unsorted LIST class. Each list should be able to store 100 names.
Create an unsorted LIST class. Each list should be able to store 100 names.
Research the Windows and Mac app stores. Are these profitable for companies that publish to these...
Research the Windows and Mac app stores. Are these profitable for companies that publish to these stores? Why would a developer publish to one of these stores as opposed to providing a download from their website? The main post must be at least 200 words. Include any sources used
HTML Create a page of texts that uses inline elements. The page should contain a citation,...
HTML Create a page of texts that uses inline elements. The page should contain a citation, a term definition, a subscript, a superscript and some highlighted texts.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT