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"
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...
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.
Create a class named GameCharacter to define an object as follows: The class should contain class...
Create a class named GameCharacter to define an object as follows: The class should contain class variables for charName (a string to store the character's name), charType (a string to store the character's type), charHealth (an int to store the character's health rating), and charScore (an int to store the character's current score). Provide a constructor with parameters for the name, type, health and score and include code to assign the received values to the four class variables. Provide a...
Create a simple python app that allows the user to create a roster of students and...
Create a simple python app that allows the user to create a roster of students and their grade on CUS-1166. Moreover the app needs to calculate the average grade of students added to the roster. 1-To begin with, create a new file n the same working folder as part A (i.e. cus1166_lab1) and name it app.py. Moreover, create a subfolder and name it mymodules. 2-Within mymodules create the files __init__.py , models.py , math_utils.py . 3-In the models.py file define...
• The first tab should contain the simulation model. • The second tab should contain the...
• The first tab should contain the simulation model. • The second tab should contain the algebra of the optimization model. • The third tab should contain the optimization model and its solution using Excel Solver. Q1. Construct a spreadsheet simulation model for calculating profits for a company given that the demand for their new product is normally distributed with a mean of 6 and a standard deviation of 1. The selling price is $30/unit. The fixed cost is $50....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT