SlideShare a Scribd company logo
Content Providers’ in
Android Application
Sample Project Coursework
Wael Almadhoun
Background
Content providers in Android provide access to data that is shared between different apps. The
contentprovideristhe ownerof the data,but providesaninterfacetoallow activitiesfromother
applications in Android to access the data.
The intention istoadd; You can populate the contentwithdataaboutEuropeanUnion
countries,orGulf CooperationCouncil countries,AfricanUnion,etc.For eachcountry you
shouldstore itscapital city,population,areainsquare kilometres,anditsofficial language or
languages,andanyotherdata you like..
The Solution:
1. FirstApp:The producerapplicationisdesignedtoconstructthe SQLite database and
the data entryscreen.
2. SecondApp:The consumerapplicationisdesignedtoview the datastoredbythe
firstapp (aslist) the data can be editedalso.
The followingscreensandJavaclasses includedinthe ProducerApplication:
1. Classeswithin com.example.contentproviderproducerpackage
 MainActivity
 CountryProvider
2. ClasseswithinDBSQLin com.example.contentproviderproducer package
 DBCountry
 CountryDatabaseHelper
3. Activities
 activity_main.xml
Introduction
The ApplicationUserExperience.
 Simple userinterfacetoenterthe followingrequireddata,
Selectthe " union", " capital ", " population","area", " language" and" other”
Activity:
activity_main
Input form
ContentValuesMainActivityClass
SQLite
FirstApp:Producer
UTHORITY = "com.example.contentproviderproducer.countrycrovider";
CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + STUDENT_TABLE);
SecondApp:
Consumer
Activity:
row_country
List view
(Card Widget)
Show Details
(Flip View)
Activity:
activity_main
Add Form
The Activities
The below screenshots taken from my Mobile (samsung galaxy s6 – android lollipop)
FirstApp – Addnewcountryentry:
SecondApp – ViewCountries:
SeconApp– Update country item:
The Code for First Application(Producer)
1. The manifestfile
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contentproviderproducer" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:authorities="com.example.contentproviderproducer.countrycrovider"
android:name=".CountryProvider"
android:exported="true"></provider>
</application>
</manifest>
2. Main Activity
3. package com.example.contentproviderproducer;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.contentproviderproducer.DBSQL.DBCountry;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// declare new instance of the database and open the connection
final DBCountry db = new DBCountry(this);
db.open();
final EditText name = (EditText)findViewById(R.id.name);
final EditText population =
(EditText)findViewById(R.id.population);
final EditText area = (EditText)findViewById(R.id.area);
final EditText capital = (EditText)findViewById(R.id.capital);
final EditText language = (EditText)findViewById(R.id.language);
final EditText other = (EditText)findViewById(R.id.other);
final Spinner union = (Spinner)findViewById(R.id.union);
Button buttonsave=(Button)findViewById(R.id.insert);
// add items values taken from the input screen to contentValues;
buttonsave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put("name", ""+name.getText().toString());
values.put("capital", ""+capital.getText().toString());
values.put("population",
""+population.getText().toString());
values.put("area", ""+area.getText().toString());
values.put("language", ""+language.getText().toString());
values.put("count_union",
""+union.getSelectedItem().toString());
values.put("other", ""+other.getText().toString());
// insert the loaded values into database using the DB helper
insert procedure
db.insert("Country", values);
// preview a toast message to user confirming the new entry
Toast.makeText(MainActivity.this, "New Country Added!",
Toast.LENGTH_SHORT).show();
}
});
}
}
4. CountryProvider
package com.example.contentproviderproducer;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import com.example.contentproviderproducer.DBSQL.DBCountry;
/**
* class CountryProvider as Content Provide and uri.
*/
public class CountryProvider extends ContentProvider{
public static final String AUTHORITY =
"com.example.contentproviderproducer.countrycrovider";
public static final String STUDENT_TABLE = "Country";
public static final int CHOICE_TABLE = 1;
public static final int CHOICE_TABLE_ROW = 2;
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
DBCountry db;
@Override
public boolean onCreate() {
uriMatcher.addURI(AUTHORITY,STUDENT_TABLE,CHOICE_TABLE);
uriMatcher.addURI(AUTHORITY,STUDENT_TABLE+"/#",CHOICE_TABLE_ROW);
db = new DBCountry(getContext());
db.open();
return (db==null)? false:true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
int choice = uriMatcher.match(uri);
Cursor c = null;
if(choice == CHOICE_TABLE){
c =
db.query(STUDENT_TABLE,projection,selection,selectionArgs,sortOrder);
getContext().getContentResolver().notifyChange(uri,null);
}
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
int choice = uriMatcher.match(uri);
long id = -1;
if(choice == CHOICE_TABLE){
id = db.insert(STUDENT_TABLE,values);
getContext().getContentResolver().notifyChange(uri,null);
}
return Uri.parse("content://"+AUTHORITY+"/"+STUDENT_TABLE+"/"+id);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int choice = uriMatcher.match(uri);
int count = -1;
if(choice == CHOICE_TABLE){
count = db.delete(STUDENT_TABLE,selection,selectionArgs);
}
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[]
selectionArgs) {
int choice = uriMatcher.match(uri);
int rowsAffected = -1;
if(choice == CHOICE_TABLE){
rowsAffected =
db.update(STUDENT_TABLE,values,selection,selectionArgs);
}
return rowsAffected;
}
@Override
public String getType(Uri uri) {
return null;
}
}
5. DBSQL. DBCountry
6. package com.example.contentproviderproducer.DBSQL;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
/**
* Define the databse helper to perform CRUD actions on the deatabase.
* I used insert prcedure in this app
*/
public class DBCountry {
CountryDatabaseHelper countryDatabaseHelper;
SQLiteDatabase db;
Context context;
public DBCountry(Context context) {
this.context = context;
countryDatabaseHelper = new CountryDatabaseHelper(context,
"dbCountry", null, 1);
}
public void open() {
db = countryDatabaseHelper.getWritableDatabase();
}
public void close() {
countryDatabaseHelper.close();
}
public void beginTransaction() {
db.beginTransaction();
}
public void endTransaction() {
db.endTransaction();
}
public void setTransactionSuccessful() {
db.setTransactionSuccessful();
}
public long insert(String tableName, ContentValues values) {
return db.insert(tableName, null, values);
}
public Cursor query(String tableName, String[] projection, String
selection, String[] selectionArgs, String sortOrder) {
return db.query(tableName, projection, selection, selectionArgs,
null, null, sortOrder);
}
public int delete(String tableName , String whereClause , String[]
args){
return db.delete(tableName, whereClause, args);
}
public int update(String tableName ,ContentValues values, String
whereClause , String[] args){
return db.update(tableName, values, whereClause, args);
}
public void insertWithPerformance(String query,String... values){
SQLiteStatement stmt = db.compileStatement(query);
beginTransaction();
stmt.bindString(1,values[0]);
stmt.bindString(2,values[1]);
stmt.execute();
stmt.clearBindings();
setTransactionSuccessful();
endTransaction();
}
}
7. DBSQL. CountryDatabaseHelper
package com.example.contentproviderproducer.DBSQL;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Create the database table required to store the app data - Country.
* using SQLite
*/
public class CountryDatabaseHelper extends SQLiteOpenHelper{
public CountryDatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create Table Country(_id INTEGER PRIMARY KEY AUTOINCREMENT
," +
" name TEXT NOT NULL ," +
" capital TEXT ," +
" population TEXT ," +
" area TEXT ," +
" language TEXT ," +
" count_union TEXT ," +
" other TEXT )");
}
// in case of updating the app, the table will be recreated
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE Country IF EXIST");
onCreate(db);
}
}
8. Activity_main.xml
<LinearLayout 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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical"
>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Union"
android:ems="10"
android:id="@+id/union"
android:entries="@array/unionArray" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="name"
android:ems="10"
android:id="@+id/name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="capital"
android:ems="10"
android:id="@+id/capital" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="population"
android:ems="10"
android:id="@+id/population" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="area"
android:ems="10"
android:id="@+id/area" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="language"
android:ems="10"
android:id="@+id/language" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="other"
android:ems="10"
android:id="@+id/other" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert"
android:id="@+id/insert" />
</LinearLayout>
9. string.xml
<resources>
<string name="app_name">ContentProviderProducer</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string-array name="unionArray">
<item>European Union</item>
<item>Gulf Cooperation Council</item>
<item>African Union</item>
</string-array>
</resources>
The Code for Second Application(Consumer)
1. The manifestfile
2. <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contentproviderconsumer" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>
3. MainActivity
package com.example.contentproviderconsumer;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ViewFlipper;
public class MainActivity extends Activity implements
LoaderManager.LoaderCallbacks<Cursor> {
ListView lst;
ViewFlipper flipper;
CountryCursorAdapter countryCursorAdapter;
int ref = 1;
public static final String AUTHORITY =
"com.example.contentproviderproducer.countrycrovider";
public static final String STUDENT_TABLE = "Country";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY +
"/" + STUDENT_TABLE);
private Button buttonsave;
EditText name, population, area, capital, language, other;
Spinner union;
ContentResolver contentResolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flipper = (ViewFlipper) findViewById(R.id.viewFlipper);
name = (EditText) findViewById(R.id.name);
population = (EditText) findViewById(R.id.population);
area = (EditText) findViewById(R.id.area);
capital = (EditText) findViewById(R.id.capital);
language = (EditText) findViewById(R.id.language);
other = (EditText) findViewById(R.id.other);
union = (Spinner)findViewById(R.id.union);
buttonsave = (Button) findViewById(R.id.insert);
contentResolver = getContentResolver();
lst = (ListView) findViewById(R.id.listView);
getLoaderManager().initLoader(ref, null, this);
ref++;
btnAddClick();
}
public void btnAddClick(){
buttonsave.setText("Save insert");
buttonsave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put("name", "" + name.getText().toString());
values.put("capital", "" + capital.getText().toString());
values.put("population", "" + population.getText().toString());
values.put("area", "" + area.getText().toString());
values.put("language", "" + language.getText().toString());
values.put("other", "" + other.getText().toString());
values.put("count_union",
""+union.getSelectedItem().toString());
Uri uri = contentResolver.insert(CONTENT_URI, values);
// countryCursorAdapter.
//contentResolver
Toast.makeText(v.getContext(), uri.toString(),
Toast.LENGTH_SHORT).show();
getLoaderManager().initLoader(ref, null, MainActivity.this);
countryCursorAdapter.notifyDataSetChanged();
ref++;
name.setText("");
population.setText("");
area.setText("");
capital.setText("");
language.setText("");
other.setText("");
//----------------------------------
try {
flipper.showPrevious();
} catch (Exception w) {
flipper.showNext();
}
// ---------------------------------------
}
});
}
@Override
public Loader onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, CONTENT_URI, null, null, null, null);
}
@Override
public void onLoadFinished(Loader loader, Cursor data) {
countryCursorAdapter = new CountryCursorAdapter(this, data, 0);
lst.setAdapter(countryCursorAdapter);
countryCursorAdapter.setCutdorListLisiner(new
CountryCursorAdapter.CutdorListLisiner() {
@Override
public void OnClickCountryListener(Context context, final String
_id, String s_name, String s_population, String s_area, String s_capital,
String s_language) {
//populate the text values into fields
name.setText(s_name);
population.setText(s_population);
area.setText(s_area);
capital.setText(s_capital);
language.setText(s_language);
flipper.showNext();
buttonsave.setText("Save Update");
buttonsave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put("name", "" + name.getText().toString());
values.put("capital", "" +
capital.getText().toString());
values.put("population", "" +
population.getText().toString());
values.put("area", "" + area.getText().toString());
values.put("language", "" +
language.getText().toString());
values.put("count_union",
""+union.getSelectedItem().toString());
// countryCursorAdapter.swapCursor()
contentResolver.update(CONTENT_URI,values,"_id=?",new
String[]{""+_id});
getLoaderManager().initLoader(ref, null,
MainActivity.this);
countryCursorAdapter.notifyDataSetChanged();
ref++;
//----------------------------------
try {
flipper.showPrevious();
} catch (Exception w) {
flipper.showNext();
}
// ---------------------------------------
}
});
}
});
}
@Override
public void onLoaderReset(Loader loader) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.add);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
int id = item.getItemId();
if (id == R.id.add) {
btnAddClick();
try {
flipper.showNext();
} catch (Exception w) {
flipper.showPrevious();
}
return true;
} else {
try {
flipper.showPrevious();
} catch (Exception w) {
flipper.showNext();
}
return true;
}
}
}
4. CountryCursorAdapter
package com.example.contentproviderconsumer;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class CountryCursorAdapter extends CursorAdapter {
public CountryCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
CutdorListLisiner cutdorListLisiner;
public void setCutdorListLisiner(CutdorListLisiner cutdorListLisiner) {
this.cutdorListLisiner = cutdorListLisiner;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.row_country,
parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
@Override
public void bindView(View view, final Context context, Cursor cursor) {
// Find fields to populate in inflated template
final TextView name = (TextView)view.findViewById(R.id.name);
final TextView population =
(TextView)view.findViewById(R.id.population);
final TextView area = (TextView)view.findViewById(R.id.area);
final TextView capital = (TextView)view.findViewById(R.id.capital);
final TextView language = (TextView)view.findViewById(R.id.language);
final TextView union = (TextView)view.findViewById(R.id.union);
final RelativeLayout rel_item =
(RelativeLayout)view.findViewById(R.id.rel_item);
final String _id =
cursor.getString(cursor.getColumnIndexOrThrow("_id"));
final String s_name =
cursor.getString(cursor.getColumnIndexOrThrow("name"));
final String s_population =
cursor.getString(cursor.getColumnIndexOrThrow("population"));
final String s_area =
cursor.getString(cursor.getColumnIndexOrThrow("area"));
final String s_capital =
cursor.getString(cursor.getColumnIndexOrThrow("capital"));
final String s_language =
cursor.getString(cursor.getColumnIndexOrThrow("language"));
final String s_union =
cursor.getString(cursor.getColumnIndexOrThrow("count_union"));
rel_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cutdorListLisiner.OnClickCountryListener(context,_id,s_name,s_population,s_a
rea,s_capital,s_language);
}
});
// Populate fields with extracted properties
name.setText(s_name);
population.setText(s_population);
area.setText(s_area);
capital.setText("("+s_capital+")");
language.setText(s_language);
union.setText(s_union);
}
public interface CutdorListLisiner{
public void OnClickCountryListener(Context context, String
_id,String s_name,String s_population,String s_area,String s_capital,String
s_language);
}
}
5. activity_main.xml
<LinearLayout 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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical"
>
<ViewFlipper
android:id="@+id/viewFlipper"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Union"
android:ems="10"
android:id="@+id/union"
android:entries="@array/unionArray" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="name"
android:ems="10"
android:id="@+id/name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="capital"
android:ems="10"
android:id="@+id/capital" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="population"
android:ems="10"
android:id="@+id/population" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="area"
android:ems="10"
android:id="@+id/area" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="language"
android:ems="10"
android:id="@+id/language" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="other"
android:ems="10"
android:id="@+id/other" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert"
android:id="@+id/insert" />
</LinearLayout>
</ViewFlipper>
</LinearLayout>
6. row_country.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:id="@+id/rel_item"
android:padding="4dp"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
app:cardBackgroundColor="#ccc"
android:layout_height="wrap_content"
android:background="#ccc"
app:cardCornerRadius="4dp"
app:cardElevation="3dp"
app:cardMaxElevation="3dp"
app:cardPreventCornerOverlap="false"
android:padding="8dp"
android:layout_margin="8dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/view">
<RelativeLayout
android:layout_width="match_parent"
android:padding="4dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="name"
android:layout_marginBottom="4dp"
android:id="@+id/name"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="capital"
android:id="@+id/capital"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="population"
android:gravity="center"
android:id="@+id/population"
android:layout_alignBottom="@+id/imageView2"
android:layout_toEndOf="@+id/imageView2"
android:layout_alignTop="@+id/imageView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="area"
android:id="@+id/area"
android:gravity="center"
android:layout_alignBottom="@+id/imageView"
android:layout_toEndOf="@+id/imageView"
android:layout_below="@+id/name" />
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="@+id/imageView"
android:src="@drawable/ic_area"
android:layout_below="@+id/name"
android:layout_alignParentStart="true" />
<ImageView
android:layout_marginLeft="20dp"
android:layout_width="25dp"
android:layout_height="25dp"
android:id="@+id/imageView2"
android:src="@drawable/ic_people"
android:layout_below="@+id/name"
android:layout_toEndOf="@+id/area" />
<ImageView
android:layout_marginLeft="20dp"
android:layout_width="15dp"
android:layout_height="15dp"
android:id="@+id/imageView3"
android:src="@drawable/ic_language"
android:layout_alignBottom="@+id/language"
android:layout_toStartOf="@+id/language" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="union"
android:id="@+id/union"
android:layout_marginTop="8dp"
android:layout_alignParentStart="true"
android:layout_below="@+id/language" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="language"
android:layout_marginTop="8dp"
android:id="@+id/language"
android:layout_below="@+id/area"
android:layout_alignParentStart="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
7. Menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item android:id="@+id/show" android:title="Show"
android:orderInCategory="100" android:showAsAction="always" />
<item android:id="@+id/add" android:title="Add"
android:orderInCategory="100" android:showAsAction="always" />
</menu>
8. String
9. <resources>
<string name="app_name">Content Consumer</string>
<string name="action_settings">Settings</string>
<string-array name="unionArray">
<item>European Union</item>
<item>Gulf Cooperation Council</item>
<item>African Union</item>
</string-array>
</resources>

More Related Content

What's hot

Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curse
Yonatan Levin
 
Getting Started with MongoDB: 4 Application Designs
Getting Started with MongoDB: 4 Application DesignsGetting Started with MongoDB: 4 Application Designs
Getting Started with MongoDB: 4 Application Designs
DATAVERSITY
 
mobl - model-driven engineering lecture
mobl - model-driven engineering lecturemobl - model-driven engineering lecture
mobl - model-driven engineering lecture
zefhemel
 

What's hot (19)

Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curse
 
Py spark cheat sheet by cheatsheetmaker.com
Py spark cheat sheet by cheatsheetmaker.comPy spark cheat sheet by cheatsheetmaker.com
Py spark cheat sheet by cheatsheetmaker.com
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no android
 
Getting Started with MongoDB: 4 Application Designs
Getting Started with MongoDB: 4 Application DesignsGetting Started with MongoDB: 4 Application Designs
Getting Started with MongoDB: 4 Application Designs
 
Functions
FunctionsFunctions
Functions
 
Google Chart Tools Kanika Garg (10BM60035) Lavanya R. (10BM60042)
Google Chart Tools Kanika Garg (10BM60035) Lavanya R. (10BM60042)Google Chart Tools Kanika Garg (10BM60035) Lavanya R. (10BM60042)
Google Chart Tools Kanika Garg (10BM60035) Lavanya R. (10BM60042)
 
Android crashcourse
Android crashcourseAndroid crashcourse
Android crashcourse
 
What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?
 
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.
 
Cassandra Summit 2015
Cassandra Summit 2015Cassandra Summit 2015
Cassandra Summit 2015
 
Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View Classes
 
Dex Technical Seminar (April 2011)
Dex Technical Seminar (April 2011)Dex Technical Seminar (April 2011)
Dex Technical Seminar (April 2011)
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkit
 
mobl - model-driven engineering lecture
mobl - model-driven engineering lecturemobl - model-driven engineering lecture
mobl - model-driven engineering lecture
 
Vaadin 7 Today and Tomorrow
Vaadin 7 Today and TomorrowVaadin 7 Today and Tomorrow
Vaadin 7 Today and Tomorrow
 
662305 LAB12
662305 LAB12662305 LAB12
662305 LAB12
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQuery
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Java: Nie popełniaj tych błędów!
Java: Nie popełniaj tych błędów!Java: Nie popełniaj tych błędów!
Java: Nie popełniaj tych błędów!
 

Similar to Android Sample Project By Wael Almadhoun

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
Heiko Behrens
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
Conint29
 

Similar to Android Sample Project By Wael Almadhoun (20)

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)
 
Android For All The Things
Android For All The ThingsAndroid For All The Things
Android For All The Things
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
 
SharePoint Conference 2018 - APIs, APIs everywhere!
SharePoint Conference 2018 - APIs, APIs everywhere!SharePoint Conference 2018 - APIs, APIs everywhere!
SharePoint Conference 2018 - APIs, APIs everywhere!
 
AI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedAI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You Typed
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
 
ButterKnife
ButterKnifeButterKnife
ButterKnife
 
Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
 
Vaadin7
Vaadin7Vaadin7
Vaadin7
 
Implementing cast in android
Implementing cast in androidImplementing cast in android
Implementing cast in android
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
What's New in Android
What's New in AndroidWhat's New in Android
What's New in Android
 
F1
F1F1
F1
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Android development for iOS developers
Android development for iOS developersAndroid development for iOS developers
Android development for iOS developers
 
SharePoint Saturday Belgium 2018 - APIs, APIs everywhere!
SharePoint Saturday Belgium 2018 - APIs, APIs everywhere!SharePoint Saturday Belgium 2018 - APIs, APIs everywhere!
SharePoint Saturday Belgium 2018 - APIs, APIs everywhere!
 
APIs, APIs Everywhere!
APIs, APIs Everywhere!APIs, APIs Everywhere!
APIs, APIs Everywhere!
 

Android Sample Project By Wael Almadhoun

  • 1. Content Providers’ in Android Application Sample Project Coursework Wael Almadhoun
  • 2. Background Content providers in Android provide access to data that is shared between different apps. The contentprovideristhe ownerof the data,but providesaninterfacetoallow activitiesfromother applications in Android to access the data. The intention istoadd; You can populate the contentwithdataaboutEuropeanUnion countries,orGulf CooperationCouncil countries,AfricanUnion,etc.For eachcountry you shouldstore itscapital city,population,areainsquare kilometres,anditsofficial language or languages,andanyotherdata you like.. The Solution: 1. FirstApp:The producerapplicationisdesignedtoconstructthe SQLite database and the data entryscreen. 2. SecondApp:The consumerapplicationisdesignedtoview the datastoredbythe firstapp (aslist) the data can be editedalso. The followingscreensandJavaclasses includedinthe ProducerApplication: 1. Classeswithin com.example.contentproviderproducerpackage  MainActivity  CountryProvider 2. ClasseswithinDBSQLin com.example.contentproviderproducer package  DBCountry  CountryDatabaseHelper 3. Activities  activity_main.xml Introduction The ApplicationUserExperience.  Simple userinterfacetoenterthe followingrequireddata, Selectthe " union", " capital ", " population","area", " language" and" other”
  • 3. Activity: activity_main Input form ContentValuesMainActivityClass SQLite FirstApp:Producer UTHORITY = "com.example.contentproviderproducer.countrycrovider"; CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + STUDENT_TABLE); SecondApp: Consumer Activity: row_country List view (Card Widget) Show Details (Flip View) Activity: activity_main Add Form
  • 4. The Activities The below screenshots taken from my Mobile (samsung galaxy s6 – android lollipop) FirstApp – Addnewcountryentry:
  • 7. The Code for First Application(Producer) 1. The manifestfile <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.contentproviderproducer" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:authorities="com.example.contentproviderproducer.countrycrovider" android:name=".CountryProvider" android:exported="true"></provider> </application> </manifest> 2. Main Activity 3. package com.example.contentproviderproducer; import android.app.Activity; import android.content.ContentValues; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.example.contentproviderproducer.DBSQL.DBCountry; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // declare new instance of the database and open the connection final DBCountry db = new DBCountry(this); db.open(); final EditText name = (EditText)findViewById(R.id.name);
  • 8. final EditText population = (EditText)findViewById(R.id.population); final EditText area = (EditText)findViewById(R.id.area); final EditText capital = (EditText)findViewById(R.id.capital); final EditText language = (EditText)findViewById(R.id.language); final EditText other = (EditText)findViewById(R.id.other); final Spinner union = (Spinner)findViewById(R.id.union); Button buttonsave=(Button)findViewById(R.id.insert); // add items values taken from the input screen to contentValues; buttonsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ContentValues values = new ContentValues(); values.put("name", ""+name.getText().toString()); values.put("capital", ""+capital.getText().toString()); values.put("population", ""+population.getText().toString()); values.put("area", ""+area.getText().toString()); values.put("language", ""+language.getText().toString()); values.put("count_union", ""+union.getSelectedItem().toString()); values.put("other", ""+other.getText().toString()); // insert the loaded values into database using the DB helper insert procedure db.insert("Country", values); // preview a toast message to user confirming the new entry Toast.makeText(MainActivity.this, "New Country Added!", Toast.LENGTH_SHORT).show(); } }); } } 4. CountryProvider package com.example.contentproviderproducer; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import com.example.contentproviderproducer.DBSQL.DBCountry; /** * class CountryProvider as Content Provide and uri. */ public class CountryProvider extends ContentProvider{ public static final String AUTHORITY = "com.example.contentproviderproducer.countrycrovider";
  • 9. public static final String STUDENT_TABLE = "Country"; public static final int CHOICE_TABLE = 1; public static final int CHOICE_TABLE_ROW = 2; UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); DBCountry db; @Override public boolean onCreate() { uriMatcher.addURI(AUTHORITY,STUDENT_TABLE,CHOICE_TABLE); uriMatcher.addURI(AUTHORITY,STUDENT_TABLE+"/#",CHOICE_TABLE_ROW); db = new DBCountry(getContext()); db.open(); return (db==null)? false:true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { int choice = uriMatcher.match(uri); Cursor c = null; if(choice == CHOICE_TABLE){ c = db.query(STUDENT_TABLE,projection,selection,selectionArgs,sortOrder); getContext().getContentResolver().notifyChange(uri,null); } return c; } @Override public Uri insert(Uri uri, ContentValues values) { int choice = uriMatcher.match(uri); long id = -1; if(choice == CHOICE_TABLE){ id = db.insert(STUDENT_TABLE,values); getContext().getContentResolver().notifyChange(uri,null); } return Uri.parse("content://"+AUTHORITY+"/"+STUDENT_TABLE+"/"+id); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int choice = uriMatcher.match(uri); int count = -1; if(choice == CHOICE_TABLE){ count = db.delete(STUDENT_TABLE,selection,selectionArgs); } return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int choice = uriMatcher.match(uri); int rowsAffected = -1; if(choice == CHOICE_TABLE){ rowsAffected = db.update(STUDENT_TABLE,values,selection,selectionArgs); }
  • 10. return rowsAffected; } @Override public String getType(Uri uri) { return null; } } 5. DBSQL. DBCountry 6. package com.example.contentproviderproducer.DBSQL; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; /** * Define the databse helper to perform CRUD actions on the deatabase. * I used insert prcedure in this app */ public class DBCountry { CountryDatabaseHelper countryDatabaseHelper; SQLiteDatabase db; Context context; public DBCountry(Context context) { this.context = context; countryDatabaseHelper = new CountryDatabaseHelper(context, "dbCountry", null, 1); } public void open() { db = countryDatabaseHelper.getWritableDatabase(); } public void close() { countryDatabaseHelper.close(); } public void beginTransaction() { db.beginTransaction(); } public void endTransaction() { db.endTransaction(); } public void setTransactionSuccessful() { db.setTransactionSuccessful(); } public long insert(String tableName, ContentValues values) { return db.insert(tableName, null, values); } public Cursor query(String tableName, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
  • 11. return db.query(tableName, projection, selection, selectionArgs, null, null, sortOrder); } public int delete(String tableName , String whereClause , String[] args){ return db.delete(tableName, whereClause, args); } public int update(String tableName ,ContentValues values, String whereClause , String[] args){ return db.update(tableName, values, whereClause, args); } public void insertWithPerformance(String query,String... values){ SQLiteStatement stmt = db.compileStatement(query); beginTransaction(); stmt.bindString(1,values[0]); stmt.bindString(2,values[1]); stmt.execute(); stmt.clearBindings(); setTransactionSuccessful(); endTransaction(); } } 7. DBSQL. CountryDatabaseHelper package com.example.contentproviderproducer.DBSQL; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Create the database table required to store the app data - Country. * using SQLite */ public class CountryDatabaseHelper extends SQLiteOpenHelper{ public CountryDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("Create Table Country(_id INTEGER PRIMARY KEY AUTOINCREMENT ," + " name TEXT NOT NULL ," + " capital TEXT ," + " population TEXT ," + " area TEXT ," + " language TEXT ," + " count_union TEXT ," + " other TEXT )"); }
  • 12. // in case of updating the app, the table will be recreated @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE Country IF EXIST"); onCreate(db); } } 8. Activity_main.xml <LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical" > <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Union" android:ems="10" android:id="@+id/union" android:entries="@array/unionArray" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="name" android:ems="10" android:id="@+id/name" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="capital" android:ems="10" android:id="@+id/capital" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="population" android:ems="10" android:id="@+id/population" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="area" android:ems="10" android:id="@+id/area" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName"
  • 13. android:hint="language" android:ems="10" android:id="@+id/language" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="other" android:ems="10" android:id="@+id/other" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Insert" android:id="@+id/insert" /> </LinearLayout> 9. string.xml <resources> <string name="app_name">ContentProviderProducer</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string-array name="unionArray"> <item>European Union</item> <item>Gulf Cooperation Council</item> <item>African Union</item> </string-array> </resources>
  • 14. The Code for Second Application(Consumer) 1. The manifestfile 2. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.contentproviderconsumer" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 3. MainActivity package com.example.contentproviderconsumer; import android.app.Activity; import android.app.LoaderManager; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; import android.widget.ViewFlipper; public class MainActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> { ListView lst; ViewFlipper flipper; CountryCursorAdapter countryCursorAdapter; int ref = 1; public static final String AUTHORITY =
  • 15. "com.example.contentproviderproducer.countrycrovider"; public static final String STUDENT_TABLE = "Country"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + STUDENT_TABLE); private Button buttonsave; EditText name, population, area, capital, language, other; Spinner union; ContentResolver contentResolver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); flipper = (ViewFlipper) findViewById(R.id.viewFlipper); name = (EditText) findViewById(R.id.name); population = (EditText) findViewById(R.id.population); area = (EditText) findViewById(R.id.area); capital = (EditText) findViewById(R.id.capital); language = (EditText) findViewById(R.id.language); other = (EditText) findViewById(R.id.other); union = (Spinner)findViewById(R.id.union); buttonsave = (Button) findViewById(R.id.insert); contentResolver = getContentResolver(); lst = (ListView) findViewById(R.id.listView); getLoaderManager().initLoader(ref, null, this); ref++; btnAddClick(); } public void btnAddClick(){ buttonsave.setText("Save insert"); buttonsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ContentValues values = new ContentValues(); values.put("name", "" + name.getText().toString()); values.put("capital", "" + capital.getText().toString()); values.put("population", "" + population.getText().toString()); values.put("area", "" + area.getText().toString()); values.put("language", "" + language.getText().toString()); values.put("other", "" + other.getText().toString()); values.put("count_union", ""+union.getSelectedItem().toString()); Uri uri = contentResolver.insert(CONTENT_URI, values); // countryCursorAdapter. //contentResolver Toast.makeText(v.getContext(), uri.toString(), Toast.LENGTH_SHORT).show(); getLoaderManager().initLoader(ref, null, MainActivity.this); countryCursorAdapter.notifyDataSetChanged(); ref++; name.setText(""); population.setText(""); area.setText(""); capital.setText(""); language.setText(""); other.setText(""); //----------------------------------
  • 16. try { flipper.showPrevious(); } catch (Exception w) { flipper.showNext(); } // --------------------------------------- } }); } @Override public Loader onCreateLoader(int id, Bundle args) { return new CursorLoader(this, CONTENT_URI, null, null, null, null); } @Override public void onLoadFinished(Loader loader, Cursor data) { countryCursorAdapter = new CountryCursorAdapter(this, data, 0); lst.setAdapter(countryCursorAdapter); countryCursorAdapter.setCutdorListLisiner(new CountryCursorAdapter.CutdorListLisiner() { @Override public void OnClickCountryListener(Context context, final String _id, String s_name, String s_population, String s_area, String s_capital, String s_language) { //populate the text values into fields name.setText(s_name); population.setText(s_population); area.setText(s_area); capital.setText(s_capital); language.setText(s_language); flipper.showNext(); buttonsave.setText("Save Update"); buttonsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ContentValues values = new ContentValues(); values.put("name", "" + name.getText().toString()); values.put("capital", "" + capital.getText().toString()); values.put("population", "" + population.getText().toString()); values.put("area", "" + area.getText().toString()); values.put("language", "" + language.getText().toString()); values.put("count_union", ""+union.getSelectedItem().toString()); // countryCursorAdapter.swapCursor() contentResolver.update(CONTENT_URI,values,"_id=?",new String[]{""+_id}); getLoaderManager().initLoader(ref, null, MainActivity.this); countryCursorAdapter.notifyDataSetChanged(); ref++; //---------------------------------- try { flipper.showPrevious(); } catch (Exception w) { flipper.showNext(); } // ---------------------------------------
  • 17. } }); } }); } @Override public void onLoaderReset(Loader loader) { } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); MenuItem item = menu.findItem(R.id.add); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long int id = item.getItemId(); if (id == R.id.add) { btnAddClick(); try { flipper.showNext(); } catch (Exception w) { flipper.showPrevious(); } return true; } else { try { flipper.showPrevious(); } catch (Exception w) { flipper.showNext(); } return true; } } } 4. CountryCursorAdapter package com.example.contentproviderconsumer; import android.content.Context; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
  • 18. import android.widget.RelativeLayout; import android.widget.TextView; public class CountryCursorAdapter extends CursorAdapter { public CountryCursorAdapter(Context context, Cursor cursor, int flags) { super(context, cursor, 0); } CutdorListLisiner cutdorListLisiner; public void setCutdorListLisiner(CutdorListLisiner cutdorListLisiner) { this.cutdorListLisiner = cutdorListLisiner; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.row_country, parent, false); } // The bindView method is used to bind all data to a given view // such as setting the text on a TextView. @Override public void bindView(View view, final Context context, Cursor cursor) { // Find fields to populate in inflated template final TextView name = (TextView)view.findViewById(R.id.name); final TextView population = (TextView)view.findViewById(R.id.population); final TextView area = (TextView)view.findViewById(R.id.area); final TextView capital = (TextView)view.findViewById(R.id.capital); final TextView language = (TextView)view.findViewById(R.id.language); final TextView union = (TextView)view.findViewById(R.id.union); final RelativeLayout rel_item = (RelativeLayout)view.findViewById(R.id.rel_item); final String _id = cursor.getString(cursor.getColumnIndexOrThrow("_id")); final String s_name = cursor.getString(cursor.getColumnIndexOrThrow("name")); final String s_population = cursor.getString(cursor.getColumnIndexOrThrow("population")); final String s_area = cursor.getString(cursor.getColumnIndexOrThrow("area")); final String s_capital = cursor.getString(cursor.getColumnIndexOrThrow("capital")); final String s_language = cursor.getString(cursor.getColumnIndexOrThrow("language")); final String s_union = cursor.getString(cursor.getColumnIndexOrThrow("count_union")); rel_item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cutdorListLisiner.OnClickCountryListener(context,_id,s_name,s_population,s_a rea,s_capital,s_language); } }); // Populate fields with extracted properties name.setText(s_name); population.setText(s_population); area.setText(s_area); capital.setText("("+s_capital+")"); language.setText(s_language);
  • 19. union.setText(s_union); } public interface CutdorListLisiner{ public void OnClickCountryListener(Context context, String _id,String s_name,String s_population,String s_area,String s_capital,String s_language); } } 5. activity_main.xml <LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical" > <ViewFlipper android:id="@+id/viewFlipper" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent" android:layout_width="match_parent"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listView" /> <LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:layout_height="wrap_content"> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Union" android:ems="10" android:id="@+id/union" android:entries="@array/unionArray" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="name" android:ems="10" android:id="@+id/name" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="capital" android:ems="10" android:id="@+id/capital" />
  • 20. <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="population" android:ems="10" android:id="@+id/population" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="area" android:ems="10" android:id="@+id/area" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="language" android:ems="10" android:id="@+id/language" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="other" android:ems="10" android:id="@+id/other" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Insert" android:id="@+id/insert" /> </LinearLayout> </ViewFlipper> </LinearLayout> 6. row_country.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:id="@+id/rel_item" android:padding="4dp" android:layout_height="match_parent"> <android.support.v7.widget.CardView android:layout_width="match_parent" app:cardBackgroundColor="#ccc" android:layout_height="wrap_content" android:background="#ccc" app:cardCornerRadius="4dp" app:cardElevation="3dp" app:cardMaxElevation="3dp" app:cardPreventCornerOverlap="false" android:padding="8dp" android:layout_margin="8dp" android:layout_alignParentTop="true"
  • 21. android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:id="@+id/view"> <RelativeLayout android:layout_width="match_parent" android:padding="4dp" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="name" android:layout_marginBottom="4dp" android:id="@+id/name" android:layout_alignParentTop="true" android:layout_alignParentStart="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="capital" android:id="@+id/capital" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="population" android:gravity="center" android:id="@+id/population" android:layout_alignBottom="@+id/imageView2" android:layout_toEndOf="@+id/imageView2" android:layout_alignTop="@+id/imageView2" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="area" android:id="@+id/area" android:gravity="center" android:layout_alignBottom="@+id/imageView" android:layout_toEndOf="@+id/imageView" android:layout_below="@+id/name" /> <ImageView android:layout_width="25dp" android:layout_height="25dp" android:id="@+id/imageView" android:src="@drawable/ic_area" android:layout_below="@+id/name" android:layout_alignParentStart="true" /> <ImageView android:layout_marginLeft="20dp" android:layout_width="25dp" android:layout_height="25dp" android:id="@+id/imageView2" android:src="@drawable/ic_people" android:layout_below="@+id/name"
  • 22. android:layout_toEndOf="@+id/area" /> <ImageView android:layout_marginLeft="20dp" android:layout_width="15dp" android:layout_height="15dp" android:id="@+id/imageView3" android:src="@drawable/ic_language" android:layout_alignBottom="@+id/language" android:layout_toStartOf="@+id/language" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="union" android:id="@+id/union" android:layout_marginTop="8dp" android:layout_alignParentStart="true" android:layout_below="@+id/language" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="language" android:layout_marginTop="8dp" android:id="@+id/language" android:layout_below="@+id/area" android:layout_alignParentStart="true" /> </RelativeLayout> </android.support.v7.widget.CardView> </RelativeLayout> 7. Menu <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <item android:id="@+id/show" android:title="Show" android:orderInCategory="100" android:showAsAction="always" /> <item android:id="@+id/add" android:title="Add" android:orderInCategory="100" android:showAsAction="always" /> </menu> 8. String 9. <resources> <string name="app_name">Content Consumer</string> <string name="action_settings">Settings</string> <string-array name="unionArray"> <item>European Union</item> <item>Gulf Cooperation Council</item> <item>African Union</item> </string-array> </resources>