insert to database and automatically update listview - android

i ve created a project with a single activity in android and i want to add a new record to database by pressing "insert button" as i showed in picture, but i want as soon as the New record saved to database , ListView updates and show the added record to the list in the last position...
when i run this code unexpected error occures and it close
where is the error or any suggestion ...
i put all the codes and layout here...
MainActivity.java
package com.example.db;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button Btninser;
SQLiteDatabase db;
EditText etName, etPhone;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
etPhone = (EditText) findViewById(R.id.etPhone);
Btninsert = (Button) findViewById(R.id.btnInsert);
lv = (ListView) findViewById(R.id.listView1);
Btninsert.setOnClickListener(this);
Open_Create();
}
public void Open_Create() {
db = openOrCreateDatabase("MyDB1", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS MyTable (_id INTEGER PRIMARY KEY AUTOINCREMENT, LastName VARCHAR,Phone VARCHAR);");
}
public void Insert_Info() {
db.execSQL("INSERT INTO MyTable (LastName,Phone) VALUES('" + etName.getText().toString()
+ "','" + etPhone.getText().toString() + "');");
Populate_ListView();
// db.close();
Toast.makeText(this, "Data has been saved!", Toast.LENGTH_LONG).show();
}
public void Populate_ListView() {
Cursor cursor = db.rawQuery("SELECT LastName,Phone FROM MyTable", null);
startManagingCursor(cursor);
String[] from = new String[] { "LastName", "Phone" };
int[] to = new int[] { R.id.tvItemListName, R.id.tvItemListPhone };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item_list, cursor, from, to);
lv.setAdapter(adapter);
}
And here is the XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Name" />
<EditText
android:id="#+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Phone" />
<EditText
android:id="#+id/etPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:ems="10" >
</EditText>
<Button
android:id="#+id/btnInsert"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Insert" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="21dp" >
</ListView>
</RelativeLayout>
I ve added the error from DDMS also
as you can see in Error page It mentioned a field "_id" that i never had it!!!! :(
confusing me too much...

If you want to use a Cursor, Android automatically assumes that your tables have a column called _id which acts as the row's unique primary identifier, for more details on that see the "Class Overview" section of the CursorAdapter's documentation which says:
Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.
Basically all you need to do is replace your CREATE TABLE call with:
db.execSQL("CREATE TABLE IF NOT EXISTS MyTable (_id INTEGER PRIMARY KEY AUTOINCREMENT, LastName VARCHAR,Phone VARCHAR);");
That should fix your crash. To get it to automatically refresh the list, see my comment regrading notifyDatasetChanged().
And as a sidenote: I'd strongly recommend using a SQLiteOpenHelper instance to handle the opening and creation of your tables, rather than what you are doing now, it's bad form to repeatedly call CREATE TABLE IF NOT EXISTS where you could only call it the one time you know it'd need to be called. Vogella.com has a great guide on that.
Edit: Based on your last edit of your code: You're still not requesting the _id field that you made. If you don't have it in your SELECT statement the cursor can't access it!
Replace your rawQuery in Populate_ListView with SELECT * FROM MyTable so that the _id field is also returned by the cursor.

Have you try to delete Open_Create() call from onClick() method? You have two consecutive call to openOrCreateDatabase() without any close() in the middle. Don't forget the try { ... } catch (SQLiteException) { ... }. You test.

Related

How can I insert a new contact by using ContentProviderOperation

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"/>

In android studio, sqlite database is not created but no error in my code

At first I got a message "cant build to local 8600 for debugger" then someone says to update the jre version from 7 to 8, then I got a message like "device does not match the local build on disk" then afterwards My code runs without any message, but database is not created. here is my mainclass,
package com.kaizen.sqlitedatabase;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
Sqlite mydb;
TextView name,surName,marks;
EditText edtName,edtSurName,edtMarks;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb=new Sqlite(this);
name=(TextView)findViewById(R.id.name);
surName=(TextView)findViewById(R.id.surName);
marks=(TextView)findViewById(R.id.marks);
edtName=(EditText)findViewById(R.id.edt_name);
edtSurName=(EditText)findViewById(R.id.edt_surName);
edtMarks=(EditText)findViewById(R.id.edt_marks);
}
}
Here is my subclass of sqlite openhelper,please somebody help me
package com.kaizen.sqlitedatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Naveen on 05-10-2016.
*/
public class Sqlite extends SQLiteOpenHelper{
public static final String DATABASENAME="STUDENTS_DATABASE.db";
public static final String TABLENAME="STUDENTS_MARKS";
public static final String COL_1="ID";
public static final String COL_2="STUDENT_NAME";
public static final String COL_3="SUR_NAME";
public static final String COL_4="MARKS";
public Sqlite(Context context) {
super(context, DATABASENAME, null, 1);
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLENAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER) ");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLENAME);
onCreate(db);
}
}
This is my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kaizen.sqlitedatabase.MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:text="Name"
android:id="#+id/name" />
<EditText
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:id="#+id/edt_name" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:id="#+id/surName"
android:text="Sur Name" />
<EditText
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:id="#+id/edt_surName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="match_parent"
android:id="#+id/marks"
android:text="Marks" />
<EditText
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:id="#+id/edt_marks" />
</LinearLayout>
<Button
android:text="Add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_marginTop="60dp"
/>
</LinearLayout>
Use this query to create table, i think problem is in your query
String CREATE_TABLE_CITY = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY , " + NAME+ " TEXT, " + SURNAMENAME+ " TEXT, " + MARKS+ " INTEGER )";
mDatabase.execSQL(CREATE_TABLE_CITY);
you want to check your database is create or not then go...
Tools > Android > Android Device Monitor
Click on your device on the left.
Go to File Explorer (one of the tabs on the right), go to /data/data/databases
Select the database by just clicking on it.
in new version of android studio you can check database create or not.
Click on:
View > Tool Windows > File Explorer > data > data > find your application name > database
Actually the SQLiteOpenHelper is that it doesn't call the onCreate method by only creating its object.
Whenever you try to access the database for retrieving or inserting data, if the database is not already created, it will call the onCreate method for the first time.
The onUpgrade method will be called if the database is available but the version is lower than the one you provide.
So that please try to run some queries and then check the database is created.
Database created location is
View -> Tool Windows -> Device file Explorer -> data -> data -> -> database

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.

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