Question: I need help with the following program using Java with Android Studio. In the current ContentProvider Example, each contact has three fields: Name, Email, and

I need help with the following program using Java with Android Studio.

In the current ContentProvider Example, each contact has three fields: Name, Email, and Phone Number. Add two new fields: address and birthday. Update both ContentProvider and ContentProviderUser to reflect the changes.

In the current ContentProviderUser Example, the ADD NEW CONTACT and UPDATE buttons were not fully implemented, I temporarily used random data. Instead of using random data, you need to design and implement these two buttons use the knowledge you learned. When the user clicks the ADD NEW CONTACT, a dialog box/new text fields appears on screen for users input. When the user enters an ID of a contact to update, a dialog box/new text fields appears on screen for users input. User can Edit the contact or Cancel. The contact list should be updated accordingly

Here are the ContentProvider and ContentProvider programs I have so far:

ContentProvider Example:

strings.xml

<resources> <string name="app_name">ContentProvider Examplestring> <string name="menu_settings">Settingsstring> <string name="name">Enter Namestring> <string name="email">Enter Emailstring> <string name="contact">Enter Phone Numberstring> <string name="add">Add Contactstring> <string name="save_data">New Contactstring> <string name="show">Show Contactsstring> resources>

AndriodManifest.xml

xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="edu.ucmo.cs.contentproviderexample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> intent-filter> activity> <provider android:name="edu.ucmo.cs.contentproviderexample.Custom_ContentProvider" android:authorities="edu.ucmo.cs.contentproviderexample.Custom_ContentProvider" android:exported="true" android:multiprocess="true" > provider> application> manifest>

activity_main.xml

xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:fillViewport="true" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" android:padding="5dp" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:gravity="center" android:padding="10dp" android:text="@string/save_data" android:textColor="#F44336" android:textSize="20sp" android:textStyle="bold" /> <EditText android:id="@+id/txtName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/name" android:inputType="textCapWords" android:padding="10dp" /> <EditText android:id="@+id/txtEmail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/email" android:inputType="textEmailAddress" android:padding="10dp" /> <EditText android:id="@+id/txtContact" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/contact" android:inputType="number" android:padding="10dp" /> <Button android:id="@+id/btnAdd" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="@string/add" /> <Button android:id="@+id/btnShow" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="@string/show" /> <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="10dp" android:textColor="#000000" android:textSize="15sp" /> LinearLayout> ScrollView>

Custom_ContentProvider.java

package edu.ucmo.cs.contentproviderexample; import java.util.HashMap; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class Custom_ContentProvider extends ContentProvider { static final String PROVIDER_NAME = "edu.ucmo.cs.contentproviderexample.Custom_ContentProvider";// Provider // name static final String URL = "content://" + PROVIDER_NAME + "/contacts";// Provider // url static final Uri CONTENT_URI = Uri.parse(URL);// Content Uri in URI format // All fields of database static final String id = "id"; static final String name = "name"; static final String email = "email"; static final String number = "number"; // Uri code static final int uriCode = 1; static final UriMatcher uriMatcher; private static HashMap values; static { // Match the uri code to provider name uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "contacts", uriCode); uriMatcher.addURI(PROVIDER_NAME, "contacts/*", uriCode); } // detele uri method @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0;// Count to tell how many rows deleted switch (uriMatcher.match(uri)) { case uriCode: count = db.delete(TABLE_NAME, selection, selectionArgs); break; default: count = 0; throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } // return type of content provider @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case uriCode: return "vnd.android.cursor.dir/contacts"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } // Insert method @Override public Uri insert(Uri uri, ContentValues values) { long rowID = db.insert(TABLE_NAME, "", values);// Insert data into // database // If row id is greater than 0 then notify content provider if (rowID > 0) { Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(_uri, null); return _uri; } throw new SQLException("Failed to add a record into " + uri); } @Override public boolean onCreate() { Context context = getContext(); DatabaseHelper dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase(); if (db != null) { return true; } return false; } // Read all data method @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(TABLE_NAME); switch (uriMatcher.match(uri)) { case uriCode: qb.setProjectionMap(values); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } if (sortOrder == null || sortOrder == "") { sortOrder = name; } Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } // Update data @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0;// Count to tell number of rows updated switch (uriMatcher.match(uri)) { case uriCode: count = db.update(TABLE_NAME, values, selection, selectionArgs); break; default: count = 0; throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /** SqlLite Database **/ private SQLiteDatabase db; static final String DATABASE_NAME = "ContentProvider_Database";// Database // name static final String TABLE_NAME = "User_Details";// Table Name static final int DATABASE_VERSION = 1;// Database Version static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, " + name + " TEXT NOT NULL, " + email + " TEXT NOT NULL, " + number + " TEXT NOT NULL" + " );"; // Create table query private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_DB_TABLE);// Create table } // On database version upgrade create new table @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } } }

MainActivity.java

package edu.ucmo.cs.contentproviderexample; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static EditText name, email, number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = (EditText) findViewById(R.id.txtName); email = (EditText) findViewById(R.id.txtEmail); number = (EditText) findViewById(R.id.txtContact); findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // Get all text fields into string String getName = name.getText().toString(); String getEmail = email.getText().toString(); String getNumber = number.getText().toString(); // Check if all fields are not null if (!getName.equals("") && getName.length() != 0 && !getEmail.equals("") && getEmail.length() != 0 && !getNumber.equals("") && getNumber.length() != 0) { onClickAddData(getName, getEmail, getNumber);// Add data // empty all fields name.setText(""); email.setText(""); number.setText(""); } // else show toast else Toast.makeText(MainActivity.this, "Please fill all details.", Toast.LENGTH_SHORT) .show(); } }); findViewById(R.id.btnShow).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { TextView resultView = (TextView) findViewById(R.id.result); Cursor cursor = getContentResolver().query( Custom_ContentProvider.CONTENT_URI, null, null, null, null);// Get cursor // Check if it is null or not if (cursor != null && cursor.moveToFirst()) { StringBuilder result = new StringBuilder(); // Loop to all items while (!cursor.isAfterLast()) { // Add data to string builder result.append("Id - " + cursor.getString(cursor.getColumnIndex("id")) + " Name - " + cursor.getString(cursor .getColumnIndex("name")) + " Email - " + cursor.getString(cursor .getColumnIndex("email")) + " Phone - " + cursor.getString(cursor .getColumnIndex("number")) + " "); cursor.moveToNext(); } resultView.setText(result);// finally set string builder to // textview } else { // if cursor is null then set data empty resultView.setText("No Contact."); } } }); } // Add data method private void onClickAddData(String name, String email, String number) { ContentValues values = new ContentValues();// Content values to add data values.put(Custom_ContentProvider.name, name); values.put(Custom_ContentProvider.email, email); values.put(Custom_ContentProvider.number, number); Uri uri = getContentResolver().insert( Custom_ContentProvider.CONTENT_URI, values);// Insert data to // content provider Toast.makeText(getBaseContext(), "New Data Inserted.", Toast.LENGTH_LONG).show(); } }

ContentProviderUser Example:

strings.xml

<resources> <string name="app_name">ContentProviderUser Examplestring> <string name="hello_world">Hello world!string> <string name="menu_settings">Settingsstring> <string name="show_data">Show Contactsstring> <string name="id">Enter IDstring> <string name="update">Updatestring> <string name="delete">Deletestring> <string name="update_delete">Enter ID to Update/Delete Contactstring> <string name="insert">Add New Contactstring> resources>

activity_main.xml

xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:fillViewport="true" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp" > <Button android:id="@+id/btnRetrieve" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="@string/show_data" /> <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:clickable="false" android:padding="5dp" android:textColor="#000000" android:textSize="15sp" /> <Button android:id="@+id/btnInsert" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="@string/insert" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:gravity="center" android:padding="10dp" android:text="@string/update_delete" android:textColor="#F44336" android:textSize="20sp" android:textStyle="bold" /> <EditText android:id="@+id/id" android:layout_width="fill_parent" android:layout_height="wrap_content" android:focusableInTouchMode="true" android:hint="@string/id" android:inputType="number" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btnUpdate" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:padding="5dp" android:text="@string/update" /> <Button android:id="@+id/btnDelete" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="1" android:padding="5dp" android:text="@string/delete" /> LinearLayout> LinearLayout> ScrollView>

Random_Data.java

package edu.ucmo.cs.contentprovideruserexample; /** * Created by Fei on 2/27/2018. */ public class Random_Data { /** Strings array to insert/update data in Content Provider **/ public static final String[] Name = { "Moira", "Mercy", "Ana", "Reaper", "Lucio", "Reinhardt" }; public static final String[] Email = { "Moira@bllizard.com", "Mercy@bllizard.com", "Ana@bllizard.com", "Reaper@bllizard.com", "Lucio@bllizard.com", "Reinhardt@bllizard.com" }; public static final String[] Number = { "6605432547", "66054355412", "6605436359", "6605438432", "6605436357", "6605438753" }; }

MainActivity.java

package edu.ucmo.cs.contentprovideruserexample; import java.util.Random; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks, OnClickListener { private static TextView resultView; private static EditText id; private static Button retrieve, update, delete, insert; private static CursorLoader cursorLoader; private static final String uri = "content://edu.ucmo.cs.contentproviderexample.Custom_ContentProvider/contacts";// Content URI @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Find Ids resultView = (TextView) findViewById(R.id.result); id = (EditText) findViewById(R.id.id); retrieve = (Button) findViewById(R.id.btnRetrieve); update = (Button) findViewById(R.id.btnUpdate); delete = (Button) findViewById(R.id.btnDelete); insert = (Button) findViewById(R.id.btnInsert); // Implement click listener retrieve.setOnClickListener(this); update.setOnClickListener(this); delete.setOnClickListener(this); insert.setOnClickListener(this); } // On click call representative methods @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnRetrieve: onClickDisplayData();// Fetch data break; case R.id.btnUpdate: // Update data according to Id String getId = id.getText().toString(); if (!getId.equals("") && getId.length() != 0) updateData(new String[] { getId }); else Toast.makeText(MainActivity.this, "ID is empty.", Toast.LENGTH_SHORT).show(); break; case R.id.btnDelete: // Delete data according to Id String getId_ = id.getText().toString(); if (!getId_.equals("") && getId_.length() != 0) deleteData(new String[] { getId_ }); else Toast.makeText(MainActivity.this, "ID is empty.", Toast.LENGTH_SHORT).show(); break; case R.id.btnInsert: // Insert data insertData(); break; } } private void onClickDisplayData() { // Initate loader manager getSupportLoaderManager().initLoader(1, null, this); } @Override public Loader onCreateLoader(int arg0, Bundle arg1) { try { cursorLoader = new CursorLoader(this, Uri.parse(uri), null, null, null, null);// Get cursor loader from URI } catch (NullPointerException e) { // if exception occurs toast occurs Toast.makeText( MainActivity.this, "There is no app found corresponding to your content provider.", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, "Error fetching data. Try again.", Toast.LENGTH_SHORT) .show(); e.printStackTrace(); } return cursorLoader; } @Override public void onLoadFinished(Loader arg0, Cursor cursor) { // First check if cursor is not null if (cursor != null && cursor.moveToFirst()) { StringBuilder result = new StringBuilder(); // Now loop to all items and append it to string builder while (!cursor.isAfterLast()) { result.append("Id - " + cursor.getString(cursor.getColumnIndex("id")) + " Name - " + cursor.getString(cursor.getColumnIndex("name")) + " Email - " + cursor.getString(cursor.getColumnIndex("email")) + " Phone Number - " + cursor.getString(cursor.getColumnIndex("number")) + " "); cursor.moveToNext(); } resultView.setText(result);// Finally set string builder to textview } else { // If cursor is null then display toast and set empty data. resultView.setText("No Contact."); Toast.makeText( MainActivity.this, "No app corresponding to your provider or there is null data.", Toast.LENGTH_LONG).show(); } } @Override public void onLoaderReset(Loader arg0) { } // Random int value generator method between 0-5 private int RandomInt() { Random random = new Random(); int randomValue = random.nextInt(5); return randomValue; } // Update data method private void updateData(String[] id) { Cursor cursor = getContentResolver().query(Uri.parse(uri), null, null, null, null);// Get cursor from Uri // If cursor is not null then update data else show toast if (cursor != null) { int randomValue = RandomInt();// Get random integer ContentValues values = new ContentValues();// Content values to // insert data values.put("name", Random_Data.Name[randomValue]);// add data from // RandomData // class values.put("email", Random_Data.Email[randomValue]); values.put("number", Random_Data.Number[randomValue]); int count = getContentResolver().update(Uri.parse(uri), values, "id = ?", id);// now update provider using ID // If count is not 0 then row is updated else no row is updated if (count != 0) Toast.makeText(MainActivity.this, "Row updated", Toast.LENGTH_LONG).show(); else Toast.makeText( MainActivity.this, "No row to update or the id you pass is not present in database.", Toast.LENGTH_LONG).show(); } else { Toast.makeText( MainActivity.this, "No app corresponding to your provider or there is null data.", Toast.LENGTH_LONG).show(); } } // Delete data private void deleteData(String[] id) { // First get the cursor then check if it is null Cursor cursor = getContentResolver().query(Uri.parse(uri), null, null, null, null); if (cursor != null) { int count = getContentResolver().delete(Uri.parse(uri), "id = ? ", id);// Delete row according to id if (count != 0) Toast.makeText(MainActivity.this, "Row deleted", Toast.LENGTH_LONG).show(); else Toast.makeText( MainActivity.this, "No row to delete or the id you pass is not exist in database.", Toast.LENGTH_LONG).show(); } else { Toast.makeText( MainActivity.this, "No app corresponding to your provider or there is null data.", Toast.LENGTH_LONG).show(); } } // Insert random data private void insertData() { Cursor cursor = getContentResolver().query(Uri.parse(uri), null, null, null, null); // First check if cursor is null or not if (cursor != null) { int randomValue = RandomInt(); ContentValues values = new ContentValues(); values.put("name", Random_Data.Name[randomValue]); values.put("email", Random_Data.Email[randomValue]); values.put("number", Random_Data.Number[randomValue]); Uri uri_ = getContentResolver().insert(Uri.parse(uri), values); Toast.makeText(MainActivity.this, "Contact Inserted.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "No app corresponding to your provider.", Toast.LENGTH_LONG).show(); } } @Override public void onDestroy() { super.onDestroy(); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!