Database saving all the details rather than the image - android

Im writing a simple app to save contacts in a list.
My database is working fine, but when Im restarting the app or updating a contact's details(even when im not updating an image), all the Images are not visible again.
There's something I missed along the way?
Thanks in advance!
MainActivity.class
package org.intracode.contactmanager;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//live apearences in screen objects
EditText nameLine, PhoneLine, EmailLine, AddressLine;
Button addBtn;
TabHost myTab;
List<Contact> myContactList = new ArrayList<>();
ListView myListView;
ImageView contactImage;
Uri imageURI = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_logo.png");// including assigning
DatabaseHandler contacsDB;
ArrayAdapter<Contact> myContactsAdapter;
int longcClickElemnt;//clicked item position
private static final int EDIT=0,DELETE=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assigning line fields
nameLine = (EditText) findViewById(R.id.nameLine);
PhoneLine = (EditText) findViewById(R.id.PhoneLine);
EmailLine = (EditText) findViewById(R.id.EmailLine);
AddressLine = (EditText) findViewById(R.id.AdressLine);
addBtn = (Button) findViewById(R.id.saveButton);
//assigning tab objects
myTab = (TabHost) findViewById(R.id.tabHost); //assigning general tab
myTab.setup();
//assigning first sub tub
TabHost.TabSpec tabspec = myTab.newTabSpec("creator");
tabspec.setContent(R.id.creatorTab);
tabspec.setIndicator("Creator");//name of sub tab
myTab.addTab(tabspec);// connecting the sub tab to the general tab
// assigning second sub tub
tabspec = myTab.newTabSpec("list");
tabspec.setContent(R.id.tabContactList);
tabspec.setIndicator("List");//name of sub tab
myTab.addTab(tabspec);// connecting the sub tab to the general tab
//assigning the listview object
myListView = (ListView) findViewById(R.id.listview);
// assigning ImageView object
contactImage = (ImageView) findViewById(R.id.contactImage);
//assignig dataBase
contacsDB = new DatabaseHandler(getApplicationContext());
//register a menu for the list object
registerForContextMenu(myListView);
myListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
longcClickElemnt=i;
contactImage.setVisibility(View.VISIBLE);
return false;
}
});
// name event
nameLine.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String email = charSequence.toString().trim();
addBtn.setEnabled(String.valueOf(nameLine.getText()).trim().length() > 0 && isValidEmaillId(email));
}
#Override
public void afterTextChanged(Editable editable) {
}
});
// email event
EmailLine.addTextChangedListener(new TextWatcher() {
String emailString = EmailLine.getText().toString().trim();
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String email = charSequence.toString().trim();
addBtn.setEnabled(nameLine.getText().toString().trim().length() > 0 && isValidEmaillId(email));
}
#Override
public void afterTextChanged(Editable editable) {
}
});
//buttonEvent
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Contact newCont = new Contact(contacsDB.getContactsCount(), nameLine.getText().toString(), PhoneLine.getText().toString(), EmailLine.getText().toString(), AddressLine.getText().toString(), imageURI);
if (!contactExist(newCont)) {
contacsDB.createContact(newCont);
myContactList.add(newCont);
myContactsAdapter.notifyDataSetChanged();// let the adapter know something is changing in our list
Toast.makeText(getApplicationContext(), "You added " + nameLine.getText().toString() + " to your contact list", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getApplicationContext(), nameLine.getText().toString() + " is already exist in your list", Toast.LENGTH_SHORT).show();
nameLine.setText("");
PhoneLine.setText("");
EmailLine.setText("");
AddressLine.setText("");
contactImage.setImageResource(R.drawable.no_logo);
}
});
//contactImageEvent
contactImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {// defining a chooser
Intent intent = new Intent();// intent is an object that passes a messeges in our system
intent.setType("image/*");// Set an explicit MIME data type.
intent.setAction(intent.ACTION_GET_CONTENT);//Allow the user to select a particular kind of data and return it.
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
//populate the list such that our list view will show all the contact that in pur database
// synchronized with our database
if (contacsDB.getContactsCount() > 0)
myContactList.addAll(contacsDB.getAllContacts());
populateList();// write the contact that we added now into the list's screen
}
//special method for the moment that we create the menu with its fields
public void onCreateContextMenu(ContextMenu myMenu, View myView,ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(myMenu,myView,menuInfo);
myMenu.setHeaderIcon(R.drawable.edit_icon);
myMenu.setHeaderTitle("Contact options");
myMenu.add(Menu.NONE,EDIT,myMenu.NONE,"Edit contact");
myMenu.add(Menu.NONE,DELETE,myMenu.NONE,"Delete contact");
}
public boolean onContextItemSelected(MenuItem myItem){
switch(myItem.getItemId()){
case EDIT:
Intent moveToEdit= new Intent(this,EditContactActivity.class);
String[] argToPass={String.valueOf(myContactList.get(longcClickElemnt).getId()),myContactList.get(longcClickElemnt).getName(),
myContactList.get(longcClickElemnt).getPhone(), myContactList.get(longcClickElemnt).getEmail(),
myContactList.get(longcClickElemnt).getAddress(),String.valueOf(myContactList.get(longcClickElemnt).getImageURI())};
moveToEdit.putExtra("args",argToPass);
startActivityForResult(moveToEdit,2);
break;
case DELETE:
//longcClickElemnt represents the position of item that we clicked on in our listview
// , initilized every setOnItemLongClickListener
contacsDB.deleteContact(myContactList.get(longcClickElemnt));//remove from database
myContactList.remove(longcClickElemnt);// remove from list
myContactsAdapter.notifyDataSetChanged();// update database instantly
break;
}
return super.onContextItemSelected(myItem);
}
//Handling the result of clicking the contact image(Created to reply startActivityForResult function )
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 1:// comeback from image collecting screen
imageURI = data.getData();
contactImage.setImageURI(data.getData());//Sets the content of this ImageView to the specified Uri.
break;
case 2://comeback from edit contact screen
String[] contactDetails=data.getStringArrayExtra("result");
contacsDB.updateContact(new Contact(Integer.parseInt(contactDetails[0]), contactDetails[1], contactDetails[2],
contactDetails[3],contactDetails[4], Uri.parse(contactDetails[5])));//update datatbase operation
myContactList.get(longcClickElemnt).setAll(contactDetails[1], contactDetails[2],
contactDetails[3],contactDetails[4], Uri.parse(contactDetails[5]));
myContactsAdapter.notifyDataSetChanged();// update database instantly
Toast.makeText(getApplicationContext(),"Changes saved!",Toast.LENGTH_SHORT).show();
break;
}
}
}
// special adapter that helps display data in a UI element, extending the array adapter class
private class ContactListAdapter extends ArrayAdapter<Contact> {
public ContactListAdapter() {
super(MainActivity.this, R.layout.contact_layout, myContactList);
}
#Override
public View getView(int position, View myView, ViewGroup parent) {//adding a contact in a certain position to our contactList screen
if (myView == null)
myView = getLayoutInflater().inflate(R.layout.contact_layout, parent, false);
Contact currContact = myContactList.get(position);
TextView name = myView.findViewById(R.id.contact_name_store);
name.setText(currContact.getName());
TextView phone = myView.findViewById(R.id.phone_store);
phone.setText(currContact.getPhone());
TextView email = myView.findViewById(R.id.email_store);
email.setText(currContact.getEmail());
TextView address = myView.findViewById(R.id.address_store);
address.setText(currContact.getAddress());
ImageView contactImage = myView.findViewById(R.id.imageViewOnLayput);
contactImage.setImageURI(currContact.getImageURI());
return myView;
}
}
// write inside myListView with the help of the adapter
private void populateList() {
myContactsAdapter = new ContactListAdapter();
myListView.setAdapter(myContactsAdapter);
}
//check if one's email address is valid
public static boolean isValidEmaillId(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private boolean contactExist(Contact c) {
String c_name = c.getName();
int count = myContactList.size();
for (int i = 0; i < count; i++) {
if (myContactList.get(i).getName().compareToIgnoreCase(c_name) == 0)
return true;
}
return false;
}
}
DatabaseHandler.class
package org.intracode.contactmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Johnny Manson on 19.01.14.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactManager",
TABLE_CONTACTS = "contacts",
KEY_ID = "id",
KEY_NAME = "name",
KEY_PHONE = "phone",
KEY_EMAIL = "email",
KEY_ADDRESS = "address",
KEY_IMAGEURI = "imageUri";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_IMAGEURI + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
public void createContact(Contact contact) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PHONE, contact.getPhone());
values.put(KEY_EMAIL, contact.getEmail());
values.put(KEY_ADDRESS, contact.getAddress());
values.put(KEY_IMAGEURI, String.valueOf(contact.getImageURI()));
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
public Contact getContact(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PHONE, KEY_EMAIL, KEY_ADDRESS, KEY_IMAGEURI }, 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), cursor.getString(4), Uri.parse(cursor.getString(5)));
db.close();
cursor.close();
return contact;
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
db.close();
}
public int getContactsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updateContact(Contact contact) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PHONE, contact.getPhone());
values.put(KEY_EMAIL, contact.getEmail());
values.put(KEY_ADDRESS, contact.getAddress());
values.put(KEY_IMAGEURI, contact.getImageURI().toString());
int rowsAffected = db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
db.close();
return rowsAffected;
}
public List<Contact> getAllContacts() {
List<Contact> contacts = new ArrayList<Contact>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
if (cursor.moveToFirst()) {
do {
contacts.add(new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5))));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return contacts;
}
}
EditActivity.class
package org.intracode.contactmanager;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class EditContactActivity extends AppCompatActivity {
//live appearances in screen objects
EditText editName, editPhone, editEmail, editAddress;
Button editButton;
ImageView editImage;
Uri imageURI = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_logo.png");// including assigning
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_contact);
//assigning fields
editName = (EditText) findViewById(R.id.editName);
editPhone = (EditText) findViewById(R.id.editPhone);
editEmail = (EditText) findViewById(R.id.editEmail);
editAddress = (EditText) findViewById(R.id.editAddress);
editButton = (Button) findViewById(R.id.editButton);
editImage = (ImageView) findViewById(R.id.editImage);
// getting passed arguments
String[] passedArg = getIntent().getStringArrayExtra("args");
editName.setText(passedArg[1]);
editPhone.setText(passedArg[2]);
editEmail.setText(passedArg[3]);
editAddress.setText(passedArg[4]);
editImage.setImageURI(Uri.parse(passedArg[5]));
//events
editName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String email = charSequence.toString().trim();
editButton.setEnabled(String.valueOf(editName.getText()).trim().length() > 0 && MainActivity.isValidEmaillId(email));
}
#Override
public void afterTextChanged(Editable editable) {
}
});
// email event
editEmail.addTextChangedListener(new TextWatcher() {
String emailString = editEmail.getText().toString().trim();
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String email = charSequence.toString().trim();
editButton.setEnabled(editName.getText().toString().trim().length() > 0 && MainActivity.isValidEmaillId(email));
}
#Override
public void afterTextChanged(Editable editable) {
}
});
//buttonEvent
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent returnIntent = new Intent();
String[] passedArg = getIntent().getStringArrayExtra("args");
String[] argToReturn = {passedArg[0], String.valueOf(editName.getText()), String.valueOf(editPhone.getText()), String.valueOf(editEmail.getText()),
String.valueOf(editAddress.getText()), String.valueOf(editImage)};
returnIntent.putExtra("result", argToReturn);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
editImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {// defining a chooser
Intent intent = new Intent();// intent is an object that passes a messeges in our system
intent.setType("image/*");// Set an explicit MIME data type.
intent.setAction(intent.ACTION_GET_CONTENT);//Allow the user to select a particular kind of data and return it.
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 1:// comeback from image collecting screen
imageURI = data.getData();
editImage.setImageURI(data.getData());//Sets the content of this ImageView to the specified Uri.
}
}
}
}
Contact class
package org.intracode.contactmanager;
import android.net.Uri;
import java.net.URI;
/**
* Created by Roey on 09/08/2017.
*/
public class Contact {
private String name ,email, phone, address;
private Uri imageURI;
private int id;// added for database manners
public Contact(int id,String name ,String phone,String email,String address,Uri imageURI){
this.id=id;
this.name=name;
this.email=email;
this.phone=phone;
this.address=address;
this.imageURI=imageURI;
}
//getters
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public String getPhone(){
return phone;
}
public String getAddress(){
return address;
}
public Uri getImageURI(){
return imageURI;
}
public int getId(){
return id;
}
//setters
public void setAll(String name,String phone,String email,String address,Uri imageURI){
this.name=name;
this.email=email;
this.phone=phone;
this.address=address;
this.imageURI=imageURI;
}
}

Related

Do I need to write SELECT query additionally while using content values?

I'm working on a code snippet for performing CRUD operations in Sqlite DB in Android Studio. I created a listView to hold two attributes, i.e., name and job but the application is getting crashed at runtime. It says:
Sqlite Exception: no such column( code 1) "name" Found.
I've searched for the solution but every solution I've checked is a failed one. My DB browser shows the table contains the column. Do I need to add SELECT FROM ...query to my code? If it is, then where should I put the code?
my code as below:
DatabaseHelper.class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public static final String TABLE_NAME = "USERS";
public static final String _ID = "_id";
public static final String DESC = "occupation";
public static final String SUBJECT = "name";
SQLiteDatabase myDb;
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
"(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SUBJECT + "TEXT NOT NULL,"
+ DESC + "TEXT"+ ")" ;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long insert(String name, String desc) {
myDb = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
long id = myDb.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
myDb.close();
return id;
}
public Cursor read(){
SQLiteDatabase myDb = this.getWritableDatabase();
String[] columns = new String[] {DatabaseHelper._ID,DatabaseHelper.SUBJECT,DatabaseHelper.DESC};
Cursor cursor = myDb.query(DatabaseHelper.TABLE_NAME,columns,null,null,null,null,null);
if(cursor!=null){
cursor.moveToFirst();
}
myDb.close();
return cursor;
}
}
MainActivity.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button addUser;
ArrayList<String> list;
ArrayAdapter<String> adapter;
DatabaseHelper dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addUser = findViewById(R.id.add_button);
list = new ArrayList<>();
adapter = new ArrayAdapter<>(this, R.layout.populate_list, R.id.name, list);
dbManager = new DatabaseHelper(this);
addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addAccount();
}
});
}
public void addAccount() {
Intent intent = new Intent(MainActivity.this, AddUser.class);
startActivityForResult(intent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
final String name = intent.getStringExtra("name");
final String occupation = intent.getStringExtra("occupation");
ListView listView = findViewById(R.id.parentLayout);
dbManager.read();
list.add(name);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, UpdateActivity.class);
i.putExtra(name, "username");
i.putExtra(occupation, "occupation");
startActivity(i);
}
});
}
}
}
AddUser.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddUser extends AppCompatActivity {
EditText userName, job;
Button submitButton, cancelButton;
DatabaseHelper dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
dbManager = new DatabaseHelper(this);
userName = findViewById(R.id.userText);
job = findViewById(R.id.occupation);
submitButton = findViewById(R.id.submit_button);
cancelButton = findViewById(R.id.cancel_button);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddUser.this, MainActivity.class);
startActivity(intent);
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
String name = userName.getText().toString();
String desc = job.getText().toString();
intent.putExtra(name, "name");
intent.putExtra(desc, "occupation");
dbManager.insert(name, desc);
setResult(1, intent);
finish();
}
});
}
}
You can try using a rawquery like this :
String sql = " SELECT * FROM " + TABLE_NAME + " WHERE " + ONE_COLUMN_NAME + "=?" + " AND " + PERHAPS_ANOTHER_COLUMN + " =?";
ArrayList<YourKindOfObject> array = new ArrayList<>();
Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[]{firstParameter, secondParameter});
while (cursor.moveToNext()) {
YourKindOfObject yourKindOfObject = new YourKindOfObject();
yourKindOfObject.setOneThing(cursor.getString(cursor.getColumnIndex(ColumnName));
yourKindOfObject.setOneOtherThing(cursor.getString(cursor.getColumnIndex(ColumnName1)));
array.add(yourKindOfObject);
}
cursor.close();
return array;

How to Refresh list view in android

I am creating an android application that consists of a list view populated by the data from the database.
Here I need to delete the data from the database as well as the list view and refresh the list view.
I used both notifyOnDataSetChanged() and notifyOnDataSetInvalidated() but
it wont work for me please help me with this
package com.developer.milanandroid;
import android.app.ActionBar;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.gc.materialdesign.widgets.Dialog;
import com.milan.emptylayout.EmptyLayout;
import com.milan.lib.progressgenarator.lib.ProgressGenerator;
import com.milan.lib.progressgenarator.lib.ProgressGenerator.OnCompleteListener;
import com.milan.swipemenulistview.SwipeMenu;
import com.milan.swipemenulistview.SwipeMenuCreator;
import com.milan.swipemenulistview.SwipeMenuItem;
import com.milan.swipemenulistview.SwipeMenuListView;
import com.milan.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.processbutton.lib.milan.ActionProcessButton;
public class DatabaseListView extends Activity implements OnCompleteListener {
MediaPlayer media_player;
ActionProcessButton fetch_database;
SwipeMenuListView database_results;
LoginDataBaseAdapter logindatabase_adapter;
SimpleCursorAdapter cursoradapter;
Cursor cursor;
TextView username_txt,password_txt;
String user_name_string,password_string;
String text;
Dialog dialog;
private EmptyLayout empty_layout;
View.OnClickListener emptyClickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databaselistview);
View.OnClickListener mErrorClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
fetch_database.setText("Checking...");
empty_layout.showLoading();
ProgressGenerator pg = new ProgressGenerator(DatabaseListView.this);
pg.start(fetch_database);
}
};
emptyClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DatabaseListView.this, "Try again button clicked", Toast.LENGTH_LONG).show();
}
};
ActionBar actionbar = getActionBar();
actionbar.hide();
View v;
LinearLayout linear = (LinearLayout)findViewById(R.id.linearLayout1);
username_txt = (TextView)linear.getChildAt(0);
password_txt = (TextView)linear.getChildAt(0);
user_name_string = username_txt.getText().toString();
password_string = password_txt.getText().toString();
fetch_database = (ActionProcessButton)findViewById(R.id.Button_Fetch_from_Database);
database_results = (SwipeMenuListView)findViewById(R.id.listview_database);
final ProgressGenerator progressGenerator = new ProgressGenerator(DatabaseListView.this);
logindatabase_adapter = new LoginDataBaseAdapter(DatabaseListView.this);
empty_layout = new EmptyLayout(DatabaseListView.this, database_results);
empty_layout.setErrorButtonClickListener(mErrorClickListener);
fetch_database.setMode(ActionProcessButton.Mode.PROGRESS);
fetch_database.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
progressGenerator.start(fetch_database);
fetch_database.setText("Checking...");
fetch_database.setEnabled(false);
empty_layout.showLoading();
media_player = MediaPlayer.create(DatabaseListView.this, R.raw.retrievingfromdatabase);
media_player.start();
String[] from = {LoginDataBaseAdapter.USER_NAME,LoginDataBaseAdapter.USER_PASSWORD};
int[] to = {R.id.txt_username,R.id.txt_pasword};
cursor = logindatabase_adapter.feching_Data();
cursoradapter = new SimpleCursorAdapter(DatabaseListView.this, R.layout.listcell, cursor, from, to);
cursoradapter.notifyDataSetChanged();
//registerForContextMenu(database_results);
}
});
SwipeMenuCreator swipe_list_view = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
SwipeMenuItem open_swipemenu = new SwipeMenuItem(DatabaseListView.this);
open_swipemenu.setBackground(new ColorDrawable(Color.rgb(0x9B,0x33,0xF0)));
open_swipemenu.setWidth(dp2px(90));
open_swipemenu.setIcon(R.drawable.databasedelete);
menu.addMenuItem(open_swipemenu);
}
};
database_results.setMenuCreator(swipe_list_view);
database_results.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
switch(index) {
case 0:
dialog = new Dialog(DatabaseListView.this, "Delete Record", "Do you want to delete Record from database");
dialog.setCancelable(false);
dialog.setOnAcceptButtonClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cursor = (Cursor) database_results.getItemAtPosition(position);
final int item_id = cursor.getInt(cursor.getColumnIndex(LoginDataBaseAdapter.ID));
cursor.getString(cursor.getColumnIndex(LoginDataBaseAdapter.USER_NAME));
cursor.getString(cursor.getColumnIndex(LoginDataBaseAdapter.USER_PASSWORD));
logindatabase_adapter.deleteEntry(item_id);
//database_results.removeViewAt(position);
//cursoradapter.notifyDataSetChanged();
database_results.invalidateViews();
}
});
dialog.show();
}
return false;
}
});
}
protected int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getResources().getDisplayMetrics());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.database_list_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onComplete() {
if(cursor!=null && cursor.getCount()>0){
database_results.setAdapter(cursoradapter);
fetch_database.setEnabled(false);
fetch_database.setText("SUCCESS");
}
else{
/*fetch_database.setEnabled(false);
fetch_database.setText("OOPS");
fetch_database.setBackgroundColor(Color.parseColor("#ffb74d"));
final Dialog dialog_database = new Dialog(DatabaseListView.this, "Database Records", "No Records was found in the database");
dialog_database.setOnAcceptButtonClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog_database.cancel();
}
});
dialog_database.show();*/
fetch_database.setText("OOPS");
fetch_database.setBackgroundColor(Color.parseColor("#ffb74d"));
empty_layout.showError();
}
}
}
This is my LoginDatabase adpater:
package com.developer.milanandroid;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
public class LoginDataBaseAdapter
{
//Database name
static final String DATABASE_NAME = "MilanloginRegistration.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
public static final String TABLE_NAME="MilanLoginregistration";
public static final String ID="_id";
public static final String USER_NAME="USERNAME";
public static final String USER_PASSWORD ="PASSWORD";
static final String DATABASE_CREATE = "create table "+ TABLE_NAME +
"( " +ID+" integer primary key autoincrement,"+"USERNAME text not null,"+USER_PASSWORD+" text not null); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public LoginDataBaseAdapter opentoRead() throws android.database.SQLException{
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
db = dbHelper.getReadableDatabase();
return this;
}
public LoginDataBaseAdapter opentoWrite() throws android.database.SQLException{
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
db = dbHelper.getWritableDatabase();
return this;
}
public void Close(){
dbHelper.close();
}
public void insertEntry(String username,String password)
{
ContentValues newValues = new ContentValues();
newValues.put("USERNAME",username);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("MilanLoginregistration",null,newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteAll(){
return db.delete(TABLE_NAME, null, null);
}
public void deleteEntry(int id){
//String id=String.valueOf(ID);
db.delete(TABLE_NAME, ID+"="+id, null);
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
}
public Cursor queue_all(){
String[] columns = new String[]{ID,"USERNAME","PASSWORD"};
Cursor cursor_queue_all =db.query(TABLE_NAME, columns, null, null, null, null, null);
return cursor_queue_all;
}
public Cursor feching_Data(){
String[] columns = {ID,USER_NAME,USER_PASSWORD};
db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, columns,null,null,null,null,null);
return cursor;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
//cursor.close();
return password;
}
public String checkSinlgeEntry(String userName)
{
Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()>=1) // UserName Exist
{
cursor.close();
return "NOT EXIST";
}
// cursor.close();
return "";
}
public void updateEntry(String user_name,String pasword)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", user_name);
updatedValues.put("PASSWORD",pasword);
String where="USERNAME = ?";
db.update("MilanLoginregistration",updatedValues, where, new String[]{user_name});
}
/*public void Display(View v){
Cursor c = db.rawQuery("select * from MilanloginRegistration", null);
admin_settings_child.text_fetched_database_results.setText("");
c.moveToFirst();
do{
String username = c.getString(c.getColumnIndex("USERNAME"));
String password = c.getString(1);
admin_settings_child.text_fetched_database_results.append("USERNAME::-->"+username+"PASSWORD::-->"+password+"\n");
}while(c.moveToNext());
}*/
}
Kindly post the code of your adapter as well. in the above code you are deleting the data from other adapter and notifying other adapter for data set changed. i.e in following lines I can't see where cursoradapter is actually being updated.
logindatabase_adapter.deleteEntry(item_id);
cursoradapter.notifyDataSetChanged();
cursoradapter.notifyDataSetInvalidated();
also you can try this.
listview.getAdapter().notifyDataSetChanged();
For proper implementing datasetchanged functionality you need to create custom adapter other wise you just setlist adapter every time your data is being changed.i.e
listeview.setAdapter(modifiedAdapter);
listview.getAdapter.notifyDataSetChanged();
Edit 1:
as you are using simple cursor adapter you need to add following lines after deleting the entry:
logindatabase_adapter.deleteEntry(item_id);
cursor = logindatabase_adapter.feching_Data();
//database_results.removeViewAt(position);
cursoradapter = new SimpleCursorAdapter(DatabaseListView.this, R.layout.listcell, cursor, from, to);
database_results.setAdapter(cursoradapter);
database_results.getAdapter().notifyDataSetChanged();
Use the notifyDataSetChanged() method on the adapter like this:
final ArrayAdapter adapter = ((ArrayAdapter) getListAdapter());
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});

Can't delete Database item SQLite Android

I've been going round in circles with this for days and I can't get my head around what's wrong.
With the following code, when you press the "yes" button to delete the item you touched, it shows everything and appears to do everything but the item is not removed from the list.
Activity class:
package com1032.em00224.knit;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class NoteActivity extends Activity {
private ListView list;
DatabaseHandler db;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
db = new DatabaseHandler(this);
ArrayList array_list = db.getAllNotes();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
//adding it to the list view.
list = (ListView)findViewById(R.id.listView1);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View arg1, final int position,
long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(NoteActivity.this);
adb.setTitle("Delete Note?");
adb.setMessage(R.string.deleteNote);
adb.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteNote(position + 1);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com1032.em00224.knit.NoteActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
adb.show();
}
});
}
And the Database helper:
package com1032.em00224.knit;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "NoteDatabase.db";
public static final String NOTES_TABLE_NAME = "notes";
public static final String NOTES_COLUMN_ID = "id";
public static final String NOTES_COLUMN_NOTE = "note";
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table notes " +
"(id integer primary key, note text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
public boolean insertNote (String note)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("note", note);
db.insert("notes", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, NOTES_TABLE_NAME);
return numRows;
}
public boolean updateNote (Integer id, String note)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("note", note);
db.update("notes", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteNote (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("notes",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllNotes()
{
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from notes", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(NOTES_COLUMN_NOTE)));
res.moveToNext();
}
return array_list;
}
}
Everything else, such as adding a new item, works as it should.
Edit - It now deletes the one that is selected, but it doesn't always actually delete and there seems to be no pattern - I've added some system.out.printlns to get a clearer picture but it says that it is deleting the right one when it isn't.
In some Projects I faced the same Problem. So there are two possible Solutions. First, after removing Your data from database, also remove item from listview/Adapter and call notifyDataSetChanged:
db.deleteNote(position);
arrayAdapter.remove(arrayAdapter.getItem(itemToRemove));
arrayAdapter.notifyDataSetChanged();
So, my Problem was, that this sometimes doesn´t work, until now, I don´t know what I was doing wrong. Anyway, if this doesn´t work, refresh the whole data after deleting:
private void refreshData(){
ArrayList array_list = db.getAllNotes();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
list.setAdapter(arrayAdapter);
list.invalidateViews();
}
So this should look somehting like this in Your onClick:
adb.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteNote(position);
refreshData();
Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com1032.em00224.knit.NoteActivity.class);
startActivity(intent);
}
});
This is just from scratch, I can´t test the code for now because I have no IDE here. So don´t forget to do some Workaround (like opening and closing database etc.).

How to select an item from ListView and see its corresponding id from SQLite database

I have the following two files:
podatkovna_baza.java
package com.example.ultimate.basketball.stats;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class podatkovna_baza extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "baza5";
public podatkovna_baza(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase baza5) {
/*
* Create the employee table and populate it with sample data.
* In step 6, we will move these hardcoded statements to an XML document.
*/
String sql = "CREATE TABLE IF NOT EXISTS ekipe4 (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"ime_ekipe TEXT, " +
"kratko_ime TEXT, " +
"kraj TEXT, " +
"slika TEXT )";
baza5.execSQL(sql);
ContentValues values = new ContentValues();
values.put("ime_ekipe", "Drustvo partizan");
values.put("kratko_ime", "DRP");
values.put("kraj", "Mirna");
values.put("slika", "jajaja");
baza5.insert("ekipe4", null, values);
}
#Override
public void onUpgrade(SQLiteDatabase baza5, int oldVersion, int newVersion) {
baza5.execSQL("DROP TABLE IF EXISTS ekipe4");
onCreate(baza5);
}
}
osnovni_meni.java
package com.example.ultimate.basketball.stats;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class osnovni_meni extends Activity {
protected SQLiteDatabase baza5;
protected Cursor cursor;
protected ListAdapter adapter;
protected ListView ekipe_list;
protected EditText searchtext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_osnovni_meni);
baza5 = (new podatkovna_baza(this)).getWritableDatabase();
//searchtext = (EditText) findViewById (R.id.searchText);
//searchText = (EditText) findViewById (R.id.searchText);
//employeeList = (ListView) findViewById (R.id.list);
}
public void hello(View view) {
//cursor = baza2.rawQuery("SELECT ime_ekipe, kratko_ime, kraj FROM ekipe2" , null);
ekipe_list = (ListView) findViewById (R.id.lista);
cursor = baza5.query("ekipe4", null, null, null, null, null,
"_id" + " ASC");
adapter = new SimpleCursorAdapter(
this,
R.layout.ekipe_layout,
cursor,
new String[] {"_id","kratko_ime","kraj"},
new int[] {R.id.ime_ekipe,R.id.kratko_ime,R.id.kraj});
ekipe_list.setAdapter(adapter);
String sadas=adapter.toStr
}
public void delete_byID(int id) {
baza5.delete("ekipe4", "_id"+"="+id, null);
}
public void delete_by_ime_ekipe(String ime) {
baza5.delete("ekipe4", "kraj"+"="+ime, null);
}
public int deleteAll() {
return baza5.delete("ekipe4", null, null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_osnovni_meni, menu);
return true;
}
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
finish();
}
public void vibriraj()
{
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(30);
}
public void vpisi(View view)
{
ContentValues values1 = new ContentValues();
//values1.put("_id", "1");
values1.put("ime_ekipe", "Chicago Bulls");
values1.put("kratko_ime", "CHI");
values1.put("kraj", "Chicago");
baza5.insert("ekipe4", "kratko_ime", values1);
vibriraj();
}
public void vpisi_ekipo(View view)
{
vibriraj();
EditText novo_ime_ekipe = (EditText) findViewById (R.id.novo_ime_ekipe);
EditText novo_kratko_ime_ekipe = (EditText) findViewById (R.id.novo_kratko_ime_ekipe);
EditText novo_kraj_ekipe = (EditText) findViewById (R.id.novo_kraj_ekipe);
EditText novo_slika_ekipe = (EditText) findViewById (R.id.novo_slika_ekipe);
ContentValues values1 = new ContentValues();
values1.put("ime_ekipe", (novo_ime_ekipe.getText()).toString());
values1.put("kratko_ime", (novo_kratko_ime_ekipe.getText()).toString());
values1.put("kraj", (novo_kraj_ekipe.getText()).toString());
values1.put("slika", (novo_slika_ekipe.getText()).toString());
baza5.insert("ekipe4", "kratko_ime", values1);
vibriraj();
setContentView(R.layout.edit_teams);
}
}
Now I want to for example delete a row I select (get ID from list and corresponding ID from database) or edit a row. How do I do this? It's pretty easy to delete or edit a SQLite entry if you know the id from a database, but I do not.
Sorry for my English, as you can see, it's not my first language.
ekipe_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// your code here
}
});
Here in "position" you get the id of the item you've clicked.
So you need only to convert the id in ListView to the id in database.
Otherwise you will need to create custom adapter instead of SimpleCursorAdapter, and override the getView() method.
in the select query you have mentioned "SELECT * FROM ANSWER WHERE ID="
But you have to mention as " "SELECT * FROM answer WHERE ID"
Because table name is answer not ANSWER

can i use database demo

Hello people i have been making my app now for 6 month. iv been working on my layout all this time and coding etc.
Now for the Last month iv been trying to make a database. But i just can't get my head round this problem. I have finished the android notepad tutorial and i have downloaded SQLite database browser. and even tho i have a working database from the notepad v3( add & delete data) i just don't know if i can use this database demo in my project.
also i was on some stack overflow page (cant find it now) and someone put a link to a database demo zip file in which i downloaded and when i run it. its just what am after.
hope you guys can help me out and let me know if i can just use this database demo as my own..
Don't get me wrong am not looking for a easy way out of making my own database or learning about it.
There is a lot to learn in the android world. and if i have a working DB which i can use on other project i will learn along the way about coding..
here is the java code of the database demo its a bit heavy pasteing all this so sorry
if you would like to see my XML please just say..
package mina.android.DatabaseDemo;
import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Spannable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
public class AddEmployee extends Activity {
EditText txtName;
EditText txtAge;
TextView txtEmps;
DatabaseHelper dbHelper;
Spinner spinDept;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addemployee);
txtName=(EditText)findViewById(R.id.txtName);
txtAge=(EditText)findViewById(R.id.txtAge);
txtEmps=(TextView)findViewById(R.id.txtEmps);
spinDept=(Spinner)findViewById(R.id.spinDept);
}
#Override
public void onStart()
{
try
{
super.onStart();
dbHelper=new DatabaseHelper(this);
txtEmps.setText(txtEmps.getText()+String.valueOf(dbHelper.getEmployeeCount()));
Cursor c=dbHelper.getAllDepts();
startManagingCursor(c);
//SimpleCursorAdapter ca=new
SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String []
{DatabaseHelper.colDeptName}, new int []{android.R.id.text1});
SimpleCursorAdapter ca=new
SimpleCursorAdapter(this,R.layout.deptspinnerrow, c, new String []
{DatabaseHelper.colDeptName,"_id"}, new int []{R.id.txtDeptName});
//ca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinDept.setAdapter(ca);
spinDept.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View
selectedView,
int position, long id) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
//never close cursor
}
catch(Exception ex)
{
CatchError(ex.toString());
}
}
public void btnAddEmp_Click(View view)
{
boolean ok=true;
try
{
Spannable spn=txtAge.getText();
String name=txtName.getText().toString();
int age=Integer.valueOf(spn.toString());
int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());
Employee emp=new Employee(name,age,deptID);
dbHelper.AddEmployee(emp);
}
catch(Exception ex)
{
ok=false;
CatchError(ex.toString());
}
finally
{
if(ok)
{
//NotifyEmpAdded();
Alerts.ShowEmpAddedAlert(this);
txtEmps.setText("Number of employees
"+String.valueOf(dbHelper.getEmployeeCount()));
}
}
}
void CatchError(String Exception)
{
Dialog diag=new Dialog(this);
diag.setTitle("Add new Employee");
TextView txt=new TextView(this);
txt.setText(Exception);
diag.setContentView(txt);
diag.show();
}
void NotifyEmpAdded()
{
Dialog diag=new Dialog(this);
diag.setTitle("Add new Employee");
TextView txt=new TextView(this);
txt.setText("Employee Added Successfully");
diag.setContentView(txt);
diag.show();
try {
diag.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
CatchError(e.toString());
}
diag.notify();
diag.dismiss();
}
}
package mina.android.DatabaseDemo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;
public class Alerts {
public static void ShowEmpAddedAlert(Context con)
{
AlertDialog.Builder builder=new AlertDialog.Builder(con);
builder.setTitle("Add new Employee");
builder.setIcon(android.R.drawable.ic_dialog_info);
DialogListner listner=new DialogListner();
builder.setMessage("Employee Added successfully");
builder.setPositiveButton("ok", listner);
AlertDialog diag=builder.create();
diag.show();
}
public static AlertDialog ShowEditDialog(final Context con,final Employee emp)
{
AlertDialog.Builder b=new AlertDialog.Builder(con);
b.setTitle("Employee Details");
LayoutInflater li=LayoutInflater.from(con);
View v=li.inflate(R.layout.editdialog, null);
b.setIcon(android.R.drawable.ic_input_get);
b.setView(v);
final TextView txtName=(TextView)v.findViewById(R.id.txtDelName);
final TextView txtAge=(TextView)v.findViewById(R.id.txtDelAge);
final Spinner spin=(Spinner)v.findViewById(R.id.spinDiagDept);
Utilities.ManageDeptSpinner(con, spin);
for(int i=0;i<spin.getCount();i++)
{
long id=spin.getItemIdAtPosition(i);
if(id==emp.getDept())
{
spin.setSelection(i, true);
break;
}
}
txtName.setText(emp.getName());
txtAge.setText(String.valueOf(emp.getAge()));
b.setPositiveButton("Modify", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
emp.setName(txtName.getText().toString());
emp.setAge(Integer.valueOf(txtAge.getText().toString()));
emp.setDept((int)spin.getItemIdAtPosition(spin.getSelectedItemPosition()));
try
{
DatabaseHelper db=new DatabaseHelper(con);
db.UpdateEmp(emp);
}
catch(Exception ex)
{
CatchError(con, ex.toString());
}
}
});
b.setNeutralButton("Delete", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DatabaseHelper db=new DatabaseHelper(con);
db.DeleteEmp(emp);
}
});
b.setNegativeButton("Cancel", null);
return b.create();
//diag.show();
}
static public void CatchError(Context con, String Exception)
{
Dialog diag=new Dialog(con);
diag.setTitle("Error");
TextView txt=new TextView(con);
txt.setText(Exception);
diag.setContentView(txt);
diag.show();
}
}
package mina.android.DatabaseDemo
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.TabHost;
import android.widget.TextView;
public class DatabaseDemo extends TabActivity {
DatabaseHelper dbHelper;
GridView grid;
TextView txtTest;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SetupTabs();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(1, 1, 1, "Add Employee");
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
//Add employee
case 1:
Intent addIntent=new Intent(this,AddEmployee.class);
startActivity(addIntent);
break;
}
super.onOptionsItemSelected(item);
return false;
}
void SetupTabs()
{
TabHost host=getTabHost();
TabHost.TabSpec spec=host.newTabSpec("tag1");
Intent in1=new Intent(this, AddEmployee.class);
spec.setIndicator("Add Employee");
spec.setContent(in1);
TabHost.TabSpec spec2=host.newTabSpec("tag2");
Intent in2=new Intent(this, GridList.class);
spec2.setIndicator("Employees");
spec2.setContent(in2);
host.addTab(spec);
host.addTab(spec2);
}
}
package mina.android.DatabaseDemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
static final String dbName="demoDB";
static final String employeeTable="Employees";
static final String colID="EmployeeID";
static final String colName="EmployeeName";
static final String colAge="Age";
static final String colDept="Dept";
static final String deptTable="Dept";
static final String colDeptID="DeptID";
static final String colDeptName="DeptName";
static final String viewEmps="ViewEmps";
public DatabaseHelper(Context context) {
super(context, dbName, null,33);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+deptTable+" ("+colDeptID+ " INTEGER PRIMARY KEY
, "+
colDeptName+ " TEXT)");
db.execSQL("CREATE TABLE "+employeeTable+" ("+colID+" INTEGER PRIMARY KEY
AUTOINCREMENT, "+
colName+" TEXT, "+colAge+" Integer, "+colDept+" INTEGER
NOT NULL ,FOREIGN KEY ("+colDept+") REFERENCES "+deptTable+"
("+colDeptID+"));");
db.execSQL("CREATE TRIGGER fk_empdept_deptid " +
" BEFORE INSERT "+
" ON "+employeeTable+
" FOR EACH ROW BEGIN"+
" SELECT CASE WHEN ((SELECT "+colDeptID+" FROM
"+deptTable+" WHERE "+colDeptID+"=new."+colDept+" ) IS NULL)"+
" THEN RAISE (ABORT,'Foreign Key Violation') END;"+
" END;");
db.execSQL("CREATE VIEW "+viewEmps+
" AS SELECT "+employeeTable+"."+colID+" AS _id,"+
" "+employeeTable+"."+colName+","+
" "+employeeTable+"."+colAge+","+
" "+deptTable+"."+colDeptName+""+
" FROM "+employeeTable+" JOIN "+deptTable+
" ON "+employeeTable+"."+colDept+"
="+deptTable+"."+colDeptID
);
//Inserts pre-defined departments
InsertDepts(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+employeeTable);
db.execSQL("DROP TABLE IF EXISTS "+deptTable);
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger");
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger22");
db.execSQL("DROP TRIGGER IF EXISTS fk_empdept_deptid");
db.execSQL("DROP VIEW IF EXISTS "+viewEmps);
onCreate(db);
}
void AddEmployee(Employee emp)
{
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName, emp.getName());
cv.put(colAge, emp.getAge());
cv.put(colDept, emp.getDept());
//cv.put(colDept,2);
db.insert(employeeTable, colName, cv);
db.close();
}
int getEmployeeCount()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("Select * from "+employeeTable, null);
int x= cur.getCount();
cur.close();
return x;
}
Cursor getAllEmployees()
{
SQLiteDatabase db=this.getWritableDatabase();
//Cursor cur= db.rawQuery("Select "+colID+" as _id , "+colName+",
"+colAge+" from "+employeeTable, new String [] {});
Cursor cur= db.rawQuery("SELECT * FROM "+viewEmps,null);
return cur;
}
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id, "+colDeptName+" from
"+deptTable,new String [] {});
return cur;
}
void InsertDepts(SQLiteDatabase db)
{
ContentValues cv=new ContentValues();
cv.put(colDeptID, 1);
cv.put(colDeptName, "Sales");
db.insert(deptTable, colDeptID, cv);
cv.put(colDeptID, 2);
cv.put(colDeptName, "IT");
db.insert(deptTable, colDeptID, cv);
cv.put(colDeptID, 3);
cv.put(colDeptName, "HR");
db.insert(deptTable, colDeptID, cv);
db.insert(deptTable, colDeptID, cv);
}
public String GetDept(int ID)
{
SQLiteDatabase db=this.getReadableDatabase();
String[] params=new String[]{String.valueOf(ID)};
Cursor c=db.rawQuery("SELECT "+colDeptName+" FROM"+ deptTable+" WHERE
"+colDeptID+"=?",params);
c.moveToFirst();
int index= c.getColumnIndex(colDeptName);
return c.getString(index);
}
public Cursor getEmpByDept(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
String [] columns=new String[]{"_id",colName,colAge,colDeptName};
Cursor c=db.query(viewEmps, columns, colDeptName+"=?", new String[]
{Dept}, null, null, null);
return c;
}
public int GetDeptID(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(deptTable, new String[]{colDeptID+" as
_id",colDeptName},colDeptName+"=?", new String[]{Dept}, null, null, null);
//Cursor c=db.rawQuery("SELECT "+colDeptID+" as _id FROM "+deptTable+"
WHERE "+colDeptName+"=?", new String []{Dept});
c.moveToFirst();
return c.getInt(c.getColumnIndex("_id"));
}
public int UpdateEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName, emp.getName());
cv.put(colAge, emp.getAge());
cv.put(colDept, emp.getDept());
return db.update(employeeTable, cv, colID+"=?", new String
[]{String.valueOf(emp.getID())});
}
public void DeleteEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
db.delete(employeeTable,colID+"=?", new String []
{String.valueOf(emp.getID())});
db.close();
}
}
package mina.android.DatabaseDemo;
import android.content.DialogInterface;
public class DialogListner implements
android.content.DialogInterface.OnClickListener {
public DialogListner()
{
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
package mina.android.DatabaseDemo;
import android.content.Context;
public class Employee {
int _id;
String _name;
int _age;
int _dept;
public Employee(String Name,int Age,int Dept)
{
this._name=Name;
this._age=Age;
this._dept=Dept;
}
public Employee(String Name,int Age)
{
this._name=Name;
this._age=Age;
}
public int getID()
{
return this._id;
}
public void SetID(int ID)
{
this._id=ID;
}
public String getName()
{
return this._name;
}
public int getAge()
{
return this._age;
}
public void setName(String Name)
{
this._name=Name;
}
public void setAge(int Age)
{
this._age=Age;
}
public void setDept(int Dept)
{
this._dept=Dept;
}
public String getDeptName(Context con, int Dept)
{
return new DatabaseHelper(con).GetDept(Dept);
}
public int getDept()
{
return this._dept;
}
}
package mina.android.DatabaseDemo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
public class GridList extends Activity {
DatabaseHelper dbHelper;
static public GridView grid;
TextView txtTest;
Spinner spinDept1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
grid=(GridView)findViewById(R.id.grid);
txtTest=(TextView)findViewById(R.id.txtTest);
spinDept1=(Spinner)findViewById(R.id.spinDept1);
Utilities.ManageDeptSpinner(this.getParent(),spinDept1);
final DatabaseHelper db=new DatabaseHelper(this);
try
{
http://img856.imageshack.us/img856/446/hoop.png
spinDept1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
LoadGrid();
//sca.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
catch(Exception ex)
{
txtTest.setText(ex.toString());
}
try
{
grid.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
try
{
SQLiteCursor
cr=(SQLiteCursor)parent.getItemAtPosition(position);
String
name=cr.getString(cr.getColumnIndex(DatabaseHelper.colName));
int
age=cr.getInt(cr.getColumnIndex(DatabaseHelper.colAge));
String
Dept=cr.getString(cr.getColumnIndex(DatabaseHelper.colDeptName));
Employee emp=new Employee(name, age,db.GetDeptID(Dept));
emp.SetID((int)id);
AlertDialog diag= Alerts.ShowEditDialog(GridList.this,emp);
diag.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
txtTest.setText("dismissed");
//((SimpleCursorAdapter)grid.getAdapter()).notifyDataSetChanged();
LoadGrid();
}
});
diag.show();
}
catch(Exception ex)
{
Alerts.CatchError(GridList.this, ex.toString());
}
}
}
);
}
catch(Exception ex)
{
}
}
#Override
public void onStart()
{
super.onStart();
//LoadGrid();
}
public void LoadGrid()
{
dbHelper=new DatabaseHelper(this);
try
{
//Cursor c=dbHelper.getAllEmployees();
View v=spinDept1.getSelectedView();
TextView txt=(TextView)v.findViewById(R.id.txtDeptName);
String Dept=String.valueOf(txt.getText());
Cursor c=dbHelper.getEmpByDept(Dept);
startManagingCursor(c);
String [] from=new String
[]{DatabaseHelper.colName,DatabaseHelper.colAge,DatabaseHelper.colDeptName};
int [] to=new int [] {R.id.colName,R.id.colAge,R.id.colDept};
SimpleCursorAdapter sca=new
SimpleCursorAdapter(this,R.layout.gridrow,c,from,to);
grid.setAdapter(sca);
}
catch(Exception ex)
{
AlertDialog.Builder b=new AlertDialog.Builder(this);
b.setMessage(ex.toString());
b.show();
}
}
}
package mina.android.DatabaseDemo;
import android.content.Context;
import android.database.Cursor;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
public class Utilities {
static public void ManageDeptSpinner(Context context,Spinner view)
{
DatabaseHelper dbHelper=new DatabaseHelper(context);
Cursor c=dbHelper.getAllDepts();
//context.startManagingCursor(c);
//SimpleCursorAdapter ca=new
SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String []
{DatabaseHelper.colDeptName}, new int []{android.R.id.text1});
SimpleCursorAdapter ca=new
SimpleCursorAdapter(context,R.layout.deptspinnerrow,c,
new String [] {DatabaseHelper.colDeptName,"_id"}, new int []{R.id.txtDeptName});
view.setAdapter(ca);
}
}
Most Android demos, including the current version of Notepad, use the Apache License v2.0. This license says you can freely use and redistribute the code, but you must preserve all existing notices and attributions, and clearly acknowledge that you have modified the code. (See paragraph 4 for the exact wording.)

Categories

Resources