I'm stuck in an application , and I need your advice .
I wish the first page to be able to run items from the database using the buttons inainte(front) and inapoi(back), but I try to order the database in OnClick Lisiner , but the application crashes , and do not know why , tend to, I think i don`t appelea ,the items in the database, properly.
How do you think I should do , or what should I do for this job to do , to run elements .
And again the problem that I have not found it anywhere, how do I do the print button ,to send the print information from the screen element displayed.
The vast majority of the code I've written was hith the help of tutorials.
So, this is the code, and files, that i creat:
Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<ImageView
android:id="#+id/ivImagineaRetetei"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/INAPOI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/numeleRetetei" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Carrefour Suceava"
android:id="#+id/textView2"
/>
<TextView
android:layout_width="290dp"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Numele Retetei"
android:id="#+id/numeleRetetei"
android:layout_alignTop="#+id/PPR"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/PPR" />
<Button
android:layout_width="99dp"
android:layout_height="wrap_content"
android:text="Adauga"
android:id="#+id/ADD"
android:layout_gravity="right"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/PPR" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Printeaza"
android:id="#+id/PPR"
android:layout_marginTop="28dp"
android:layout_gravity="right"
android:layout_below="#+id/textView2"
android:layout_alignEnd="#+id/INAINTE" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inapoi"
android:id="#+id/INAPOI"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inainte"
android:id="#+id/INAINTE"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TabHost
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tabHost">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/tabContactList"
android:layout_width="match_parent"
android:layout_height="458dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Retetele mele"
android:id="#+id/textView"
android:layout_gravity="center"
android:layout_marginTop="10dp" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView"
android:layout_gravity="center" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabCreator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Adauga Reteta"
android:id="#+id/lblCreatorTitle"
android:layout_gravity="center"
android:layout_marginTop="10dp" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imgViewContactImage"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:src="#drawable/index" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/txtName"
android:phoneNumber="false"
android:layout_marginTop="15dp"
android:hint="Numele Retetei" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Adaugare"
android:id="#+id/btnAdd"
android:layout_marginTop="10dp"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inapoi"
android:id="#+id/btnRET"
android:layout_marginTop="10dp"
android:enabled="true" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
Contact.java
package ciprian.retete_carrefour;
import android.net.Uri;
public class Contact {
private String _name;
private Uri _imageURI;
private int _id;
public Contact(int id, String name, Uri imageURI){
_id = id;
_name = name;
_imageURI = imageURI;
}
public int getId() { return _id; }
public String getName() { return _name; }
public Uri getImageURI() { return _imageURI; }
}
DatabaseHandler.java
package ciprian.retete_carrefour;
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;
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_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_IMAGEURI + " TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
//CREARE DE USER
public void createContact (Contact contact)
{
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGEURI, contact.getImageURI().toString());
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
//CITIRE BAZA DE DATE
public Contact getContact(int id)
{
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, 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), Uri.parse(cursor.getString(2)));
db.close();
cursor.close();
return contact;
}
//STERGERE CONTACT DIN DB
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_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), Uri.parse(cursor.getString(2))));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return contacts;
}
}
Main2Activity.java
package ciprian.retete_carrefour;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
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.util.ArrayList;
import java.util.List;
public class Main2Activity extends Activity {
private static final int DELETE=1;
EditText nameTxt;
ImageView contactImageImgView;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
Uri imageUri = Uri.parse("android.resource://ciprian.retete_carrefour/drawable/index.jpg");
DatabaseHandler dbHandler;
int longClickedItemIndex;
ArrayAdapter<Contact> contactAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
nameTxt = (EditText) findViewById(R.id.txtName);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
contactListView = (ListView) findViewById(R.id.listView);
contactImageImgView = (ImageView)findViewById(R.id.imgViewContactImage);
dbHandler = new DatabaseHandler(getApplicationContext());
registerForContextMenu(contactListView);
contactListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
});
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("Adaugare");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("list");
tabSpec.setContent(R.id.tabContactList);
tabSpec.setIndicator("Memorate");
tabHost.addTab(tabSpec);
final Button retBtn = (Button) findViewById(R.id.btnRET);
final Button addBtn = (Button) findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact contact = new Contact(dbHandler.getContactsCount(), String.valueOf(nameTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
contactAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), String.valueOf(nameTxt.getText()) + " a fost adaugata la retete!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getApplicationContext(), String.valueOf(nameTxt.getText()) + " exista deja, te rugam alege alta reteta.", Toast.LENGTH_SHORT).show();
}
});
retBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
}
});
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addBtn.setEnabled(String.valueOf(nameTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Selecteaza Imaginea Retetei"), 1);
}
});
if (dbHandler.getContactsCount()!=0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.pencil_icon);
menu.setHeaderTitle("Optiuni");
menu.add(Menu.NONE, DELETE, menu.NONE, "Sterge");
}
public boolean onContextItemSelected(MenuItem item){
switch (item.getItemId())
{
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
Contacts.remove(longClickedItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(Contact contact)
{
String name = contact.getName();
int contactCount = Contacts.size();
for (int i=0; i <contactCount; i++)
{
if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
return true;
}
return false;
}
public void onActivityResult (int reqCode, int resCode, Intent data)
{
if (resCode == RESULT_OK)
{
if (reqCode == 1) {
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
private void populateList() {
contactAdapter = new ContactListAdapter();
contactListView.setAdapter(contactAdapter);
}
private class ContactListAdapter extends ArrayAdapter<Contact>
{
public ContactListAdapter()
{
super(Main2Activity.this, R.layout.listview_item,Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent)
{
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
ImageView ivContactImage = (ImageView) view.findViewById(R.id.ivContactImage);
ivContactImage.setImageURI(currentContact.getImageURI());
return view;
}
}
}
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="#+id/ivContactImage" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Numele Retetei"
android:id="#+id/contactName"
android:layout_marginTop="20dp" />
</LinearLayout>
</LinearLayout>
MainActivity.java
package ciprian.retete_carrefour;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
// DatabaseHandler bazaDate;
// Button inainte;
// List<Contact> Contacts = new ArrayList<Contact>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setupInainte();
setupAdaugaProdus();
}
/* private void setupInainte()
{
inainte = (Button)findViewById(R.id.INAINTE);
inainte.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contacts = bazaDate.getAllContacts();
int contactCount = Contacts.size();
for (int i=0; i <contactCount; i++)
{
Contact currentContact = Contacts.get(i);
TextView name = (TextView) findViewById(R.id.numeleRetetei);
name.setText(currentContact.getName());
ImageView ivContactImage = (ImageView)findViewById(R.id.ivImagineaRetetei);
ivContactImage.setImageURI(currentContact.getImageURI());
}
}
});
}*/
private void setupAdaugaProdus()
{
Button btn = (Button) findViewById(R.id.ADD);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ciprian.retete_carrefour">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Main2Activity"></activity>
</application>
</manifest>
You are facing a NullPointerException probably because you haven't initialized the database helper class in your MainActivity.
Try:
DatabaseHandler bazaDate = new DatabaseHandler(this);
Only then you may call the methods you have implemented such as GetAllContacts
Try i!
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGEURI = "imageUri";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGEURI + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_IMAGEURI, contact.getImageURI().toString());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, 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));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGEURI, contact.getImageURI().toString());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Related
So basically my goal is to create a notes a page for people to write text/upload files and display those in a list. Right now I am working on doing it through text. I have never used a Database before and as of right now the code will let the user type in text and it will display it on the screen and add it to the database.
My code:
Main Activity:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
// Declare references
EditText userInput;
TextView recordsTextView;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userInput = (EditText) findViewById(R.id.user_Input);
recordsTextView = (TextView) findViewById(R.id.records_TextView);
/* Can pass nulls because of the constants in the helper.
* the 1 means version 1 so don't run update.
*/
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Print the database
public void printDatabase(){
String dbString = dbHandler.databaseToString();
recordsTextView.setText(dbString);
userInput.setText("");
}
//add your elements onclick methods.
//Add a product to the database
public void addButtonClicked(View view){
// dbHandler.add needs an object parameter.
Products product = new Products(userInput.getText().toString());
dbHandler.addProduct(product);
printDatabase();
}
//Delete items
public void deleteButtonClicked(View view){
// dbHandler delete needs string to find in the db
String inputText = userInput.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
}
MyDBHandler:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "productDB.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
//We need to pass database information along to superclass
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT " +
");";
db.execSQL(query);
}
//Lesson 51
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add a new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete a product from the database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";");
}
// this is goint in record_TextView in the Main activity.
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";// why not leave out the WHERE clause?
//Cursor points to a location in your results
Cursor recordSet = db.rawQuery(query, null);
//Move to the first row in your results
recordSet.moveToFirst();
//Position after the last row means the end of the results
while (!recordSet.isAfterLast()) {
// null could happen if we used our empty constructor
if (recordSet.getString(recordSet.getColumnIndex("productname")) != null) {
dbString += recordSet.getString(recordSet.getColumnIndex("productname"));
dbString += "\n";
}
recordSet.moveToNext();
}
db.close();
return dbString;
}
}
Products:
public class Products {
private int _id;
private String _productname;
//Added this empty constructor in lesson 50 in case we ever want to create the object and assign it later.
public Products(){
}
public Products(String productName) {
this._productname = productName;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_productname() {
return _productname;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
}
activity_main.xml;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/user_Input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="69dp"
android:width="300dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/add_Button"
android:layout_below="#+id/user_Input"
android:layout_alignStart="#+id/user_Input"
android:layout_marginTop="40dp"
android:onClick="addButtonClicked"
android:layout_alignLeft="#+id/user_Input" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:id="#+id/delete_Button"
android:layout_alignTop="#+id/add_Button"
android:layout_alignEnd="#+id/user_Input"
android:onClick="deleteButtonClicked"
android:layout_alignRight="#+id/user_Input" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/records_TextView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Use room, it will be easy to use local SQLite db using room, all you need to define entity, dao and database using Room annotations.
For displaying list of records in listview, just create list view adapter and bind record data to views in item layout. I suggest you use RecyclerView instead of listview to get performance benefits.
You can find room and recycler view examples here http://www.zoftino.com/android
Create a ListView somewhere (I created a new layout):
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.pelozo.testjava.MainActivity">
<ListView
android:id="#+id/listview_products"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Create row_product.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textview_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/textview_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Add this method to your database clase:
public ArrayList<Products> getProducts(){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Products> products = new ArrayList<Products>();
while(cursor.moveToNext()){
Products product = new Products();
product.set_id(cursor.getInt(0));
product.set_productname(cursor.getString(1));
products.add(product);
}
cursor.close();
db.close();
return products;
}
create a ProductsAdapter:
public class ProductsAdapter extends ArrayAdapter<Products> {
// View lookup cache
private static class ViewHolder {
TextView id;
TextView name;
}
public ProductsAdapter(Context context, ArrayList<Products> products) {
super(context, R.layout.row_product, products);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Products product = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_product, parent, false);
viewHolder.id = (TextView) convertView.findViewById(R.id.textview_id);
viewHolder.name = (TextView) convertView.findViewById(R.id.textview_name);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data from the data object via the viewHolder object
// into the template view.
viewHolder.id.setText("id:" + product.get_id());
viewHolder.name.setText("name: " + product.get_productname());
// Return the completed view to render on screen
return convertView;
}
}
Now just put it all together:
//get db
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
//add a product
dbHandler.addProduct(new Products("Product Name"));
//retrieve products from db
ArrayList<Products> productsList = dbHandler.getProducts();
// Create the adapter
ProductsAdapter adapter = new ProductsAdapter(this, productsList);
// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.listview_products);
//set adapter
listView.setAdapter(adapter);
Experts,
I would like to store my Spinner1,Spinner2 and multiple checkbox value,edit text value in to my sqlite database upon submitting the button. I try to tweak the same but no luck. Could you advise experts..
Layout is attached below. Two spinner and multiple check box and one submit button,one edit text.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dip"
android:text="#string/lblAcc" />
<!-- Spinner Dropdown -->
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
android:layout_marginTop="10dip"
/>
<!-- Select Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dip"
android:text="#string/lblSubAcc" />
<!-- Spinner Dropdown -->
<Spinner
android:id="#+id/spinner2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Visit Day" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Saturday" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sunday" />
<CheckBox
android:id="#+id/checkBox3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Monday" />
<CheckBox
android:id="#+id/checkBox4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tuesday" />
<CheckBox
android:id="#+id/checkBox5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Wednesday" />
<CheckBox
android:id="#+id/checkBox6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Thursday" />
<CheckBox
android:id="#+id/checkBox7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Outlet is Closed" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calling Frequency" />
<Spinner
android:id="#+id/spinner3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/input_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Comments" />
<Button
android:id="#+id/btn_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />
<!-- Add Button -->
</LinearLayout>
Mainactivity java file.
package aaa.qw.cv;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.DatabaseUtils;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.ArrayList;
import java.util.Arrays;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleCursorAdapter;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.content.Intent;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnClickListener;
import android.util.Log;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.EditText;
import java.util.LinkedList;
import android.view.inputmethod.InputMethodManager;
public class ok extends Activity {
Spinner s1,s2,s3;
Button btnAdd;
EditText inputLabel;
DatabaseHandler dbhndlr;
Cursor spinner1csr, spinner2csr;
SimpleCursorAdapter sca, sca2;
long spinner1_selected = 0;
CheckBox ck1,ck2,ck3,ck4,ck5,ck6,ck7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_ex4);
s1 = (Spinner)findViewById(R.id.spinner1);
s2 = (Spinner)findViewById(R.id.spinner2);
s3 = (Spinner)findViewById(R.id.spinner3);
btnAdd = (Button) findViewById(R.id.btn_add);
inputLabel = (EditText) findViewById(R.id.input_label);
dbhndlr = new DatabaseHandler(this);
ck1=(CheckBox) findViewById(R.id.checkBox);
ck2=(CheckBox)findViewById(R.id.checkBox2);
ck3=(CheckBox)findViewById(R.id.checkBox3);
ck4=(CheckBox)findViewById(R.id.checkBox4);
ck6=(CheckBox) findViewById(R.id.checkBox5);
ck7=(CheckBox)findViewById(R.id.checkBox6);
loadSpinnerData();
// Get Cursors for Spinners
spinner1csr = dbhndlr.getAllLabelsAsCursor();
//Setup Adapter for Spinner 1
sca = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,spinner1csr,
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},
0
);
// Set the Adapters to the Spinners
s1.setAdapter(sca);
// Set Spinner1 OnSelectedItemListener
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"You Selected: " + id + " - " +
spinner1csr.getString(
spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
" - " + spinner1csr.getString(spinner1csr.getColumnIndex(DatabaseHandler.KEY_ID))
,
Toast.LENGTH_SHORT).show();
spinner1_selected = id;
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca2.swapCursor(spinner2csr);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Steup Adapter for Spinner2
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca2 = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
spinner2csr,
new String[]{DatabaseHandler.KEY_ID},
new int[]{android.R.id.text1},
0
);
s2.setAdapter(sca2);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler commeneted out, use dbhndlr instance instead
// inserting new label into database
dbhndlr.insertLabel(label);
// making input filed text to blank
inputLabel.setText("");
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
// loading spinner with newly added data
spinner1csr = dbhndlr.getAllLabelsAsCursor();
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca.swapCursor(spinner1csr);
sca2.swapCursor(spinner2csr);
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
s3.setAdapter(dataAdapter1);
}
#Override
public void onDestroy() {
spinner1csr.close();
spinner2csr.close();
super.onDestroy();
}
}
database java file.
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 {
// Database Version
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "spinnerExample";
// Labels table name
public static final String TABLE_LABELS = "labels"; //<<<< Made public
public static final String TABLE_LABELS1= "labels1";
public static final String TABLE_LABELS2= "labels2";
// Labels Table Columns names
public static final String KEY_ID = "id"; //<<<< Made public
public static final String KEY_NAME = "name"; //<<<< made public
public static final String KEY_ID1 = "id1"; //<<<< Made public
public static final String KEY_NAME1 = "name1";
public static final String KEY_1 = "number"; //<<<< Made public
public static final String KEY_2 = "outletname"; //<<<< made public
public static final String KEY_3 = "sunday"; //<<<< Made public
public static final String KEY_4 = "monday";
public static final String KEY_5 = "tuesday";
public static final String KEY_6 = "wednesday";
public static final String KEY_7 = "thursday";
public static final String KEY_8 = "saturday";
public static final String KEY_9 = "closed";
public static final String KEY_10 = "calling";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
+ KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
db.execSQL(CREATE_CATEGORIES_TABLE1);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
// Inserting Row
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
public void insertLabel1(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
// Inserting Row
db.insert(TABLE_LABELS1, null, values);
db.close(); // Closing database connection
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
// Added for adding new data
public void insertlabel(String id, String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_ID,id);
cv.put(KEY_NAME,label);
db.insert(TABLE_LABELS,null,cv);
db.close();
}
// Added to get Cursor for Simple CursorAdapter
public Cursor getAllLabelsAsCursor() {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
}
public Cursor getAllLabelsExceptedSelected(long selected) {
String[] columns = new String[]{"rowid AS _id, *"};
String whereclause = "rowid <> ?";
String[] whereargs = new String[]{String.valueOf(selected)};
return this.getWritableDatabase().query(TABLE_LABELS,
columns,
whereclause,
whereargs,
null,
null,
null
);
}
public Cursor getByRowid(long id) {
String[] columns = new String[]{"rowid AS _id, *"};
return this.getWritableDatabase().query(
TABLE_LABELS,
columns,
"rowid=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
}
issue is solved with
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_3,message3);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
database
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_3,message3);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
main
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//String label = inputLabel.getText().toString();
String SaveString="No";
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
String message1= ((Cursor) s1.getSelectedItem()).getString(2);
String message2= ((Cursor) s2.getSelectedItem()).getString(1);
String message = inputLabel.getText().toString();
// String message1 = s1.getSelectedItem().toString();
// String message2 = s2.getSelectedItem().toString();
String message10 = s3.getSelectedItem().toString();
String message4 = ck1.getText().toString();
String message5 = ck2.getText().toString();
String message6 = ck3.getText().toString();
String message7 = ck4.getText().toString();
String message9 = ck6.getText().toString();
String message3 = ck7.getText().toString();
String message8 = ck8.getText().toString();
if (ck1.isChecked())
{ message4 = ck1.getText().toString();
}
else
{ message4="No";
}
if (ck2.isChecked())
{ message5 = ck2.getText().toString();
}
else
{ message5="No";
}
if (ck3.isChecked())
{ message6 = ck3.getText().toString();
}
else
{ message6="No";
}
if (ck4.isChecked())
{ message7 = ck4.getText().toString();
}
else
{ message7="No";
}
if (ck6.isChecked())
{ message9 = ck6.getText().toString();
}
else
{ message9="No";
}
if (ck7.isChecked())
{ message3 = ck7.getText().toString();
}
else
{ message3="No";
}
if (ck8.isChecked())
{ message8 = ck8.getText().toString();
}
else
{ message8="No";
}
db.insertLabel(message1,message2,message5,message6,message7,message9,message3,message4,message8,message10);
how to get a data in KEY_NAME from my database(in DbHelper) into TextView("txtSchedName")? and after i retrieve the name its ID will also display in TextView("txtID")?
DbHelper
package com.example.dn;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="patientdata";
public static final String TABLE_NAME="patient";
public static final String KEY_ID="id";
public static final String KEY_NAME="pname";
public static final String KEY_AGE="page";
public static final String KEY_GENDER="pgender";
public static final String KEY_ADDRESS="paddress";
public static final String KEY_CONTACT="pcontact";
private SQLiteDatabase mDb;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, " +
""+KEY_NAME+" TEXT, "+KEY_AGE+" TEXT, "+KEY_GENDER+" TEXT, "+KEY_ADDRESS+" TEXT, "+KEY_CONTACT+" TEXT)";
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 void openDataBase() {
//Open the database
String myPath = DATABASE_NAME + TABLE_NAME;
SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
//latest created
public Cursor displayPatient() {
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {KEY_ID,
KEY_NAME,KEY_AGE,KEY_CONTACT,KEY_GENDER,KEY_ADDRESS},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToLast();
}
return mCursor;
}
/*cur */
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return labels;
}
}
Schedule_DB_Helper
package com.example.dn;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Schedule_DB_Helper extends SQLiteOpenHelper {
static String DATABASE_NAME="patient_schedule";
public static final String TABLE_NAME="schedule";
public static final String KEY_ID="ID";
public static final String KEY_NAME="NAME";
public static final String KEY_DATE="DATE";
public static final String KEY_TIME="TIME";
//public static final String KEY_NOTI="NOTI";
public Schedule_DB_Helper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, " +
""+KEY_NAME+" TEXT,"+KEY_DATE+" TEXT, "+KEY_TIME+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
AddSchedule
/* ©muhammad dn version 1.0
* created 2015
* run in 2 threads*/
package com.example.dn;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.database.Cursor;
public class AddSchedule extends Activity implements OnClickListener {
private Button btn_save;
private EditText name,datee, timee ; //gender_n_u
private Schedule_DB_Helper schedHelper;
private SQLiteDatabase dataBase;
private String id,sName,sDate,sTime;
private boolean isUpdate;
private Spinner spin;
//prprivate ArrayList<String> sched_name = new ArrayList<String>();pinner Notifications List
String []notifications = {"5minutes", "10minutes","20minutes","30minutes","1hours"};
//Spinner spin;
String Notifications;
ArrayAdapter<String> adapter;
// Variable for storing current date and time
private int mYear, mMonth, mDay, mHour, mMinute;
String am_pm = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_schedule);
spin=(Spinner)findViewById(R.id.Notification_spinner);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,notifications);
spin.setAdapter(adapter);
btn_save=(Button)findViewById(R.id.btn_save);
name=(EditText)findViewById(R.id.txtSchedName);
datee=(EditText)findViewById(R.id.txtSchedDate1);
timee=(EditText)findViewById(R.id.txtSchedTime);
datee.setOnClickListener(this);
timee.setOnClickListener(this);
btn_save.setOnClickListener(this);
name.setOnClickListener(this);
//add new record
findViewById(R.id.btnAddSchedule).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
AddPatient.class);
i.putExtra("update", false);
startActivity(i);
}
});
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
sName=getIntent().getExtras().getString("NAME");
sDate=getIntent().getExtras().getString("DATE");
sTime=getIntent().getExtras().getString("TIME");
//sNoti=getIntent().getExtras().getString("NOTI");//
name.setText(sName);
datee.setText(sDate);
timee.setText(sTime);
//spin.setTag(sNoti);//
}
schedHelper=new Schedule_DB_Helper(this);
}
//©muhammad saveButton click event
public void onClick(View v) { //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
if (v == name) {
DbHelper dbHelperInstance = new DbHelper(this);
Cursor cursor = dbHelperInstance.displayPatient();
if(cursor != null) {
EditText pName = (EditText) findViewById(R.id.txtSchedName);
pName.setText(cursor.getString(cursor.getColumnIndex(DbHelper.KEY_NAME)));
}
}
//date and time picking**************************************
if (v == datee) {
// Process to get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Dialog
DatePickerDialog dpd = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// Display Selected date in textbox
datee.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
dpd.show();
}
if (v == timee) {
// Process to get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute ) {
//Adding AM:PM in Time
if (c.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (c.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
// Display Selected time in textbox
timee.setText(hourOfDay + ":" + minute+" "+am_pm);
}
}, mHour, mMinute, false);
tpd.show();
}
//saving data
if (v == btn_save) {
sName=name.getText().toString().trim();
sDate=datee.getText().toString().trim();
sTime=timee.getText().toString().trim();
// sNoti=spin.getTag().toString().trim();
if(sName.length()>0 && sDate.length()>0 && sTime.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddSchedule.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();}
}}
//©muhammad Saving Data to SQLite
private void saveData(){
dataBase= schedHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(Schedule_DB_Helper.KEY_NAME, sName);
values.put(Schedule_DB_Helper.KEY_DATE, sDate );
values.put(Schedule_DB_Helper.KEY_TIME, sTime );
//values.put(Schedule_DB_Helper.KEY_NOTI, sNoti );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(Schedule_DB_Helper.TABLE_NAME, values, Schedule_DB_Helper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(Schedule_DB_Helper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
activity_add_schedule
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/note1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#222222"
android:drawableLeft="#drawable/note"
android:drawablePadding="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:text="#string/note1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#ffffff"
android:textSize="12sp" />
<EditText
android:id="#+id/txtSchedName"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/pname"
android:layout_marginLeft="14dp"
android:ems="10"
android:hint="" >
<requestFocus />
</EditText>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txtSchedName"
android:layout_alignRight="#+id/pname"
android:contentDescription="#string/cd1"
android:src="#drawable/search" />
<EditText
android:id="#+id/txtSchedTime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/TextView02"
android:layout_alignLeft="#+id/txtSchedDate1"
android:layout_alignRight="#+id/txtSchedDate1"
android:ems="10"
android:hint="#string/hint7"
android:nextFocusDown="#+id/btn_save" />
<Button
android:id="#+id/btnAddSchedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/pname"
android:layout_alignRight="#+id/pname"
android:layout_below="#+id/note1"
android:drawableLeft="#drawable/add_new"
android:drawablePadding="10dp"
android:onClick="addPatient"
android:text="#string/button_addPatient" />
<Button
android:id="#+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:drawableLeft="#drawable/done"
android:drawablePadding="-40dp"
android:text="#string/button_done"
android:textSize="12sp"
android:width="163dp" />
<Button
android:id="#+id/btncancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:drawableLeft="#drawable/cancel"
android:drawablePadding="-30dp"
android:focusableInTouchMode="true"
android:onClick="cancel"
android:text="#string/button_cancel"
android:textSize="12sp"
android:width="164dp" />
<TextView
android:id="#+id/pname"
android:layout_width="291dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtSchedName"
android:layout_below="#+id/btnAddSchedule"
android:layout_marginTop="15dp"
android:text="#string/pname"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="12sp" />
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btncancel"
android:layout_alignLeft="#+id/TextView02"
android:layout_marginBottom="34dp"
android:text="#string/textView6"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="14sp" />
<Spinner
android:id="#+id/Notification_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btn_save"
android:layout_toRightOf="#+id/TextView01" />
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Notification_spinner"
android:layout_alignLeft="#+id/TextView01"
android:layout_marginBottom="26dp"
android:text="#string/textView5"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="14sp" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/txtSchedTime"
android:layout_alignLeft="#+id/txtSchedName"
android:layout_marginBottom="21dp"
android:text="#string/textView4"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="14sp" />
<EditText
android:id="#+id/txtSchedDate1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignRight="#+id/imageView1"
android:layout_alignTop="#+id/TextView01"
android:ems="10"
android:hint="#string/hint6"
android:nextFocusDown="#+id/textTIME" />
<TextView
android:id="#+id/TextView04"
android:layout_width="291dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtSchedName"
android:layout_below="#+id/txtSchedName"
android:layout_marginTop="17dp"
android:text="ID"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#686868"
android:textSize="12sp" />
<EditText
android:id="#+id/txtID"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TextView04"
android:layout_alignBottom="#+id/TextView04"
android:layout_alignLeft="#+id/TextView04"
android:layout_marginLeft="35dp"
android:layout_toLeftOf="#+id/txtSchedDate1"
android:ems="10" />
</RelativeLayout>
Here is an example from an app of mine where I wanted to pull certain information from my SQLite database to instantiate a new custom object. I pulled the data based on UUID. You'll most likely have some other way of identifying which column to pull data from.
// Member variable for selecting all columns in my table
private String[] allColumns = { MyObjectDatabaseHelper.COLUMN_ONE
MyObjectDatabaseHelper.COLUMN_TWO,
MyObjectDatabaseHelper.COLUMN_THREE,
MyObjectDatabaseHelper.COLUMN_FOUR,
MyObjectDatabaseHelper.COLUMN_FIVE,
MyObjectDatabaseHelper.COLUMN_SIX,
MyObjectDatabaseHelper.COLUMN_SEVEN,
MyObjectDatabaseHelper.COLUMN_EIGHT};
public MyObject getSession(UUID mUUID)
{
db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(MyObjectDatabaseHelper.TABLE_MYOBJECT,
allColumns,
MyObjectDatabaseHelper.COLUMN_ONE + "=?",
new String [] {mUUID.toString()},
null,
null,
null,
null);
if (cursor != null)
{
cursor.moveToFirst();
}
MyObject mMyObject = new MyObject(UUID.fromString(cursor.getString(1)),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getInt(7));
cursor.close();
return mMyObject;
}
In this example, I selected all the columns in the table, then used all those values in the constructor for my custom object. What you can do is only select one column, if that's all you need, and then use that value to set the text in your TextView.
You might do something like this:
public getColumnText()
{
String text = cursor.getString(column);
return text;
}
For more information on query(...), see here.
public Cursor query (String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy,
String limit)
For more SQLite tutorials, see below:
http://www.tutorialspoint.com/android/android_sqlite_database.htm
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
http://www.vogella.com/tutorials/AndroidSQLite/article.html#overview_sqlite
i am new in android. i created a database and a listview. i want to add picture to listview by take picture by camera.
this is my input class:
package com.kalagar.warehouse;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class AddNew extends Activity implements View.OnClickListener {
ImageButton ib;
Button b;
ImageView iv;
EditText etName,etKharid,etForoush;
Intent i;
final static int CameraData = 0;
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addnew);
startAddNew();
}
private void startAddNew() {
ib = (ImageButton) findViewById(R.id.ibTakePic);
b = (Button) findViewById(R.id.bSave);
iv = (ImageView) findViewById(R.id.ivPic);
etName = (EditText) findViewById(R.id.etName);
etKharid = (EditText) findViewById(R.id.etKharid);
etForoush = (EditText) findViewById(R.id.etForoush);
b.setOnClickListener(this);
ib.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ibTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraData);
break;
case R.id.bSave:
boolean didItWork = true;
try {
String name = etName.getText().toString();
String kharid = etKharid.getText().toString();
String foroush = etForoush.getText().toString();
DataBase entry = new DataBase(AddNew.this);
entry.open();
entry.createEntry(name, kharid, foroush);
entry.close();
} catch (Exception e) {
// TODO Auto-generated catch block
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("oooh ! Nooo !!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
e.printStackTrace();
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heck Yea!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
}
this is my input XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="نام محصول"
>
<requestFocus />
</EditText>
<EditText
android:id="#+id/etKharid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="قیمت خرید"
android:inputType="number"
/>
<EditText
android:id="#+id/etForoush"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="قیمت فروش"
android:inputType="number"
/>
<ImageButton
android:id="#+id/ibTakePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_gravity="center"/>
<ImageView
android:id="#+id/ivPic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_gravity="center"/>
<Button
android:id="#+id/bSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ذخیره"
android:layout_gravity="center" />
</LinearLayout>
this is my DataBase :
package com.kalagar.warehouse;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBase {
private static final String LOGTAG = "WAREHOUSE";
private static final String DATABASE_TABLE = "WareHouse";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "SellList";
public static final String ROW_ID = "_id";
public static final String ROW_NAME = "nameOfObject";
public static final String ROW_KHARID = "ghBuy";
public static final String ROW_FOROUSH = "ghSell";
public static final String ROW_PICTURE = "picture";
private static final String TABLE_CREATE = "CREATE TABLE " + DATABASE_TABLE
+ " (" + ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ROW_NAME
+ " TEXT, " + ROW_KHARID + " NUMERIC, " + ROW_FOROUSH
+ " NUMERIC, " + ROW_PICTURE + " TEXT " + ")";
private WareHouseDdbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class WareHouseDdbHelper extends SQLiteOpenHelper {
public WareHouseDdbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
Log.i(LOGTAG, "Table has been create");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
onCreate(db);
}
}
public DataBase(Context c) {
ourContext = c;
}
public DataBase open() throws SQLException {
ourHelper = new WareHouseDdbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name, String kharid, String foroush) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(ROW_NAME, name);
cv.put(ROW_KHARID, kharid);
cv.put(ROW_FOROUSH, foroush);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public ArrayList<String> getDataName() {
// TODO Auto-generated method stub
String[] columns = new String[] { ROW_ID, ROW_NAME, ROW_KHARID,
ROW_FOROUSH };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
ArrayList<String> result = new ArrayList<String>();
int iRow = c.getColumnIndex(ROW_ID);
int iName = c.getColumnIndex(ROW_NAME);
int iKharid = c.getColumnIndex(ROW_KHARID);
int iForoush = c.getColumnIndex(ROW_FOROUSH);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result.add(c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iKharid) + " " + c.getString(iForoush));
}
return result;
}
}
this is my class for show data in listView:
package com.kalagar.warehouse;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Show extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
Name();
}
private void Name() {
ListView tvName = (ListView) findViewById(R.id.lvListOfObject);
DataBase infoName = new DataBase(this);
infoName.open();
ArrayList<String> dataName = infoName.getDataName();
infoName.close();
tvName.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, dataName));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.show, menu);
return true;
}
}
and this is my ListView XML that i want add picture to each row:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tvListHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textSize="30dp"
android:text="لیست محصولات" />
<ListView
android:id="#+id/lvListOfObject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView1"
android:layout_centerHorizontal="true" >
</ListView>
<SearchView
android:id="#+id/searchView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/tvListHeader" >
</SearchView>
</RelativeLayout>
how can i show ListView With this Template:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/ivPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:maxHeight="80dp"
android:maxWidth="80dp"
android:src="#drawable/download" />
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/name_shown_here"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvKharid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tvForoush"
android:layout_centerHorizontal="true"
android:text="Kharid" />
<TextView
android:id="#+id/tvForoush"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ivPicture"
android:layout_alignLeft="#+id/tvKharid"
android:text="Foroush" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tvKharid"
android:layout_alignParentRight="true"
android:text="قیمت خرید" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvForoush"
android:layout_alignBottom="#+id/tvForoush"
android:layout_alignParentRight="true"
android:text="قیمت فروش" />
</RelativeLayout>
what code i need to add and where i need to add?
Sorry for my english !
why you don't save picture in Sdcard instead of databse.
This link help you to do so
I'm having a bit of trouble figuring out how to bind data from sqlite to a listview.
Here my entire code and I'd be very thankful for some help or tips.
The trouble here is that i'm getting the following exception:
Illegalargumentexception: the column "_id" does not exist, when calling GetCursor in SimpleCursorAdapter.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#android:id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
item_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24dp"
android:padding="6dp" />
<TextView
android:id="#+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:padding="1dp" />
<TextView
android:id="#+id/date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:padding="4dp"
android:gravity="right" />
</LinearLayout>
Class implementing SQLite
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class DataHelper {
private static final String DATABASE_NAME = "example.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "table1";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private Cursor cursor;
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
}
public long insert(String name, String time, String date) {
insertStmt = db.compileStatement("insert into table1 values(?,?,?)");
this.insertStmt.bindString(1, name);
this.insertStmt.bindString(2, time);
this.insertStmt.bindString(3, date);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public Cursor GetCursor() {
cursor = this.db.query(TABLE_NAME, new String[] { "_id", "name", "time", "date" }, null, null, null, null, "date desc");
return cursor;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, time TEXT, date TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example",
"Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
}
}
onCreate class
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
public class SqlTest extends ListActivity {
private DataHelper dh;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Date now = new Date();
String time = now.getHours() + ":" + now.getMinutes();
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
String date = df.format(now);
this.dh = new DataHelper(this);
this.dh.deleteAll();
this.dh.insert("Porky Pig", time, date);
this.dh.insert("Foghorn Leghorn", time, date);
this.dh.insert("Yosemite Sam", time, date);
this.dh.insert("SD", time, date);
String[] columns = new String[] { "_id", "name", "time", "date" };
int[] to = new int[] {R.id.name, R.id.time, R.id.date};
SimpleCursorAdapter mAdap = new SimpleCursorAdapter(this, R.layout.main, this.dh.GetCursor(), columns, to);
this.setListAdapter(mAdap);
}
}
Try this:
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
public class SqlTest extends ListActivity {
private DataHelper dh;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Date now = new Date();
String time = now.getHours() + ":" + now.getMinutes();
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
String date = df.format(now);
this.dh = new DataHelper(this);
this.dh.deleteAll();
this.dh.insert("Porky Pig", time, date);
this.dh.insert("Foghorn Leghorn", time, date);
this.dh.insert("Yosemite Sam", time, date);
this.dh.insert("SD", time, date);
// Don't put _id here
String[] columns = new String[] {"name", "time", "date" };
int[] to = new int[] {R.id.name, R.id.time, R.id.date};
SimpleCursorAdapter mAdap = new SimpleCursorAdapter(this, R.layout.main, this.dh.GetCursor(), columns, to);
this.setListAdapter(mAdap);
}
}