Am trying to create a database application that stores members details eg name, phone and email address. It up and working with all CRUD functionality; I can save data into the database, I can update and even delete. But now, I want to be able to get the details of a clicked list item and use it in a popup alert to make a call or send sms. Please assist me and keep in mind that am new in android coding. (the screenshot is attached.)
These is my main activity class Database.java
public class Database extends Activity {
private SimpleCursorAdapter dataAdapter;
private DatabaseHandler dbHelper;
final Activity activity = this;
Button add_btn;
ListView Contact_listview;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
Contact_Adapter cAdapter;
DatabaseHandler db;
String Toast_msg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
try {
Contact_listview = (ListView) findViewById(R.id.list);
Contact_listview.setItemsCanFocus(false);
add_btn = (Button) findViewById(R.id.add_btn);
Set_Referash_Data();
} catch (Exception e) {
// TODO: handle exception
Log.e("some error", "" + e);
}
add_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent add_user = new Intent(Database.this,
Add_Update_User.class);
add_user.putExtra("called", "add");
add_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(add_user);
finish();
}
}); //To hadle on item clicks
Contact_listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder optionsDialog = new AlertDialog.Builder(
Database.this);
optionsDialog.setTitle("Choose option").setCancelable(true);
LayoutInflater liOptions = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View optionsView = liOptions.inflate(R.layout.dialog_choose_option, null);
Button btCall = (Button) optionsView.findViewById(R.id.btCall);
Button btSMS = (Button) optionsView.findViewById(R.id.btSMS);
Button btEmail = (Button) optionsView
.findViewById(R.id.btEmail);
optionsDialog.setView(optionsView);
btCall.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// Call code here...
Log.i("Make call", "");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel: "));
try {
startActivity(callIntent);
finish();
Log.i("Finished making a call.", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Database.this,
"Call failed, please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
btSMS.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// SMS code here...
Uri smsUri = Uri.parse("sms:");
Intent smsIntent = new Intent(Intent.ACTION_VIEW, smsUri);
smsIntent.putExtra("sms_body", "my sms body here...");
startActivity(smsIntent);
}
});
btEmail.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Email code here.....
}
});
optionsDialog.show();
}
});
}
public void Set_Referash_Data() {
contact_data.clear();
db = new DatabaseHandler(this);
ArrayList<Contact> contact_array_from_db = db.Get_Contacts();
for (int i = 0; i < contact_array_from_db.size(); i++) {
int tidno = contact_array_from_db.get(i).getID();
String name = contact_array_from_db.get(i).getName();
String mobile = contact_array_from_db.get(i).getPhoneNumber();
String email = contact_array_from_db.get(i).getEmail();
Contact cnt = new Contact();
cnt.setID(tidno);
cnt.setName(name);
cnt.setEmail(email);
cnt.setPhoneNumber(mobile);
contact_data.add(cnt);
}
db.close();
cAdapter = new Contact_Adapter(Database.this, R.layout.listview_row,
contact_data);
Contact_listview.setAdapter(cAdapter);
cAdapter.notifyDataSetChanged();
}
public void Show_Toast(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Set_Referash_Data();
}
public class Contact_Adapter extends ArrayAdapter<Contact> {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public Contact_Adapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
super(act, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.name = (TextView) row.findViewById(R.id.user_name_txt);
holder.email = (TextView) row.findViewById(R.id.user_email_txt);
holder.number = (TextView) row.findViewById(R.id.user_mob_txt);
holder.edit = (Button) row.findViewById(R.id.btn_update);
holder.delete = (Button) row.findViewById(R.id.btn_delete);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.edit.setTag(user.getID());
holder.delete.setTag(user.getID());
holder.name.setText(user.getName());
holder.email.setText(user.getEmail());
holder.number.setText(user.getPhoneNumber());
holder.edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Intent update_user = new Intent(activity,
Add_Update_User.class);
update_user.putExtra("called", "update");
update_user.putExtra("USER_ID", v.getTag().toString());
activity.startActivity(update_user);
}
});
holder.delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
// TODO Auto-generated method stub
// show a message while loader is loading
AlertDialog.Builder adb = new AlertDialog.Builder(activity);
adb.setTitle("Delete?");
adb.setIcon(android.R.drawable.ic_menu_delete);
adb.setMessage("Are you sure you want to delete "+name+"");
final int user_id = Integer.parseInt(v.getTag().toString());
//the code for DELETE buttonn here
adb.setPositiveButton("Yes, delete",
new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// MyDataObject.remove(positionToRemove);
DatabaseHandler dBHandler = new DatabaseHandler(
activity.getApplicationContext());
dBHandler.Delete_Contact(user_id);
Database.this.onResume();
}
});
//the coce for cancel button here
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
return row;
}
class UserHolder {
TextView name;
TextView email;
TextView number;
Button edit;
Button delete;
}
}
}
The database handler class is here DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_EMAIL = "email";
private static final String SQLITE_TABLE ="contacts";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT," + KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
public void Add_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
values.put(KEY_EMAIL, contact.getEmail()); // Contact Email
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO, KEY_EMAIL }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
cursor.close();
db.close();
return contact;
}
// Getting All Contacts
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contact.setEmail(cursor.getString(3));
// Adding contact to list
contact_list.add(contact);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
// Updating single contact
public int Update_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
values.put(KEY_EMAIL, contact.getEmail());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void Delete_Contact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
db.close();
}
// Getting contacts Count
public int Get_Total_Contacts() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And my last class Add_Update_User.java is here
public class Add_Update_User extends Activity {
EditText add_name, add_mobile, add_email;
Button add_save_btn, add_view_all, update_btn, update_view_all;
LinearLayout add_view, update_view;
String valid_mob_number = null, valid_email = null, valid_name = null,
Toast_msg = null, valid_user_id = "";
int USER_ID;
DatabaseHandler dbHandler = new DatabaseHandler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_update_screen);
// set screen
Set_Add_Update_Screen();
// set visibility of view as per calling activity
String called_from = getIntent().getStringExtra("called");
if (called_from.equalsIgnoreCase("add")) {
add_view.setVisibility(View.VISIBLE);
update_view.setVisibility(View.GONE);
} else {
update_view.setVisibility(View.VISIBLE);
add_view.setVisibility(View.GONE);
USER_ID = Integer.parseInt(getIntent().getStringExtra("USER_ID"));
Contact c = dbHandler.Get_Contact(USER_ID);
add_name.setText(c.getName());
add_mobile.setText(c.getPhoneNumber());
add_email.setText(c.getEmail());
// dbHandler.close();
}
add_mobile.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// min lenth 10 and max lenth 12 (2 extra for - as per phone
// matcher format)
Is_Valid_Sign_Number_Validation(10, 12, add_mobile);
}
});
add_mobile
.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
add_email.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Is_Valid_Email(add_email);
}
});
add_name.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Is_Valid_Person_Name(add_name);
}
});
add_save_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// check the value state is null or not
if (valid_name != null && valid_mob_number != null
&& valid_email != null && valid_name.length() != 0
&& valid_mob_number.length() != 0
&& valid_email.length() != 0) {
dbHandler.Add_Contact(new Contact(valid_name,
valid_mob_number, valid_email));
Toast_msg = "Colleague's details saved successfully";
Show_Toast(Toast_msg);
Reset_Text();
}
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
valid_name = add_name.getText().toString();
valid_mob_number = add_mobile.getText().toString();
valid_email = add_email.getText().toString();
// check the value state is null or not
if (valid_name != null && valid_mob_number != null
&& valid_email != null && valid_name.length() != 0
&& valid_mob_number.length() != 0
&& valid_email.length() != 0) {
dbHandler.Update_Contact(new Contact(USER_ID, valid_name,
valid_mob_number, valid_email));
dbHandler.close();
Toast_msg = "Data Update successfully";
Show_Toast(Toast_msg);
Reset_Text();
} else {
Toast_msg = "Sorry Some Fields are missing.\nPlease Fill up all.";
Show_Toast(Toast_msg);
}
}
});
update_view_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent view_user = new Intent(Add_Update_User.this,
Database.class);
view_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(view_user);
finish();
}
});
add_view_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent view_user = new Intent(Add_Update_User.this,
Database.class);
view_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(view_user);
finish();
}
});
}
public void Set_Add_Update_Screen() {
add_name = (EditText) findViewById(R.id.add_name);
add_mobile = (EditText) findViewById(R.id.add_mobile);
add_email = (EditText) findViewById(R.id.add_email);
add_save_btn = (Button) findViewById(R.id.add_save_btn);
update_btn = (Button) findViewById(R.id.update_btn);
add_view_all = (Button) findViewById(R.id.add_view_all);
update_view_all = (Button) findViewById(R.id.update_view_all);
add_view = (LinearLayout) findViewById(R.id.add_view);
update_view = (LinearLayout) findViewById(R.id.update_view);
add_view.setVisibility(View.GONE);
update_view.setVisibility(View.GONE);
}
public void Is_Valid_Sign_Number_Validation(int MinLen, int MaxLen,
EditText edt) throws NumberFormatException {
if (edt.getText().toString().length() <= 0) {
edt.setError("Number Only");
valid_mob_number = null;
} else if (edt.getText().toString().length() < MinLen) {
edt.setError("Minimum length " + MinLen);
valid_mob_number = null;
} else if (edt.getText().toString().length() > MaxLen) {
edt.setError("Maximum length " + MaxLen);
valid_mob_number = null;
} else {
valid_mob_number = edt.getText().toString();
}
} // END OF Edittext validation
public void Is_Valid_Email(EditText edt) {
if (edt.getText().toString() == null) {
edt.setError("Invalid Email Address");
valid_email = null;
} else if (isEmailValid(edt.getText().toString()) == false) {
edt.setError("Invalid Email Address");
valid_email = null;
} else {
valid_email = edt.getText().toString();
}
}
boolean isEmailValid(CharSequence email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
} // end of email matcher
public void Is_Valid_Person_Name(EditText edt) throws NumberFormatException {
if (edt.getText().toString().length() <= 0) {
edt.setError("Accept Alphabets Only.");
valid_name = null;
} else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
edt.setError("Accept Alphabets Only.");
valid_name = null;
} else {
valid_name = edt.getText().toString();
}
}
public void Show_Toast(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public void Reset_Text() {
add_name.getText().clear();
add_mobile.getText().clear();
add_email.getText().clear();
}
}
And here is the screenshot [[http://ift.tt/15K6I3C ]]
Your help will be appreciated, thanks in advance!
Aucun commentaire:
Enregistrer un commentaire