How can I insert a new contact by using ContentProviderOperation - android

I have a form like below image and I want to add a new a contact by click on button add and using ContentProviderOperation for this
How can I do this ? Thanks you so much!!
And this is my onlick method
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edtName = (EditText) findViewById(R.id.edtName);
edtPhone = (EditText) findViewById(R.id.edtPhone);
edtEmail = (EditText) findViewById(R.id.edtEmail);
}
});

Before adding a contact you have to enable permission into the manifest file.
Android Manifest:
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
after adding permission.I have created one activity for adding contacts.
AddPhoneContactActivity.java file
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.test.example.R;
public class AddPhoneContactActivity extends AppCompatActivity {
private EditText displayNameEditor;
private EditText phoneNumberEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontact);
setTitle("dev2qa.com - Android Add Phone Contact Example.");
displayNameEditor = (EditText)findViewById(R.id.add_phone_contact_display_name);
phoneNumberEditor = (EditText)findViewById(R.id.add_phone_contact_number);
// Initialize phone type dropdown spinner.
final Spinner phoneTypeSpinner = (Spinner)findViewById(R.id.add_phone_contact_type);
String phoneTypeArr[] = {"Mobile", "Home", "Work"};
ArrayAdapter<String> phoneTypeSpinnerAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, phoneTypeArr);
phoneTypeSpinner.setAdapter(phoneTypeSpinnerAdaptor);
// Click this button to save user input phone contact info.
Button savePhoneContactButton = (Button)findViewById(R.id.add_phone_contact_save_button);
savePhoneContactButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get android phone contact content provider uri.
//Uri addContactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
// Below uri can avoid java.lang.UnsupportedOperationException: URI: content://com.android.contacts/data/phones error.
Uri addContactsUri = ContactsContract.Data.CONTENT_URI;
// Add an empty contact and get the generated id.
long rowContactId = getRawContactId();
// Add contact name data.
String displayName = displayNameEditor.getText().toString();
insertContactDisplayName(addContactsUri, rowContactId, displayName);
// Add contact phone data.
String phoneNumber = phoneNumberEditor.getText().toString();
String phoneTypeStr = (String)phoneTypeSpinner.getSelectedItem();
insertContactPhoneNumber(addContactsUri, rowContactId, phoneNumber, phoneTypeStr);
Toast.makeText(getApplicationContext(),"New contact has been added, go back to previous page to see it in contacts list." , Toast.LENGTH_LONG).show();
finish();
}
});
}
// This method will only insert an empty data to RawContacts.CONTENT_URI
// The purpose is to get a system generated raw contact id.
private long getRawContactId()
{
// Inser an empty contact.
ContentValues contentValues = new ContentValues();
Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
// Get the newly created contact raw id.
long ret = ContentUris.parseId(rawContactUri);
return ret;
}
// Insert newly created contact display name.
private void insertContactDisplayName(Uri addContactsUri, long rawContactId, String displayName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
// Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
// Put contact display name value.
contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName);
getContentResolver().insert(addContactsUri, contentValues);
}
private void insertContactPhoneNumber(Uri addContactsUri, long rawContactId, String phoneNumber, String phoneTypeStr)
{
// Create a ContentValues object.
ContentValues contentValues = new ContentValues();
// Each contact must has an id to avoid java.lang.IllegalArgumentException: raw_contact_id is required error.
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
// Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
// Put phone number value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
// Calculate phone type by user selection.
int phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
if("home".equalsIgnoreCase(phoneTypeStr))
{
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
}else if("mobile".equalsIgnoreCase(phoneTypeStr))
{
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
}else if("work".equalsIgnoreCase(phoneTypeStr))
{
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
}
// Put phone type value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, phoneContactType);
// Insert new contact data into phone contact list.
getContentResolver().insert(addContactsUri, contentValues);
}
// ListPhoneContactsActivity use this method to start this activity.
public static void start(Context context)
{
Intent intent = new Intent(context, AddPhoneContactActivity.class);
context.startActivity(intent);
}
}
activity_addcontact.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:width="0dp"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Name : "
android:gravity="right"/>
<EditText
android:id="#+id/add_phone_contact_display_name"
android:layout_weight="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:width="0dp"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Number : "
android:gravity="right" />
<EditText
android:id="#+id/add_phone_contact_number"
android:layout_weight="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:width="0dp"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone Type : "
android:gravity="right" />
<Spinner
android:id="#+id/add_phone_contact_type"
android:layout_weight="1.3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"/>
</LinearLayout>
<Button
android:id="#+id/add_phone_contact_save_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save Phone Contact"/>

Related

Getting DATABASE MISSING when trying to create a database

I have made my simple project using SQLite database. As per my code, app should show Database Created when I click on 'create database' but it shows Database Missing. I have checked logcat but I don't get any error over there.
MainActivity
package com.maka.sujan.sqllitedatabase;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends ActionBarActivity {
SQLiteDatabase contactsDB = null;
Button createDBButton, addContactButton, deleteContactButton, getContactsButton,
deleteDBButton;
EditText nameEditText, emailEditText, contactListEditText, idEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDBButton = (Button) findViewById(R.id.createDBButton);
addContactButton = (Button) findViewById(R.id.addContactButton);
deleteContactButton = (Button) findViewById(R.id.deleteContactButton);
getContactsButton = (Button) findViewById(R.id.getContactsButton);
deleteDBButton = (Button) findViewById(R.id.deleteDBButton);
nameEditText = (EditText) findViewById(R.id.nameEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
contactListEditText = (EditText) findViewById(R.id.contactListEditText);
idEditText = (EditText) findViewById(R.id.idEditText);
}
public void createDatabase(View view) {
try{
// Opens a current database or creates it
// Pass the database name, designate that only this app can use it
// and a DatabaseErrorHandler in the case of database corruption
contactsDB = this.openOrCreateDatabase("MyContacts", MODE_PRIVATE, null);
// Execute an SQL statement that isn't select
contactsDB.execSQL("CREATE TABLE IF NOT EXISTS contacts " +
"(id integer primary key, name VARCHAR, email VARCHAR);");
// The database on the file system
File database = getApplicationContext().getDatabasePath("MyContacts.db");
// Check if the database exists
if (database.exists()) {
Toast.makeText(this, "Database Created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Database Missing", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
Log.e("CONTACTS ERROR", "Error Creating Database");
}
// Make buttons clickable since the database was created
addContactButton.setClickable(true);
deleteContactButton.setClickable(true);
getContactsButton.setClickable(true);
deleteDBButton.setClickable(true);
}
public void addContact(View view) {
// Get the contact name and email entered
String contactName = nameEditText.getText().toString();
String contactEmail = emailEditText.getText().toString();
// Execute SQL statement to insert new data
contactsDB.execSQL("INSERT INTO contacts (name, email) VALUES ('" +
contactName + "', '" + contactEmail + "');");
}
public void getContacts(View view) {
// A Cursor provides read and write access to database results
Cursor cursor = contactsDB.rawQuery("SELECT * FROM contacts", null);
// Get the index for the column name provided
int idColumn = cursor.getColumnIndex("id");
int nameColumn = cursor.getColumnIndex("name");
int emailColumn = cursor.getColumnIndex("email");
// Move to the first row of results
cursor.moveToFirst();
String contactList = "";
// Verify that we have results
if(cursor != null && (cursor.getCount() > 0)){
do{
// Get the results and store them in a String
String id = cursor.getString(idColumn);
String name = cursor.getString(nameColumn);
String email = cursor.getString(emailColumn);
contactList = contactList + id + " : " + name + " : " + email + "\n";
// Keep getting results as long as they exist
}while(cursor.moveToNext());
contactListEditText.setText(contactList);
} else {
Toast.makeText(this, "No Results to Show", Toast.LENGTH_SHORT).show();
contactListEditText.setText("");
}
}
public void deleteContact(View view) {
// Get the id to delete
String id = idEditText.getText().toString();
// Delete matching id in database
contactsDB.execSQL("DELETE FROM contacts WHERE id = " + id + ";");
}
public void deleteDatabase(View view) {
// Delete database
this.deleteDatabase("MyContacts");
}
#Override
protected void onDestroy() {
contactsDB.close();
super.onDestroy();
}
}
activity_main
<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" 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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Database"
android:id="#+id/createDBButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="createDatabase"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Contact"
android:id="#+id/addContactButton"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/createDBButton"
android:layout_toEndOf="#+id/createDBButton"
android:layout_marginLeft="10dp"
android:onClick="addContact"
android:clickable="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Contact"
android:id="#+id/deleteContactButton"
android:layout_below="#+id/createDBButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="deleteContact"
android:clickable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Contacts"
android:id="#+id/getContactsButton"
android:layout_below="#+id/createDBButton"
android:layout_toRightOf="#+id/deleteContactButton"
android:layout_toEndOf="#+id/deleteContactButton"
android:layout_marginLeft="10dp"
android:onClick="getContacts"
android:clickable="false"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/nameEditText"
android:layout_below="#+id/deleteContactButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Name"
android:layout_marginTop="5dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/emailEditText"
android:layout_below="#+id/nameEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Email"
android:layout_marginTop="5dp"
android:inputType="textEmailAddress"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/idEditText"
android:layout_below="#+id/emailEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="ID to Delete"
android:layout_marginTop="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Database"
android:id="#+id/deleteDBButton"
android:onClick="deleteDatabase"
android:layout_below="#+id/idEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="false" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/contactListEditText"
android:lines="8"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
put the extension in the line :
contactsDB = this.openOrCreateDatabase("MyContacts", MODE_PRIVATE, null);
to
contactsDB = this.openOrCreateDatabase("MyContacts.db", MODE_PRIVATE, null);
Your call to openOrCreateDatabase() create a database with the file name MyContacts.
Your call to getDatabasePath() searches for a file with a different name, i.e., MyContacts.db.

contacts app Manager

I want to make android Contacts app, there is no problem with my code but when I execute the code, the App crush and show a message
"Exavier unfortunately has stopped working "
--Main Activity.java
package com.example.enig.exaviser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File
public class MainActivity extends ActionBarActivity {
SQLiteDatabase contactsDB = null;
Button createDBButton, addContactButton, deleteContactButton, getContactsButton,
deleteDBButton;
EditText nameEditText, emailEditText, contactListEditText, idEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
createDBButton = (Button) findViewById(R.id.createDBButton);
addContactButton = (Button) findViewById(R.id.addContactButton);
deleteContactButton = (Button) findViewById(R.id.deleteContactButton);
getContactsButton = (Button) findViewById(R.id.getContactsButton);
deleteDBButton = (Button) findViewById(R.id.deleteDBButton);
nameEditText = (EditText) findViewById(R.id.nameEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
contactListEditText = (EditText) findViewById(R.id.contactListEditText);
idEditText = (EditText) findViewById(R.id.idEditText);
}
public void createDatabase(View view) {
try{
// Opens a current database or creates it
// Pass the database name, designate that only this app can use it
// and a DatabaseErrorHandler in the case of database corruption
contactsDB = this.openOrCreateDatabase("MyContacts", MODE_PRIVATE, null);
// Execute an SQL statement that isn't select
contactsDB.execSQL("CREATE TABLE IF NOT EXISTS contacts " +
"(id integer primary key, name VARCHAR, email VARCHAR);");
// The database on the file system
File database = getApplicationContext().getDatabasePath("MyContacts.db");
// Check if the database exists
if (database.exists()) {
Toast.makeText(this, "Database Created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Database Missing", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
Log.e("CONTACTS ERROR", "Error Creating Database");
}
// Make buttons clickable since the database was created
addContactButton.setClickable(true);
deleteContactButton.setClickable(true);
getContactsButton.setClickable(true);
deleteDBButton.setClickable(true);
}
public void addContact(View view) {
// Get the contact name and email entered
String contactName = nameEditText.getText().toString();
String contactEmail = emailEditText.getText().toString();
// Execute SQL statement to insert new data
contactsDB.execSQL("INSERT INTO contacts (name, email) VALUES ('" +
contactName + "', '" + contactEmail + "');");
}
public void getContacts(View view) {
// A Cursor provides read and write access to database results
Cursor cursor = contactsDB.rawQuery("SELECT * FROM contacts", null);
// Get the index for the column name provided
int idColumn = cursor.getColumnIndex("id");
int nameColumn = cursor.getColumnIndex("name");
int emailColumn = cursor.getColumnIndex("email");
// Move to the first row of results
cursor.moveToFirst();
String contactList = "";
// Verify that we have results
if(cursor != null && (cursor.getCount() > 0)){
do{
// Get the results and store them in a String
String id = cursor.getString(idColumn);
String name = cursor.getString(nameColumn);
String email = cursor.getString(emailColumn);
contactList = contactList + id + " : " + name + " : " + email + "\n";
// Keep getting results as long as they exist
}while(cursor.moveToNext());
contactListEditText.setText(contactList);
} else {
Toast.makeText(this, "No Results to Show", Toast.LENGTH_SHORT).show();
contactListEditText.setText("");
}
}
public void deleteContact(View view) {
// Get the id to delete
String id = idEditText.getText().toString();
// Delete matching id in database
contactsDB.execSQL("DELETE FROM contacts WHERE id = " + id + ";");
}
public void deleteDatabase(View view) {
// Delete database
this.deleteDatabase("MyContacts");
}
#Override
protected void onDestroy() {
contactsDB.close();
super.onDestroy();
}
}
fragment_main.xml
<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" 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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Database"
android:id="#+id/createDBButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="createDatabase"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Contact"
android:id="#+id/addContactButton"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/createDBButton"
android:layout_toEndOf="#+id/createDBButton"
android:layout_marginLeft="10dp"
android:onClick="addContact"
android:clickable="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Contact"
android:id="#+id/deleteContactButton"
android:layout_below="#+id/createDBButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="deleteContact"
android:clickable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Contacts"
android:id="#+id/getContactsButton"
android:layout_below="#+id/createDBButton"
android:layout_toRightOf="#+id/deleteContactButton"
android:layout_toEndOf="#+id/deleteContactButton"
android:layout_marginLeft="10dp"
android:onClick="getContacts"
android:clickable="false"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/nameEditText"
android:layout_below="#+id/deleteContactButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Name"
android:layout_marginTop="5dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/emailEditText"
android:layout_below="#+id/nameEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Email"
android:layout_marginTop="5dp"
android:inputType="textEmailAddress"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/idEditText"
android:layout_below="#+id/emailEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="ID to Delete"
android:layout_marginTop="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Database"
android:id="#+id/deleteDBButton"
android:onClick="deleteDatabase"
android:clickable="false"
android:layout_above="#+id/contactListEditText"
android:layout_alignRight="#+id/contactListEditText"
android:layout_alignEnd="#+id/contactListEditText" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/contactListEditText"
android:lines="8"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
How can I fix this problem? thanks in advance
The reason you are having this problem is because the activity is extending ActionBarActivity which requires the AppCompat theme to be applied.
All you need to do is add android:theme="#style/Theme.AppCompat.Light" to your application tag in the AndroidManifest.xml file.

Android SQLite : Take and Save Photo to DB as Base64 string... Then retrieve

I would like to develop a full-proof solution to a common problem for new android developers. I want to create a tutorial and example (for myself and others to follow) to taking a photo witin an app and then saving it to base64 string within a SQLite android database. Then I will be able to upload this string to an online database at a later stage, rather than the JPG image I originally took.
So to re-iterate it must...
Open Camera,
Take Image
Save as Base64 String to SQLite DB
(the reason that I need it to be stored in the DB as a string, is due to the fact that this will be uploaded to a central document system at some point in the future, and large JPG images will be slow and not ideal, hence why a Base64 string in the DB would be better. I also want to limit the possibility that users can delete the images they take which would be referenced in the DB should be just refrence the path to the file (which is the alternative - although I believe a less suitable one))
Thanks, I really look forward to working on this and developing a great solution that others will be able to follow.
MY EFFORTS SO FAR...
I have spent a number of days looking into this, and at the moment I am more confused than at the start. There seems to be so much outthere about this, but nothing with step by step sections to follow, about what line does what, where it comes from, what its doing etc. So to start with, I think I may need to break this down into two tasks now...
Taking an image using the camera and giving the file as an output somehow...then saving this as a base64 string to the DB or something like this.
I appreciate that usually storing binary data to the DB can cause slow and painful queries, however due to the face that only a few images will ever be displayed at once, we shouldn't have too much of an issue here, and the SQLite queries are small.
So to start with I was following Android: how to take picture with camera and convert bitmap to byte array and save to sqlite db? however the instructions to save images locally and reference the file path, really don't work. and so I was back to square one almost...
I have been reading through http://developer.android.com/guide/topics/media/camera.html to learn about the camera... confused.com !!!
To be fair, I have read so much, and now understand so little, I need a dummies guide to this now. Wish I could unlearn all the useless crap which I have read about this and start from scratch... Where is Format /F for your brain?
OK so i started again...
Things are going a lot better for me now, I have even added audio, but I won't get into that. My app at the moment, takes a photo, previews it (using the standard camera intent) and then on clicking save, displays it locally on the app. Instead of it displaying the image, on clicking save, I need it to save to a database as a blob/bit64
Here is my code so you can see where I am at...
trying to use this as the call to take the image...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<ScrollView
android:layout_height="fill_parent"
android:layout_width="fill_parent"
>
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical">
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inspection ID" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/txtName"
android:inputType="number"
android:maxLength="5"
android:digits="0123456789"
android:singleLine="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1" />
<EditText
android:id="#+id/txt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoText="false"
android:gravity="top|left"
android:lines="4"
android:maxLines="4"
android:minLines="4"
android:scrollbars="vertical"
android:singleLine="false"
android:width="0dip" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Project Ref"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/txtAge"
android:inputType="number"
android:maxLength="5"
android:digits="0123456789"
android:singleLine="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drop Down"
/>
<Spinner
android:id="#+id/spinDept"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnPhotoCamera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="camera" />
<Button
android:id="#+id/btnPhotoGallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="gallery" />
<TextView
android:id="#+id/lblDisplayImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnCancel"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="below_this_text_image_will_be_displayed"
android:textSize="13dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/lblDisplayImage"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:gravity="bottom" >
<!--
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
-->
<ImageView
android:id="#+id/imgDisplayImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:contentDescription="area_where_image_is_to_be_displayed" />
<!-- </ScrollView> -->
</RelativeLayout>
<Button
android:id="#+id/btnAudio"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnAudio"
android:text="Audio" />
<Button
android:id="#+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnAddEmp_Click"
android:text="Save Inspection" />
<Button
android:id="#+id/btnCancel"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_below="#+id/btnPhotoGallery"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="Reset/Clear Form Data" />
<TextView
android:id="#+id/txtEmps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number of Inspections on Device " />
</LinearLayout>
</ScrollView>
</LinearLayout>
with the following .java
package mina.android.DatabaseDemo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Spannable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import com.AssentApp.V100.R;
public class AddEmployee extends Activity {
EditText txtName;
EditText txtAge;
TextView txtEmps;
DatabaseHelper dbHelper;
Spinner spinDept;
/** The Constant PICK_IMAGE. */
private static final int PICK_IMAGE = 0;
/** The Constant PICK_IMAGE_FROM_GALLERY. */
private static final int PICK_IMAGE_FROM_GALLERY = 1;
/** The btn cancel. */
private Button btnPhotoCamera,btnPhotoGallery,btnCancel;
/** The img view. */
private ImageView imgView;
/** The u. */
private Uri u;
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addemployee);
txtName=(EditText)findViewById(R.id.txtName);
txtAge=(EditText)findViewById(R.id.txtAge);
txtEmps=(TextView)findViewById(R.id.txtEmps);
spinDept=(Spinner)findViewById(R.id.spinDept);
imgView=(ImageView)findViewById(R.id.imgDisplayImage);
btnPhotoCamera=(Button)findViewById(R.id.btnPhotoCamera);
btnPhotoGallery=(Button)findViewById(R.id.btnPhotoGallery);
btnCancel=(Button)findViewById(R.id.btnCancel);
btnPhotoCamera.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent camera=new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("crop", "false");
File f=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
u = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"myFile.jpg"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, u);
startActivityForResult(camera, PICK_IMAGE);
}
});
btnPhotoGallery.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_FROM_GALLERY);
}
});
btnCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent goStartUp=new Intent(AddEmployee.this, AddEmployee.class);
goStartUp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goStartUp);
finish();
}
});
}
/* (non-Javadoc)
* #see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode==RESULT_OK )
{
if(requestCode == PICK_IMAGE) {
InputStream is=null;
try {
is = this.getContentResolver().openInputStream(u);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp=BitmapFactory.decodeStream(is);
imgView.setImageBitmap(bmp);
Log.i("Inside", "PICK_IMAGE");
}
if (requestCode == PICK_IMAGE_FROM_GALLERY) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Log.d("data",filePathColumn[0]);
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imgView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Log.i("Inside", "PICK_IMAGE_FROM_GALLERY");
}
}
}
public void onStart()
{
try
{
super.onStart();
dbHelper=new DatabaseHelper(this);
txtEmps.setText(txtEmps.getText()+String.valueOf(dbHelper.getEmployeeCount()));
Cursor c=dbHelper.getAllDepts();
startManagingCursor(c);
//SimpleCursorAdapter ca=new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String [] {DatabaseHelper.colDeptName}, new int []{android.R.id.text1});
SimpleCursorAdapter ca=new SimpleCursorAdapter(this,R.layout.deptspinnerrow, c, new String [] {DatabaseHelper.colDeptName,"_id"}, new int []{R.id.txtDeptName});
//ca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinDept.setAdapter(ca);
spinDept.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View selectedView,
int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
//never close cursor
}
catch(Exception ex)
{
CatchError(ex.toString());
}
}
public void btnAddEmp_Click(View view)
{
boolean ok=true;
try
{
Spannable spn=txtAge.getText();
String name=txtName.getText().toString();
int age=Integer.valueOf(spn.toString());
int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());
Employee emp=new Employee(name,age,deptID);
dbHelper.AddEmployee(emp);
}
catch(Exception ex)
{
ok=false;
CatchError(ex.toString());
}
finally
{
if(ok)
{
//NotifyEmpAdded();
Alerts.ShowEmpAddedAlert(this);
txtEmps.setText("Number of Inspections on Device "+String.valueOf(dbHelper.getEmployeeCount()));
}
}
}
void CatchError(String Exception)
{
Dialog diag=new Dialog(this);
diag.setTitle("Adding new Inspection");
TextView txt=new TextView(this);
txt.setText(Exception);
diag.setContentView(txt);
diag.show();
}
void NotifyEmpAdded()
{
Dialog diag=new Dialog(this);
diag.setTitle("Success");
TextView txt=new TextView(this);
txt.setText("Inspection Added Successfully");
diag.setContentView(txt);
diag.show();
try {
diag.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
CatchError(e.toString());
}
diag.notify();
diag.dismiss();
}
public void btnAudio(View view)
{
Intent intent = new Intent(AddEmployee.this, AudioRecordTest.class);
startActivity(intent);
}
}
seems to do the trick, but now I need to edit it for the DB section. I need to save it "by converting image into Byte[] then save as Blob in sqlite" - or so I believe ... Whats my first step in doing this? Note, I don't want it to display the image view anymore, but instead save to DB with unique ID/Integer.
any pointers would be great !!
i don't think u can do it using base64 , but yes you can do that thing by converting image into Byte[] then save as Blob in sqlite.

Display google calendar on Android calendarView widget?

My question is simple, is there a way to display a Google Calendar using Android calendarView inside an application? I can't find a way to do so
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Introducing ICS Calendar"
android:gravity="center"
android:padding="10dip"/>
<TextView
android:id="#+id/data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/previous"
android:text="Prev"
android:padding="10dip"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:text="Next"
android:padding="10dip"/>
</LinearLayout>
</LinearLayout>
Main.java
import java.text.Format;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity implements OnClickListener{
private Cursor mCursor = null;
private static final String[] COLS = new String[]
{ CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART};
}
Now we need to override the on create method. Pay special attention to how we populate the database cursor. This is where we need our previously defined COLS constant. You’ll note also that after the database cursor is initialized and the click handler callbacks are set, we go ahead and manually invoke the on click handler. This shortcut allows us to initially fill out our UI without having to repeat code.
Main.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCursor = getContentResolver().query(
CalendarContract.Events.CONTENT_URI, COLS, null, null, null);
mCursor.moveToFirst();
Button b = (Button)findViewById(R.id.next);
b.setOnClickListener(this);
b = (Button)findViewById(R.id.previous);
b.setOnClickListener(this);
onClick(findViewById(R.id.previous));
}
In our callback, we will manipulate the cursor to the correct entry in the database and update the UI.
#Override
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.data);
String title = "N/A";
Long start = 0L;
switch(v.getId()) {
case R.id.next:
if(!mCursor.isLast()) mCursor.moveToNext();
break;
case R.id.previous:
if(!mCursor.isFirst()) mCursor.moveToPrevious();
break;
}
Format df = DateFormat.getDateFormat(this);
Format tf = DateFormat.getTimeFormat(this);
try {
title = mCursor.getString(0);
start = mCursor.getLong(1);
} catch (Exception e) {
//ignore
}
tv.setText(title+" on "+df.format(start)+" at "+tf.format(start));
}
permission :
<uses-permission android:name="android.permission.READ_CALENDAR"/>

Is it possible to execute some database query that user can write that queries from android application?

I want to create an android application that can run SQL Query to my SQL Server Database.
Here is my basic idea:
I create an android application with 1 textbox and 1 button.
Users can write the query that they want (e.g. INSERT INTO..,
UPDATE.., DELETE.., or EXEC [store procedure]) in the textbox.
Then users press the button to execute that query to run in my SQL
Server Database.
What I've made so far is an Android Application using phonegap + jQuery Mobile and I can get some data from my WCF Service with JSON that connect to my SQL Server, but now I want to run some query that I write from android application and run it to my database. Is it possible? Can you tell me the recommendation tutorials? Thanks :)
It can be done.
Create an Android application with an EditText and a Button.
Users can type the query to run (e.g. INSERT INTO.., UPDATE.., DELETE.., or EXEC [store procedure]) into the EditText.
You could do this like below to make it more user friendly.
Give users some options for Insert/Update/Delete via buttons.
Add a Spinner with all the table names.
If the user select a table name, show some _EditText_s for all the columns you need to get a value from the user.
Also you can make separate methods to call accordingly, with required inputs. It will be less complex more user friendly.
I don't know if it Is makes any sense.
Yas You can dear ..
i just success with select data from the sql server and i am sure very soon i am defiantly reach to the insert update and delete too.
for now you can also follow this tutorial which is actually in different language but you can go through the android and eclipse is working on english so just follow my steps.
1st make one project and download jtdc driver from this link but make sure the jtdc driver version is "1.2.7"
http://sourceforge.net/projects/jtds/files/jtds/1.2.7/
put this jar file in libs folder and write click on libs folder and build-add jar file and take that from libs folder and press ok which is reference library for sql server never forget this.
Now just follow my code bellow.
Make a xml file "sqlservermain.xml"
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SqlServerMain" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="SQL SERVER" />
<Button
android:id="#+id/btn_enter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/edt_name"
android:layout_alignBottom="#+id/edt_name"
android:layout_alignParentRight="true"
android:text="Enter" />
<ListView
android:id="#+id/lst_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/btn_enter"
android:layout_below="#+id/btn_enter"
android:layout_marginTop="19dp" >
</ListView>
<EditText
android:id="#+id/edt_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lst_name"
android:layout_below="#+id/textView1"
android:layout_marginTop="15dp"
android:ems="10" />
</RelativeLayout>
then make one another xml file which is "sql.xml" file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#000000"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#00BFFF"
android:textStyle="bold" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_toRightOf="#+id/imageView1"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
now make one java file which is "sqlservermain.java" file.
package com.sqlserver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class SqlServerMain extends Activity {
private Button _btnenter;
private EditText _edtval;
private ListView _lstname;
private Connection connect;
private SimpleAdapter AD;
private void declaration() {
_btnenter = (Button) findViewById(R.id.btn_enter);
_edtval = (EditText) findViewById(R.id.edt_name);
_lstname = (ListView) findViewById(R.id.lst_name);
}
private void Initialization() {
declaration();
_edtval.setText("Select Value");
connect = CONN("user","pass","db","server");
}
#SuppressLint("NewApi")
private Connection CONN(String _user, String _pass, String _DB,
String _server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String connURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connURL = "jdbc:jtds:sqlserver://" + _server + ";"
+ "databaseName=" + _DB + ";user=" + _user + ";password="
+ _pass + ";";
conn = DriverManager.getConnection(connURL);
} catch (SQLException se) {
Log.d("Error", se.getMessage());
// Toast.makeText(this, "Error : " + se,Toast.LENGTH_LONG).show();
} catch (ClassNotFoundException ce) {
Log.d("Error", ce.getMessage());
// Toast.makeText(this, "Error : " + ce,Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.d("Error", e.getMessage());
// Toast.makeText(this, "Error : " + e, Toast.LENGTH_LONG).show();
}
return conn;
}
public void QuerySQL(String COMANDOSQL) {
ResultSet rs;
try {
Statement statement = connect.createStatement();
rs = statement.executeQuery(COMANDOSQL);
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("A", rs.getString("Table Field 1"));
datanum.put("B", rs.getString("Table Field 2"));
data.add(datanum);
}
String[] from = { "A", "B" };
int[] views = { R.id.textView2, R.id.textView1 };
AD = new SimpleAdapter(this, data, R.layout.sql, from, views);
_lstname.setAdapter(AD);
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlservermain);
Initialization();
_btnenter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
QuerySQL(_edtval.getText().toString());
}
});
}
}
And now its time to give some permission in "AndroidManifest.xml"
which is
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
anjoy thats it for retriving.
the data.

Categories

Resources