I have been searching for hours but still I can't find any way on how to update a listview using the listview.setOnItemLongClickListener I have tried but I think I am doing it all wrong. Does anyone know how to edit a listview after a longclick listener?
DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static final String TEST_TABLE = "TEST_TABLE";
public static final String TEST_NAME = "NAME";
public static final String COLUMN_NAME = TEST_NAME;
public static final String COLUMN_ADDRESS = "ADDRESS";
public static final String COLUMN_ID = "ID";
public static final String TEST_AGE = "age";
public DBHelper(#Nullable Context context) {
super(context, "test.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTableStatement = "CREATE TABLE " + TEST_TABLE + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_ADDRESS + " TEXT)";
sqLiteDatabase.execSQL(createTableStatement);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public boolean addData(TestModel testModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME, testModel.getName());
cv.put(COLUMN_ADDRESS, testModel.getAddress());
long insert = db.insert(TEST_TABLE, null, cv);
if (insert == -1) {
return false;
} else {
return true;
}
}
public boolean deleteData(TestModel testModel) {
SQLiteDatabase db = this.getWritableDatabase();
String queryString = "DELETE FROM " + TEST_TABLE + " WHERE " + COLUMN_ID + " = " + testModel.getID();
Cursor cursor = db.rawQuery(queryString, null);
if (cursor.moveToFirst()) {
return true;
} else {
return false;
}
}
public void update(TestModel testModel) {
}
public List<TestModel> viewAll() {
List<TestModel> returnList = new ArrayList<>();
String queryString = "SELECT * FROM " + TEST_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
TestModel newTest = new TestModel(id, name, address);
returnList.add(newTest);
} while (cursor.moveToNext());
} else {
}
cursor.close();
db.close();
return returnList;
}
}
TestModel
public class TestModel {
private int ID;
private String name;
private String address;
public TestModel(int ID, String name, String address) {
this.ID = ID;
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "ID:" + ID +
", name:'" + name + '\'' +
", address:'" + address + '\'' +
'}';
}
public TestModel() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
MainActivity
package com.example.crudtest2;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btn_Add, btn_View;
EditText et_name, et_address, et_username;
ListView lv_allList;
ArrayAdapter testArrayAdapter;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_Add = findViewById(R.id.btnAdd);
btn_View = findViewById(R.id.btnView);
et_name = findViewById(R.id.inputName);
et_address = findViewById(R.id.inputAddress);
lv_allList = findViewById(R.id.listviewData);
dbHelper = new DBHelper(MainActivity.this);
showAllData(dbHelper);
btn_Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TestModel testModel;
try {
testModel = new TestModel(-1, et_name.getText().toString(), et_address.getText().toString());
Toast.makeText(MainActivity.this, "Successfully Added", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error adding", Toast.LENGTH_SHORT).show();
testModel = new TestModel(-1, "error", "error");
}
DBHelper dbHelper = new DBHelper(MainActivity.this);
dbHelper.addData(testModel);
showAllData(dbHelper);
}
});
btn_View.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DBHelper dbHelper = new DBHelper(MainActivity.this);
showAllData(dbHelper);
//Toast.makeText(MainActivity.this, dbHelper.viewAll().toString(), Toast.LENGTH_SHORT).show();
}
});
lv_allList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TestModel clickedData = (TestModel) adapterView.getItemAtPosition(i);
dbHelper.deleteData(clickedData);
showAllData(dbHelper);
Toast.makeText(MainActivity.this, "Data Deleted Successfully", Toast.LENGTH_SHORT).show();
}
});
lv_allList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
TestModel clickedData = (TestModel) adapterView.getItemAtPosition(i);
dbHelper.updateData(clickedData);
return true;
}
});
}
private void showAllData(DBHelper dbHelper) {
testArrayAdapter = new ArrayAdapter<TestModel>(MainActivity.this, android.R.layout.simple_list_item_1, dbHelper.viewAll());
lv_allList.setAdapter(testArrayAdapter);
}
}
Is there like any way to edit my listview once a longclick listener event has happened? I have tried doing the same thing with delete it's because I don't have really any idea how to edit a listview after a longclick.
I've existing database that have name, surname, email phone and password and I want to use that to make login activity that have two edit text (Email or phone number) & (password).
What is the code behind the login activity??
Login (if succeed get the other data)----> ParentsMenu (use the data)
DatabaseHelper.java
package edu.angelo.parentsportal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Parents_Portal.db";
public static final String TABLE_NAME = "Parents_Table";
public static final String COL_0 = "ID";
public static final String COL_1 = "NAME";
public static final String COL_2 = "SURNAME";
public static final String COL_3 = "EMAIL_ADDRESS";
public static final String COL_4 = "PHONE_NUMBER";
public static final String COL_5 = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, EMAIL_ADDRESS TEXT, PHONE_NUMBER TEXT, PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String email_address, String phone_number, String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,surname);
contentValues.put(COL_3,email_address);
contentValues.put(COL_4,phone_number);
contentValues.put(COL_5,password);
long result = db.insert(TABLE_NAME, null , contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public ArrayList<ParentModel> getAllParentsData(){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
public void updateData(int id, String name , String surname , String email , String phone_number , String password){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.update(TABLE_NAME, contentValues, COL_0 + "=" + id, null);
mydb.close();
}
public void deleteParent(int id){
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.delete(TABLE_NAME, COL_0 + "=" + id, null);
mydb.close();
}
}
existing LoginActivity.java
package edu.angelo.parentsportal;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText editTextEmailPhone;
private EditText editTextPassword;
private Button Login;
private ProgressDialog progressDialog;
DatabaseHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmailPhone = findViewById(R.id.input_username);
editTextPassword = findViewById(R.id.input_password);
findViewById(R.id.btn_register).setOnClickListener(Login.this);
progressDialog = new ProgressDialog(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_register: {
userLogin();
break;
}
}
}
private void userLogin() {
String email = editTextEmailPhone.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmailPhone.setError("Email is required");
editTextEmailPhone.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
editTextEmailPhone.setError("Please enter valid email");
editTextEmailPhone.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length()<6 ){
editTextPassword.setError("Minimum of length of password should be 6");
editTextPassword.requestFocus();
return;
}
//if the email&pass is not empty
//display dialog
else {
progressDialog.setMessage("Please Wait...");
progressDialog.show();
if ((email.equals("parent#gmail.com")) && (password.equals("123456")))
{
progressDialog.dismiss();
SharedPrefs.saveSharedSetting(this, "CaptainCode", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
else {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
}
Add this function to your DatabaseHelper.java
public boolean userExistance(String emailOrPhone, String pwd){
String sql = "select * from " + TABLE_NAME + " where ("+ COL_3 +" = " + emailOrPhone +" OR "+ COL_4 +" = "+ emailOrPhone+ ") AND " + COL_5 + " = " + pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if(cursor.getCount() > 0)
return true;
else
return false;
}
Then add call this function from your LoginActivity.java
DatabaseHelper mydb;
mydb = new DatabaseHelper(LoginActivity.this);
boolean exists = mydb.userExistance();
if(exists)
{
Intent intent = new Intent(Login.this, Parent_Home.class);
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
Add below method in your DatabaseHelper class.
public ArrayList<ParentModel> getParentData(String emailOrPhone,String pwd){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "SELECT * FROM " + TABLE_NAME+" WHERE ("+COL_3+"= "+emailOrPhone+" OR "+COL_4 +" = "+emailOrPhone+") AND "+COL_5 +" = "+pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
And use like below code :
if (mydb.getParentData(editTextEmailPhone.getText().toString(),editTextPassword.getText().toString()).size()>0)
{
progressDialog.dismiss();
SharedPrefs.saveSharedSetting(this, "CaptainCode", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
Don't forget to initialization DatabaseHelper mydb.
My Parent_home Activity needs data (name, surname, id) from the logged in user, my login activity can only check if the database has the parent(user) credential, and I want after checking if have parent in login activity, parent data from the database gonna given to the Parent_home Activity
DatabaseHelper.java
package edu.angelo.parentsportal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Parents_Portal.db";
public static final String TABLE_NAME = "Parents_Table";
public static final String COL_0 = "ID";
public static final String COL_1 = "NAME";
public static final String COL_2 = "SURNAME";
public static final String COL_3 = "EMAIL_ADDRESS";
public static final String COL_4 = "PHONE_NUMBER";
public static final String COL_5 = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, EMAIL_ADDRESS TEXT, PHONE_NUMBER TEXT, PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String email_address, String phone_number, String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,surname);
contentValues.put(COL_3,email_address);
contentValues.put(COL_4,phone_number);
contentValues.put(COL_5,password);
long result = db.insert(TABLE_NAME, null , contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public ArrayList<ParentModel> getAllParentsData(){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
public void updateData(int id, String name , String surname , String email , String phone_number , String password){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.update(TABLE_NAME, contentValues, COL_0 + "=" + id, null);
mydb.close();
}
public void deleteParent(int id){
SQLiteDatabase mydb = this.getWritableDatabase();
mydb.delete(TABLE_NAME, COL_0 + "=" + id, null);
mydb.close();
}
public ArrayList<ParentModel> getParentLoginData(String emailOrPhone,String pwd){
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "SELECT * FROM " + TABLE_NAME+" WHERE ("+COL_3+"= "+emailOrPhone+" OR "+COL_4 +" = "+emailOrPhone+") AND "+COL_5 +" = "+pwd;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext());
}
return list;
}
}
Login.java
package edu.angelo.parentsportal;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText editTextEmailPhone;
private EditText editTextPassword;
private Button Login;
private ProgressDialog progressDialog;
DatabaseHelper mydb;
SQLiteDatabase sqLiteDatabase;
CustomAdapter customAdapter;
Cursor cursor;
ArrayList<ParentModel> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmailPhone = findViewById(R.id.input_username);
editTextPassword = findViewById(R.id.input_password);
findViewById(R.id.btn_register).setOnClickListener(Login.this);
progressDialog = new ProgressDialog(this);
mydb =new DatabaseHelper(this);
sqLiteDatabase = mydb.getReadableDatabase();
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_register: {
userLogin();
break;
}
}
}
private void userLogin() {
String email = editTextEmailPhone.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmailPhone.setError("Email or Phone Number is required");
editTextEmailPhone.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length()<6 ){
editTextPassword.setError("Minimum of length of password should be 6");
editTextPassword.requestFocus();
return;
}
//if the email&pass is not empty
//display dialog
else{
progressDialog.setMessage("Please Wait...");
progressDialog.show();
if (mydb.getParentLoginData(editTextEmailPhone.getText().toString(),editTextPassword.getText().toString()).size()>0) {
progressDialog.dismiss();
DatabaseHelper mydb = new DatabaseHelper(this);
SharedPrefs.saveSharedSetting(this, "CaptainCode", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
// intent or something to forward the data from the selected parent row from the database
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
else {
Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
return;
}
}
}
}
ParentModel.java (if needed)
package edu.angelo.parentsportal;
public class ParentModel {
public String ID;
public String Name;
public String Surname;
public String Email;
public String Phone_number;
public String Password;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone_number() {
return Phone_number;
}
public void setPhone_number(String phone_number) {
Phone_number = phone_number;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
You can pass the values to the activity using Intent Extras when starting an activity via an Intent.
So you use something like :-
ArrayList<ParentModel> parents = mydb.getParentLoginData(editTextEmailPhone.getText().toString(),editTextPassword.getText().toString());
if (parents.size()>0) {
progressDialog.dismiss();
DatabaseHelper mydb = new DatabaseHelper(this);
SharedPrefs.saveSharedSetting(this, "CaptainCode", "false");
Intent intent = new Intent(Login.this, Parent_Home.class);
intent.putExtra("IK_CURRENTPARENTID",parents[0].getId());
intent.putExtra("IK_CURRENTPARENTNAME",parents[0].getName());
intent.putExtra("IK_CURRENTPARENTSURNAME",parents[0].getSurname();
// intent or something to forward the data from the selected parent row from the database
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
You then retrieve the values from the Intent Extras in the Parent_Home activity. using something like in the onCreate method :-
currentId = getIntent().getStringExtra("IK_CURRENTPARENTID");
currentName = getIntent().getStringExtra("IK_CURRENTPARENTNAME");
currentSurName = getIntent().getStringExtra("IK_CURRENTPARENTSURNAME");
noting that the above assumes that currentId, currentName and currentSurName have been declared as class variables.
typically you'd also define constants for the Intent Extra keys rater than hard coding them.
The above is in-principle code, it hasn't been run or tested and may therefore contain some errors.
public void onSignUpClick(View v){
if(v.getId() == R.id.btnRegister)
{
EditText name = (EditText)findViewById(R.id.TFname);
EditText email = (EditText)findViewById(R.id.TFemail);
EditText pass1 = (EditText)findViewById(R.id.TFpass1);
EditText pass2 = (EditText)findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = name.getText().toString();
String pass1str = name.getText().toString();
String pass2str = name.getText().toString();
if(!pass1str.equals(pass2str))
{
//popup msg:
Toast tpass = Toast.makeText(signup.this, "passwords don't match", Toast.LENGTH_LONG);
tpass.show();
}
else
{
//insert the details in DB:
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setPass(pass1str);
helper.insertContact(c);
}
}
}
I'm trying to make a signup form linked to sqlite database. the registraion button that's linked to onSignUpClick method doesn't work. any help to fix this error?
I have implemented a similar functionality to my app.. You can use this as a reference.You need to add whatever elements needed for your signup activity.
1. Create a database handler for your sqlite application.(DatabaseHandler.java)
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context, Object name,
Object factory, int version) {
// TODO Auto-generated constructor stub
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
String password;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Mydatabase.db";
// Contacts table name
private static final String TABLE_REGISTER= "register";
public static final String KEY_EMAIL_ID="email_id";
public static final String KEY_MOB_NO = "mobile_number";
public static final String KEY_PASSWORD = "password";
public static final String CREATE_TABLE="CREATE TABLE " + TABLE_REGISTER + "("
+ KEY_EMAIL_ID+ " TEXT,"
+ KEY_MOB_NO + " TEXT," + KEY_PASSWORD + " TEXT " + ")";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
onCreate(db);
}
void addregister(UserRegister registerdata)
// code to add the new register
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EMAIL_ID, registerdata.getEmailId());//register email id
values.put(KEY_MOB_NO, registerdata.getMobNo());//register mobile no
values.put(KEY_PASSWORD, registerdata.getPassword());
// Inserting Row
db.insert(TABLE_REGISTER, null, values);
db.close(); // Closing database connection
}
//code to get the register
String getregister(String username){
SQLiteDatabase db = this.getReadableDatabase();
//String selectquery="SELECT * FROM TABLE_REGISTER";
Cursor cursor=db.query(TABLE_REGISTER,null, "email_id=?",new String[]{username},null, null, null, null);
if(cursor.getCount()<1){
cursor.close();
return "Not Exist";
}
else if(cursor.getCount()>=1 && cursor.moveToFirst()){
password = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD));
cursor.close();
}
return password;
}
public String getDatabaseName() {
return DATABASE_NAME;
}
public static String getTableContacts() {
return TABLE_REGISTER;
}
public static int getDatabaseVersion() {
return DATABASE_VERSION;
}
}
2. Create a modal class UserRegister
public class UserRegister {
//private variables
String email_id;
String mobile_number;
String password;
// Empty constructor
public UserRegister(){}
// constructor
public UserRegister( String email_id,String mobile_number, String password){
this.email_id=email_id;
this.mobile_number=mobile_number;
this.password = password;
}
public String getEmailId() {
return email_id;
}
public void setEmailId(String email_id){
this.email_id = email_id;
}
public String getMobNo() {
// TODO Auto-generated method stub
return mobile_number;
}
public void setMobNo(String mobile_number){
this.mobile_number=mobile_number;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.Create the RegistrationActivity
public class Registration_Activity extends AppCompatActivity {
EditText reg_email,reg_phone,reg_password;
Button reg_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final DatabaseHandler db = new DatabaseHandler(this, null, null, 2);
reg_email = (EditText)findViewById(R.id.reg_email);
reg_phone = (EditText)findViewById(R.id.reg_phone);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_button = (Button)findViewById(R.id.reg_button);
final String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = reg_email.getText().toString();
String phone = reg_phone.getText().toString();
String password = reg_password.getText().toString();
if (email.matches(emailPattern)) {
DatabaseHandler db = new DatabaseHandler(Registration_Activity.this, null, null, 2);
UserRegister userRegister = new UserRegister();
userRegister.setEmailId(email);
userRegister.setMobNo(phone);
userRegister.setPassword(password);
db.addregister(userRegister);
Toast.makeText(getApplicationContext(), "Account Created", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration_Activity.this, Login_Activity.class);
startActivity(intent);
Registration_Activity.this.finish();
}
else
{
Toast.makeText(getApplicationContext(),"Enter a valid Email Address",Toast.LENGTH_SHORT).show();
}
}
});
}
}
4. Login_Activity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login_Activity extends AppCompatActivity {
TextView signup;
String email,password;
EditText log_username,log_password;
Button login_button;
DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signup = (TextView)findViewById(R.id.signup);
String htmlString="<u>Signup</u>";
signup.setText(Html.fromHtml(htmlString));
log_username = (EditText)findViewById(R.id.log_username);
log_password = (EditText)findViewById(R.id.log_password);
login_button = (Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db=new DatabaseHandler(Login_Activity.this, null, null, 2);
email = log_username.getText().toString();
password = log_password.getText().toString();
String StoredPassword =db.getregister(email);
if(password.equals(StoredPassword)){
Toast.makeText(getApplicationContext(),"Login Successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login_Activity.this,VideoActivity.class);
startActivity(intent);
Login_Activity.this.finish();
}
else{
Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
log_username.setText("");
log_password.setText("");
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login_Activity.this,Registration_Activity.class);
startActivity(intent);
Login_Activity.this.finish();
}
});
}
}
I am creating an android app (still the basic structure, without any design) from an Job site through XML feed using REST api.
Till now, I could managed to parse the XML data, displaying the List View with an POP UP menu item on each row. I am passing Data from PostBaseAdapter to MarkAsFav class. Could You please tell me if I am doing right or not? coz, I am getting no any data saved in database
Now, I have a problems:
I have 3 pop up menu item:
1. Set as Favourite
2. Share on Fb
3. email to Your friend
I am working on point number-1.
For now,I would be saving the data in SQLite Database itself. so, I am passing all the data (all the details about the job with all rows) to another activity, more over I am accepting a user given name to save the details through insertDB() in my Database.
But, unfortunately , nothing is getting saved in the database .
Can you tell me, if the data is getting passed or not and if the datas are being saved in database or not?
Please help me out. Please tell me where and how to modify the code?
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
MarkAsFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
Intent extras = getIntent();
if (extras != null) {
int Value = extras.getIntExtra("id",0);
if (Value > 0) {
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.JOBS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText((CharSequence) nam);
header.setFocusable(false);
header.setClickable(false);
}
}
}
public void run(View view) {
Intent extras = getIntent();
if (extras != null) {
int val = extras.getIntExtra("id",0);
String value1 = extras.getStringExtra("title");
String value2= extras.getStringExtra("company");
String value3= extras.getStringExtra("city");
String value4= extras.getStringExtra("state");
String value5= extras.getStringExtra("country");
String value6= extras.getStringExtra("formattedLocation");
String value7= extras.getStringExtra("source");
String value8= extras.getStringExtra("date");
String value9= extras.getStringExtra("snippet");
String value10= extras.getStringExtra("url");
String value11= extras.getStringExtra("onmousedown");
String value12= extras.getStringExtra("lattitude");
String value13= extras.getStringExtra("longitude");
String value14= extras.getStringExtra("jobkey");
String value15= extras.getStringExtra("sponsored");
String value16= extras.getStringExtra("expired");
String value17= extras.getStringExtra("formattedLocationFull");
String value18= extras.getStringExtra("formattedRelativeTime");
String headerValue = header.getText().toString();
Log.e("ERROR", "Inside run and checking Value and val");
if (val > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)) {
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
PostBaseAdapter.java
public class PostBaseAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ArrayList<Result> resultList;
private MainActivity mActivity;
private Context mContext;
String TAG="";
public PostBaseAdapter(Context context, ArrayList<Result> resultList) {
this.layoutInflater = LayoutInflater.from(context);
this.resultList = resultList;
this.mContext= context;
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Result getItem(int i) {
return resultList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int j=i;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_post, null);
//viewHolder = new ViewHolder(convertView);
viewHolder= new ViewHolder();
//View overFlow = convertView.findViewById(R.id.id_overflow);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.imageClick= (ImageView) convertView.findViewById(R.id.id_overflow);
convertView.setTag(viewHolder);
//overFlow.setOnClickListener(new OverflowSelectedListener(mContext, mActivity));
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Result result = resultList.get(i);
viewHolder.tvTitle.setText(result.getJobtitle());
final String jobTitle=resultList.get(i).getJobtitle();
final String company= resultList.get(i).getCompany();
final String city= resultList.get(i).getCity();
final String state= resultList.get(i).getState();
final String country= resultList.get(i).getCountry();
final String formattedLocation= resultList.get(i).getFormattedLocation();
final String source=resultList.get(i).getSource();
final String date= resultList.get(i).getDate();
final String snippet= resultList.get(i).getSnippet();
final String url= resultList.get(i).getUrl();
final String onmousedown= resultList.get(i).getOnmousedown();
final String lattitude= resultList.get(i).getLattitude();
final String longitude= resultList.get(i).getLongitude();
final String jobkey= resultList.get(i).getJobkey();
final String sponsored= resultList.get(i).getSponsored();
final String expired= resultList.get(i).getExpired();
final String formattedLocaionfull= resultList.get(i).getFormattedLocation();
final String formattedRelativeTime= resultList.get(i).getFormattedRelativeTime();
try {
viewHolder.imageClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.id_overflow:
final PopupMenu popup = new PopupMenu(mContext, v);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
// Force icons to show
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int id_To_Search = j + 1;
/*Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtras(dataBundle);
mContext.startActivity(intent);*/
switch (item.getItemId()) {
case R.id.email_whatsapp:
doEmailOrWhatsapp(mActivity);
return true;
case R.id.share_on_fb:
shareOnFb(mActivity);
return true;
case R.id.mark_as_fav:
//viewHolder.
//dataBundle.putString("name", result.getJobtitle());
Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtra("id",0);
intent.putExtra("title", jobTitle );
intent.putExtra("company",company );
intent.putExtra("city", city);
intent.putExtra("state",state );
intent.putExtra("country",country );
intent.putExtra("formattedLocation",formattedLocation );
intent.putExtra("source",source );
intent.putExtra("date", date);
intent.putExtra("snippet", snippet);
intent.putExtra("url", url);
intent.putExtra("onmousedown",onmousedown );
intent.putExtra("lattitude", lattitude);
intent.putExtra("longitude",longitude );
intent.putExtra("jobkey", jobkey);
intent.putExtra("sponsored",sponsored );
intent.putExtra("expired", expired);
intent.putExtra("formattedLocationFull",formattedLocaionfull );
intent.putExtra("formattedRelativeTime",formattedRelativeTime );
//intent.putExtras(dataBundle);
mContext.startActivity(intent);
return true;
default:
break;
}
return true;
}
});
//popup.show();
break;
default:
break;
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
TextView tvTitle;//, tvPublishDate;
ImageView imageClick;
/* public ViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);*/
// imageClick=(ImageView)item.findViewById(R.id.id_overflow);
// tvPublishDate = (TextView) item.findViewById(R.id.tvPublishDate);
}
}
mark-fav-layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<EditText
android:id="#+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="text" >
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="#string/save" />
</LinearLayout>
Result.java
public class Result {
public String jobtitle;
public String company;
public String city;
public String state;
public String country;
public String formattedLocation;
public String source;
public String date;
public String snippet;
public String url;
public String onmousedown;
public String lattitude;
public String longitude;
public String jobkey;
public String sponsored;
public String expired;
public String formattedLocationFull;
public String formattedRelativeTime;
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFormattedLocation() {
return formattedLocation;
}
public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getJobkey() {
return jobkey;
}
public void setJobkey(String jobkey) {
this.jobkey = jobkey;
}
public String getSponsored() {
return sponsored;
}
public void setSponsored(String sponsored) {
this.sponsored = sponsored;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getFormattedLocationFull() {
return formattedLocationFull;
}
public void setFormattedLocationFull(String formattedLocationFull) {
this.formattedLocationFull = formattedLocationFull;
}
public String getFormattedRelativeTime() {
return formattedRelativeTime;
}
public void setFormattedRelativeTime(String formattedRelativeTime) {
this.formattedRelativeTime = formattedRelativeTime;
}
public String getDetails() {
String result = jobtitle + ": " + company + "\n" + city + "-" + state
+ "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
"\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
+jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
return result;
}
}
I have just updated my code and its working fine for me. I am posting it here ,so that anyone can use if needed.
MarkFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
mydb.getWritableDatabase();
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
if (value > 0) {
//means this is the view part not the add contact part.
/* Cursor rs = mydb.getData(value);
id_To_Update = value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText( nam);
header.setFocusable(false);
header.setClickable(false);*/
}
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
String headerValue = header.getText().toString();
String value1 = extras.getString("title");
String value2 = extras.getString("company");
String value3 = extras.getString("city");
String value4 = extras.getString("state");
String value5 = extras.getString("country");
String value6 = extras.getString("formattedLocation");
String value7 = extras.getString("source");
String value8 = extras.getString("date");
String value9 = extras.getString("snippet");
String value10= extras.getString("url");
String value11= extras.getString("onmousedown");
String value12= extras.getString("lattitude");
String value13= extras.getString("longitude");
String value14= extras.getString("jobkey");
String value15= extras.getString("sponsored");
String value16= extras.getString("expired");
String value17= extras.getString("formattedLocationFull");
String value18= extras.getString("formattedRelativeTime");
Log.e("ERROR", "Inside run and checking Value and val");
if (value > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
/* public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);*/
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" Text, "+JOBS_COLUMN_NAME+" Text,"+JOBS_COLUMN_COMPANY+" Text, "+JOBS_COLUMN_CITY+" Text, "+JOBS_COLUMN_STATE+" Text, "+JOBS_COLUMN_COUNTRY+" Text,"+JOBS_COLUMN_FORMATEDLOCATION+" Text,"+JOBS_COLUMN_SOURCE+" Text,"+JOBS_COLUMN_DATE+" Text,"+JOBS_COLUMN_SNIPPET+" Text,"+JOBS_COLUMN_COMPANY+" Text,"+JOBS_COLUMN_URL+"Text,"+JOBS_COLUMN_ONMOUSEDOWN+" Text,"+JOBS_COLUMN_LATTITUDE+" Text,"+JOBS_COLUMN_LONGITUDE+"Text,"+JOBS_COLUMN_JOBKEY+" Text,"+JOBS_COLUMN_SPONSORED+" Text,"+JOBS_COLUMN_EXPIRED+" Text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" Text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" Text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
/* public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}*/
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}