I want to add a new button in my project that can delete some of the number and names that I saved.
I am totally new to Android Studio, so I donĀ“t know how to write my code that it will work the way I want it.
MainActivity(Register) :
public class MainActivity extends Activity {
EditText name,number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void display(View v) {
Intent i_view=new Intent(MainActivity.this,Display.class);
startActivity(i_view);
}
public void storeInDB(View v) {
Toast.makeText(getApplicationContext(), "Start Save",Toast.LENGTH_LONG).show();
name = (EditText) this.findViewById(R.id.textView1);
number = (EditText) this.findViewById(R.id.textView2);
String str_name=name.getText().toString();
String str_number=number.getText().toString();
SQLiteDatabase db;
db=openOrCreateDatabase("NumDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS details(name VARCHAR,number VARCHAR);");
Cursor c=db.rawQuery("SELECT * FROM details", null);
if(c.getCount()<20)
{
db.execSQL("INSERT INTO details VALUES('"+str_name+"','"+str_number+"');");
Toast.makeText(getApplicationContext(), "Save successfuly",Toast.LENGTH_SHORT).show();
}
db.close();
}
}
And Display :
public class Display extends Activity {
Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
SQLiteDatabase db;
db=openOrCreateDatabase("NumDB", Context.MODE_PRIVATE, null);
c=db.rawQuery("SELECT * FROM details", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found.");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append(" "+c.getString(0)+"\n");
buffer.append(" "+c.getString(1)+"\n");
}
showMessage("Contact", buffer.toString());
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
The code is working fine but I want to add a button that allows me to delete all the numbers and names that I saved,'your text'
Related
I am new in Java, I want to show the username value from my Table in SQLite Database after successful login into my TextView in layout activity_home.xml
I don't know how to get username value with my code here.
The code for my TextView in my activity_home.xml layout's
<TextView
android:id="#+id/nameuser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="18dp"
android:layout_marginTop="32dp"/>
And here's the code :
DBHelper
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "myapp.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_USERNAME + " TEXT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String username,String email,String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, username);
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String username, String email, String pass){
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_USERNAME + " = " + "'"+username+"'" + " and " + COLUMN_PASS + " = " + "'"+pass+"'";
if(email != null)
selectQuery += "and " + COLUMN_EMAIL + " = " + "'"+email+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
}
HomeActivity
public class HomeActivity extends AppCompatActivity {
TextView nameuser, walletuser, mainmenus,
pagetitle, pagesubtitle;
Button btnguide;
Animation atg, atgtwo, atgthree;
ImageView imageView3;
SharedPreferences sharedpreferences;
Intent intent;
private Session session;
TextView btnLogout, btnDaftarBarang, btnTambah;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new Session(this);
if(!session.loggedin()){
logout();
}
atg = AnimationUtils.loadAnimation(this, R.anim.atg);
atgtwo = AnimationUtils.loadAnimation(this, R.anim.atgtwo);
atgthree = AnimationUtils.loadAnimation(this, R.anim.atgthree);
nameuser = findViewById(R.id.nameuser);
walletuser = findViewById(R.id.walletuser);
btnDaftarBarang = (TextView) findViewById(R.id.btnDaftarBarang);
btnTambah = (TextView) findViewById(R.id.btnTambah);
btnLogout = (TextView) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
}
});
imageView3 = findViewById(R.id.imageView3);
mainmenus = findViewById(R.id.mainmenus);
pagetitle = findViewById(R.id.pagetitle);
pagesubtitle = findViewById(R.id.pagesubtitle);
btnguide = findViewById(R.id.btnguide);
btnguide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent a = new Intent(HomeActivity.this,PackageAct.class);
startActivity(a);
}
});
// pass an animation
imageView3.startAnimation(atg);
pagetitle.startAnimation(atgtwo);
pagesubtitle.startAnimation(atgtwo);
btnguide.startAnimation(atgthree);
btnTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent tambah = new Intent(HomeActivity.this, CrudActivity.class);
startActivity(tambah);
}
});
btnDaftarBarang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//start recordlist activity
startActivity(new Intent(HomeActivity.this, RecordListActivity.class));
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(HomeActivity.this,LoginActivity.class));
}
}
Session.java
public class Session {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context ctx;
public Session(Context ctx){
this.ctx = ctx;
prefs = ctx.getSharedPreferences("myapp", Context.MODE_PRIVATE);
editor = prefs.edit();
}
public void setLoggedin(boolean logggedin){
editor.putBoolean("loggedInmode",logggedin);
editor.commit();
}
public boolean loggedin(){
return prefs.getBoolean("loggedInmode", false);
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private Button login;
private EditText etUsername, etPass;
private DbHelper db;
private Session session;
TextView RegisterDisini;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new DbHelper(this);
session = new Session(this);
login = (Button)findViewById(R.id.btnLogin);
etUsername = (EditText)findViewById(R.id.etUsername);
etPass = (EditText)findViewById(R.id.etPass);
login.setOnClickListener(this);
RegisterDisini = (TextView) findViewById(R.id.RegisterDisini);
RegisterDisini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerHere = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerHere);
}
});
if(session.loggedin()){
startActivity(new Intent(LoginActivity.this,HomeActivity.class));
finish();
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
login();
break;
default:
}
}
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
}
1. Add the line, as per the comment, as below to the LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
public static final String INTENTEXTRAKEY_LOGGEDINUSERNAME = "iek_loggedinusername"; //<<<<<<<<<< ADDED THIS LINE
private Button login;
2. In LoginActivity Change your login method as below :-
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
//startActivity(new Intent(LoginActivity.this, HomeActivity.class)); <<<<<<<<< OLD CODE
Intent intent = new Intent(LoginActivity.this,HomeActivity.class); //<<<<<<<<<< NEW CODE
intent.putExtra(INTENTEXTRAKEY_LOGGEDINUSERNAME,username); //<<<<<<<<<< NEW CODE
startActivity(intent); //<<<<<<<<<< NEW CODE
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
3. In the HomeActivity add the line as commented :-
public class HomeActivity extends AppCompatActivity {
TextView nameuser, walletuser, mainmenus,
pagetitle, pagesubtitle;
Button btnguide;
Animation atg, atgtwo, atgthree;
ImageView imageView3;
SharedPreferences sharedpreferences;
Intent intent;
private Session session;
TextView btnLogout, btnDaftarBarang, btnTambah;
String loggedinusername; //<<<<<<<<<< ADDED
4. Also in HomeActivity add the line as commented :-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new Session(this);
loggedinusername = this.getIntent().getStringExtra(LoginActivity.INTENTEXTRAKEY_LOGGEDINUSERNAME); //<<<<<<<<<<ADDED
5. Again also in HomeActivity add the line as commented :-
atg = AnimationUtils.loadAnimation(this, R.anim.atg);
atgtwo = AnimationUtils.loadAnimation(this, R.anim.atgtwo);
atgthree = AnimationUtils.loadAnimation(this, R.anim.atgthree);
nameuser = findViewById(R.id.nameuser);
nameuser.setText(loggedinusername); //<<<<<<<<<< ADDED
Explanation
adds a constant for a value that will be used to define the key part of a key/value pair.
Adds an Intent Extra that has the constant as defined in 1 as the key and the username as the value.
Adds a class variable, loggedinusername, for the username (optional as you could get the Inten Extra directly, but this allows the username to be utilised elsewhere if need be.)
sets the loggedinusername variable according to the Intent Extra
sets the TextView to display the username as per the loggedinusername variable.
This is the recommended way of passing data from one activity to the next. You can pass many Intent Extras of varying types.
After login success pass username to your HomeActivity using intent
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
Intent intent=new Intent(this,HomeActivity.class);
intent.putExtra("username",username);
startActivity(intent);
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
// now get Username in HomeActivity like this
String username=getIntent().getStringExtra("username");
if(!TextUtils.isEmpty(username)){
// and set on your textview here
nameuser.setText(""+username);
}
Im trying to build an app that sets many alarm clocks and i want to save the alarms with an SQLite database. Already watched many tutorials for this but still having a problem using the database. Firstly i want to save the alarm one by one by pushing a button. I tried also to insert manually 2 alarms but it didnt worked either. What am i doing wrong? I am pretty new to this!
DBHelper Class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String ALARMS_TABLE_NAME = "alarms";
public static final String ALARMS_COLUMN_ID = "id";
public static final String ALARMS_COLUMN_HOUR = "hour";
public static final String ALARMS_COLUMN_MINUTES = "minutes";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 33);
}
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+ALARMS_TABLE_NAME+" ("+ALARMS_COLUMN_ID+ " INTEGER PRIMARY KEY , "+
ALARMS_COLUMN_HOUR+ " INTEGER, "+ALARMS_COLUMN_MINUTES+" INTEGER)");
InsertAlarms(db);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+ALARMS_TABLE_NAME);
onCreate(db);
}
void AddAlarm(Alarm alarm)
{
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(ALARMS_COLUMN_HOUR, alarm.getHour());
cv.put(ALARMS_COLUMN_MINUTES, alarm.getMinutes());
db.insert(ALARMS_TABLE_NAME, null, cv);
db.close();
}
Cursor getAllAlarms()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("SELECT * FROM "+ALARMS_TABLE_NAME,null);
return cur;
}
void InsertAlarms(SQLiteDatabase db) //insert manually 2 alarms
{
ContentValues cv=new ContentValues();
cv.put(ALARMS_COLUMN_ID, 1);
cv.put(ALARMS_COLUMN_HOUR, 20);
cv.put(ALARMS_COLUMN_MINUTES, 20);
db.insert(ALARMS_TABLE_NAME, null, cv);
cv.put(ALARMS_COLUMN_ID, 2);
cv.put(ALARMS_COLUMN_HOUR, 20);
cv.put(ALARMS_COLUMN_MINUTES, 20);
db.insert(ALARMS_TABLE_NAME, null, cv);
}
int getAlarmCount()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("Select * from "+ALARMS_TABLE_NAME, null);
int x= cur.getCount();
cur.close();
return x;
}
Class Alarm:
public class Alarm {
int _id;
int _hour;
int _minutes;
public Alarm(int Hour, int Minutes)
{
this._hour=Hour;
this._minutes=Minutes;
}
public int getID()
{
return this._id;
}
public void SetID(int ID)
{
this._id=ID;
}
public int getHour()
{
return this._hour;
}
public int getMinutes()
{
return this._minutes;
}
public void setHour(int Hour)
{
this._hour=Hour;
}
public void setMinutes(int Minutes)
{
this._minutes=Minutes;
}
Activity AddAlarm
public class AddAlarm extends Activity {
EditText txtHour;
EditText txtMinutes;
DBHelper dbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addalarm);
txtHour=(EditText)findViewById(R.id.txtHour);
txtMinutes=(EditText)findViewById(R.id.txtMinutes);
Button button1 = (Button)findViewById(R.id.addalarmbtn);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
btnAddAlarm_Click(v);
}
});
}
public void btnAddAlarm_Click(View view)
{
boolean ok=true;
try
{
int hour=Integer.parseInt(txtHour.getText().toString());
int minutes=Integer.parseInt(txtMinutes.getText().toString());
Alarm al=new Alarm(hour,minutes);
Toast.makeText(AddAlarm.this,"ADDED! ", Toast.LENGTH_LONG).show();
dbHelper.AddAlarm(al);
}
catch(Exception ex)
{
Toast.makeText(AddAlarm.this,"ERROR! ", Toast.LENGTH_LONG).show();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
Intent intent=getIntent();
DBHelper mydb;
TextView xupnitiria;
String hour;
public static boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.set_alarm_button);
//Bundle extras=intent.getExtras();
mydb=new DBHelper(this);
xupnitiria =(TextView)findViewById(R.id.xupnitiria);
xupnitiria.setText(xupnitiria.getText()+String.valueOf(mydb.getAlarmCount()));
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Intent a= new Intent(MainActivity.this, AddAlarm.class);
startActivity(a);
}
});
}
Errors on android Monitor
10-04 15:07:26.592 2625-2625/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection csk#8709fba that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection csk#8709fba that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1336)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1231)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1450)
at android.app.ContextImpl.bindService(ContextImpl.java:1422)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms:0)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms:1)
at bvq.run(:com.google.android.gms:9)
at bvn.run(:com.google.android.gms:10)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Add following in onCreate() of AddAlarm.java:
dbHelper=new DBHelper(this);
Also to see error log in logcat add following in try-catch block:
ex.printStackTrace();
AddAlarm Activity:
public class AddAlarm extends Activity {
EditText txtHour;
EditText txtMinutes;
DBHelper dbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addalarm);
txtHour = (EditText) findViewById(R.id.txtHour);
txtMinutes = (EditText) findViewById(R.id.txtMinutes);
dbHelper=new DBHelper(this);
Button button1 = (Button) findViewById(R.id.addalarmbtn);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnAddAlarm_Click(v);
}
});
}
public void btnAddAlarm_Click(View view) {
boolean ok = true;
try {
int hour = Integer.parseInt(txtHour.getText().toString());
int minutes = Integer.parseInt(txtMinutes.getText().toString());
Alarm al = new Alarm(hour, minutes);
Toast.makeText(AddAlarm.this, "ADDED! ", Toast.LENGTH_LONG).show();
dbHelper.AddAlarm(al);
} catch (Exception ex) {
Toast.makeText(AddAlarm.this, "ERROR! ", Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
}
I am trying to create a messaging app with several different xml views/classes:
one for the main menu (MainActivity);
one for the sending message screen (SendMsg);
one for storing sent messages (Logs).
In SendMsg, I want to store my message into an object called msgLog, which I had created in MainActivity. Just for testing, I have set SendMsg to display the Logs class upon pressing the SEND button, and the sent message does indeed appear there.
However, it is not storing it into the msgLog variable that I created, so that I can't access again from MainActivity.
How do I store it into a variable, so that it will always be there when I access it? Any help would be much appreciated.
=========================================================
public class MainActivity extends AppCompatActivity {
Logs msgLog = new Logs();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendOnClick (View view){
Intent intent = new Intent("com.example.android.attone.SendMsg");
startActivity(intent);
}
public void logsOnClick (View view){
Intent intent = new Intent(this, Logs.class);
startActivity(intent);
}
}
=========================================================
public class SendMsg extends AppCompatActivity {
EditText txtPhoneNo;
EditText txtMessage;
Button btnSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_msg);
txtPhoneNo = (EditText) this.findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) this.findViewById(R.id.txtMessage);
btnSend = (Button) this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// Get phone number and message sms
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
Intent writeLog = new Intent(getApplicationContext(), Logs.class);
writeLog.putExtra("link", message);
startActivity(writeLog);
// If phone number and message is not empty
if (phoneNo.length() > 0 && message.length() > 0)
{
sendMessage(phoneNo, message);
}
else
{
Toast.makeText(getBaseContext(), "Please enter both number and message", Toast.LENGTH_LONG).show();
}
}
});
}
// Function send message sms
private void sendMessage(String phoneNo, String message)
{
try
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "SMS failed. Please try again!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
=========================================================
public class Logs extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logs);
String logging = getIntent().getStringExtra("link");
TextView textView = (TextView) findViewById(R.id.txtLog);
textView.setText(logging);
Button log2menu = (Button)findViewById(R.id.logToMenu);
log2menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
You can use SharedPreferences to store such data.
One more thing you can try if you don't want to save the data after the app closes is storing the data in a static variable of a separate class.
In My android program I have NumberList.java with list_layout.xml
In xml there is a edit text field,and a button ..in edit text we can enter a phone number and with the button we can save..
But my requirement is I want to fetch the number from contacts and save them through a button..MainActivity.java is the program which fetchs the selected contact number..But I cant save as like NumberList.java.
How can I implement???
NumberList.java
public class NumberList extends Activity implements OnClickListener{
private RemindersDbAdapter mDbAdapter;
private EditText numbr;
private Button btnAdd;
private Button btnTree;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mDbAdapter=new RemindersDbAdapter(this);
mDbAdapter.open();
numbr=(EditText) findViewById(R.id.editNumber);
btnAdd=(Button) findViewById(R.id.btnSave);
btnAdd.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSave:
if((numbr.getText().toString()!=null)&&(numbr.getText().toString().length()>=7))
{ mDbAdapter.createReminder(numbr.getText().toString(), "", "");
mDbAdapter.close();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "plz enter correct number", Toast.LENGTH_SHORT).show();
}
default:
break;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mDbAdapter.close();
}}
and the another one which fetchs the contacts number from contact list
MainActivity.java
public class MainActivity extends Activity {
Button buttonReadContact;
TextView textPhone;
EditText ed;
final int RQS_PICKCONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonReadContact = (Button)findViewById(R.id.readcontact);
textPhone = (TextView)findViewById(R.id.phone);
ed = (EditText)findViewById(R.id.phno1);
buttonReadContact.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
//Start activity to get contact
final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK){
if(requestCode == RQS_PICKCONTACT){
Uri returnUri = data.getData();
Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);
if(cursor.moveToNext()){
int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = cursor.getString(columnIndex_ID);
int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
if(stringHasPhoneNumber.equalsIgnoreCase("1")){
Cursor cursorNum = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID,
null,
null);
//Get the first phone number
if(cursorNum.moveToNext()){
int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String stringNumber = cursorNum.getString(columnIndex_number);
ed.setText(stringNumber);
}
}else{
textPhone.setText("NO Phone Number");
}
}else{
Toast.makeText(getApplicationContext(), "NO data!", Toast.LENGTH_LONG).show();
}
}
}
}
}
this is what you need just create a table and with name and phone_no and fill db details in below code
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
readContacts(getApplicationContext());
}
});
public void readContacts(Context ctx, String no) {
ContentValues cvs cvs = new ContentValues();
Cursor phones = ctx.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
if (phones.getCount() > 0) {
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!TextUtils.isEmpty(phoneNumber)) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
cvs.put("name", name );
cvs.put("phone_no", phoneNumber );
}
}
}
insertItem(cvs, "readtables");
}
private void insertItem(ContentValues cbs, String Tablename) {
SQLiteDatabase db = dbl.getWritableDatabase();
try {
CreateTablenew(Tablename);
db.insert("Tablename", null, cbs);
} catch (SQLException e) {
}
}
MainActivity.java
public class MainActivity extends ListActivity implements OnGesturePerformedListener {
static SQLiteDatabase db;
public static String TABEl_CREATE="CONTACTS";
public static String DATA_BASE_TABLE_CREATE = "create table if not exists " +TABEl_CREATE+ "(Name text not null ,Number number unique not null)";
GestureLibrary lib;
private ArrayList<String> results = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = openOrCreateDatabase("contacts", MODE_PRIVATE, null);
db.execSQL(DATA_BASE_TABLE_CREATE);
lv = (ListView) findViewById (android.R.id.list);
populatelv();
lib = GestureLibraries.fromRawResource(this, R.raw.gestures);
if (!lib.load()) {
finish();
}
GestureOverlayView gesture = (GestureOverlayView)
findViewById(R.id.gestures);
gesture.addOnGesturePerformedListener(this);
}
private void populatelv() {
// TODO Auto-generated method stub
Cursor c = db.rawQuery("SELECT Name FROM " +TABEl_CREATE, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String Name = c.getString(c.getColumnIndex("Name"));
results.add( Name );
}while (c.moveToNext());
}
}
adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1,results);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
// TODO Auto-generated method stub
ArrayList<Prediction> predictions = lib.recognize(gesture);
if (predictions.size() > 0)
{
String action = predictions.get(0).name;
if (predictions.get(0).score > 1.0)
{
if ("ADD".equals(action))
{
Toast.makeText(this, "Adding a contact",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this,Database.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
else
if ("delete".equals(action))
{
Toast.makeText(this, "Removing a contact",Toast.LENGTH_SHORT).show();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
// Here,how can i get the position of the specific listitem where gesture action took place..?
// String str = lv.getItemAtPosition(arg2).toString();
//Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
// String delete = "delete from contacts where Name = '"+str+"'";
//db.execSQL(delete);
//Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
}
}) ;
}
else if ("refresh".equals(action))
{
Toast.makeText(this, "Reloading contacts",
Toast.LENGTH_SHORT).show();
}
}
}
}
}
Database.java
public class Database extends Activity {
Button add;
EditText name,number;
SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
db= MainActivity.db;
db = openOrCreateDatabase("contacts", MODE_PRIVATE, null);
add = (Button) findViewById(R.id.button1);
name = (EditText) findViewById(R.id.editText1);
number = (EditText) findViewById(R.id.editText2);
add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String nval,nbval;
nval = name.getText().toString();
nbval = number.getText().toString();
if(nval.length()>0 && nbval.length()>0)
{
ContentValues cv = new ContentValues();
cv.put("Name", nval);
cv.put("Number", nbval);
db.insert("CONTACTS","title", cv);
Toast.makeText(getApplicationContext(), "Inserted sucessfully",Toast.LENGTH_SHORT ).show();
}
else
{
Toast.makeText(getApplicationContext(), "Please fill all fields!!!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onBackPressed()
{
Intent intent=new Intent(Database.this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
};
}
Here,i'm trying to display contacts in listview by retrieving from database which is done by Database.java.I'm able add the contacts into database using gesture but when i tried to delete the specific contact from list using gesture,i can't able to do..I'm new to development of android applications..please suggest me..here is my code.