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

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;

Related

Why my database deletion code did not works

My Database program works so far with submit and show data function. But deletion and modify database function is not working. I have attached the code for EventsDB.java and EventDetail.java and their resource layout file. Basically there is no problem with submit and show data part. i haven done the modify part and deletion part just din work.Please help.
package com.cinrafood.teopeishen.databasedemo;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText etEvent,etEventDetail,etDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
etEvent=(EditText)findViewById(R.id.etEvent);
etEventDetail= (EditText)findViewById(R.id.etEventDetail);
etDate=(EditText)findViewById(R.id.etDate);
}
public void btnSubmit (View view)
{
try{
String event = etEvent.getText().toString();
String eventDetail = etEventDetail.getText().toString();
String date= etDate.getText().toString();
EventsDB db = new EventsDB(this);
db.open();
db.createEntry(event,eventDetail,date);
db.close();
Toast.makeText(MainActivity.this,"Successfully saved!!",Toast.LENGTH_LONG).show();
etDate.setText("");
etEventDetail.setText("");
etEvent.setText("");
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
Toast.makeText(this,"Please fill up all field",Toast.LENGTH_LONG).show();
}
}
public void btnShowEvents (View view)
{
startActivity(new Intent(this,EventData.class));
}
}
package com.cinrafood.teopeishen.databasedemo;
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 java.util.ArrayList;
public class EventsDB
{
public static final String KEY_ROWID ="_id";
public static final String KEY_EVENT="event_name";
public static final String KEY_EVENT_DESCRIPTIOM="event_description";
public static final String KEY_DATE="event_date";
private final String DATABASE_NAME="EventsDB";
private final String DATABASE_TABLE="EventsTable";
private final int DATABASE_VERSION=1;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private ArrayList<Event> events;
public EventsDB(Context context)
{
ourContext= context;
}
private class DBHelper extends SQLiteOpenHelper
{
public DBHelper (Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
/*
CREATE TABLE EventsTable (_id INTEGER PRIMARY KEY AUTOINCREMENT,
event_name TEXT NOT NULL,event_description TEXT NOT NULL,
event_date DATE NOT NULL);
*/
String sqlCode="CREATE TABLE "+DATABASE_TABLE+" ("+
KEY_ROWID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_EVENT+" TEXT NOT NULL, "+
KEY_EVENT_DESCRIPTIOM+" TEXT NOT NULL, "+
KEY_DATE+" TEXT NOT NULL);";
db.execSQL(sqlCode);
}
}
public EventsDB open() throws SQLException
{
ourHelper = new DBHelper(ourContext);
ourDatabase=ourHelper.getWritableDatabase();
events= new ArrayList<Event>();
return this;
}
public void close()
{
ourHelper.close();
}
public long createEntry(String event_name, String event_description, String event_date)
{
ContentValues cv = new ContentValues();
cv.put(KEY_EVENT,event_name);
cv.put(KEY_EVENT_DESCRIPTIOM,event_description);
cv.put(KEY_DATE,event_date);
return ourDatabase.insert(DATABASE_TABLE,null,cv);
}
public ArrayList<Event> getData()
{
String [] columns = new String[]{KEY_ROWID,KEY_EVENT,KEY_EVENT_DESCRIPTIOM,KEY_DATE};
Cursor c = ourDatabase.query(DATABASE_TABLE,columns,null,null,null,null,null);
int iRowID = c.getColumnIndex(KEY_ROWID);
int iEvent = c.getColumnIndex(KEY_EVENT);
int iEventDescription = c.getColumnIndex(KEY_EVENT_DESCRIPTIOM);
int iDate = c.getColumnIndex(KEY_DATE);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
Event event = new Event(c.getInt(iRowID),c.getString(iEvent),c.getString(iEventDescription),c.getString(iDate));
events.add(event);
}
return events;
}
public long deleteEntry (String rowID){
return ourDatabase.delete(DATABASE_TABLE,KEY_ROWID+"=?",new String[]{rowID});
}
public long updateEntry(String rowID, String event_name, String event_description, String event_date)
{
ContentValues cv = new ContentValues();
cv.put(KEY_EVENT,event_name);
cv.put(KEY_EVENT_DESCRIPTIOM,event_description);
cv.put(KEY_DATE,event_date);
return ourDatabase.update(DATABASE_TABLE,cv,KEY_ROWID+"=?",new String[]{rowID});
}
}
package com.cinrafood.teopeishen.databasedemo;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class EventData extends AppCompatActivity {
ListView lvEvents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_data);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try{
EventsDB db = new EventsDB(this);
db.open();
lvEvents= (ListView)findViewById(R.id.lvEvents);
lvEvents.setAdapter(new CustomAdapter(db.getData(),getApplicationContext()));
db.close();
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
AdapterView.OnItemLongClickListener click = new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventData.this,EventDetail.class);
intent.putExtra("Location",position);
startActivity(intent);
return true;
}
};
lvEvents.setOnItemLongClickListener(click);
}
}
package com.cinrafood.teopeishen.databasedemo;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
public class EventDetail extends AppCompatActivity {
EditText etTitlePage,etEventDetailPage,etDatePage;
Button btnDeleteEvent;
int location;
ArrayList<Event> events;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etTitlePage=(EditText) findViewById(R.id.etTitlePage);
etEventDetailPage=(EditText) findViewById(R.id.etEventDetailPage);
etDatePage=(EditText) findViewById(R.id.etDatePage);
btnDeleteEvent=(Button)findViewById(R.id.btnDeleteEvent);
try{
EventsDB db = new EventsDB(this);
db.open();
events=db.getData();
location = getIntent().getIntExtra("Location",0);
etTitlePage.setText(events.get(location).getEvent_name());
etEventDetailPage.setText(events.get(location).getEvent_description());
etDatePage.setText(events.get(location).getEvent_date());
db.close();
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
btnDeleteEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
EventsDB db = new EventsDB(getApplicationContext());
db.open();
db.deleteEntry((location+1)+"");
db.close();
Toast.makeText(getApplicationContext(),"Successfully deleted!!",Toast.LENGTH_LONG).show();
}catch (SQLException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public Integer deleteContacts (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
Actually you have passed position of the item in ListView to delete that item from database which is not correct. You have to pass the rowId of database primary key to complete the delete operation.
AdapterView.OnItemLongClickListener click = new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Retrieve Event from adapter
Event event = lvEvents.getAdapter().getItem(position);
Intent intent = new Intent(EventData.this,EventDetail.class);
intent.putExtra("Location", event.getRowId()); // get rowId from event.
startActivity(intent);
return true;
}
};
And execute delete operation using that rowId
db.deleteEntry(location + "");

Database saving all the details rather than the image

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;
}
}

SQLiteAssetHelper and getWritableDatabase

I'm having have some trouble with my Database activity. I am unable to write to the database and view the database using the following code.
my Database activity:
package com.jacob.eindproject;
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.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class Database extends SQLiteAssetHelper {
public static final String KEY_PRODUCT = "Product";
public static final String KEY_EENHEID = "Eenheid";
public static final String KEY_KCAL = "Kcal";
private static final String DATABASE_NAME = "Voedsel";
private static final String DATABASE_TABLE = "Voeding";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
#Override
public void onUpgrade(SQLiteDatabase Voedsel, int oldVersion, int newVersion) {
Voedsel.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(Voedsel);
}
public void close(Database database) {
// TODO Auto-generated method stub
}
public Database(Context c){
ourContext = c;
}
public Database open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String product, String kcal, String eenheid) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRODUCT, product);
cv.put(KEY_EENHEID, eenheid);
cv.put(KEY_KCAL, kcal);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_PRODUCT, KEY_EENHEID, KEY_KCAL};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_PRODUCT);
int iName = c.getColumnIndex(KEY_EENHEID);
int iHotness = c.getColumnIndex(KEY_KCAL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
}
My SQLView activity:
package com.jacob.eindproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
Database info = new Database(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
SQLite activity:
package com.jacob.eindproject;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;
public class SQLite extends Activity implements View.OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlVoeding, sqlKcal, sqlEenheid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllite);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlVoeding = (EditText) findViewById(R.id.etSQLVoeding);
sqlEenheid = (EditText) findViewById(R.id.etSQLEenheid);
sqlKcal = (EditText) findViewById(R.id.etSQLKcal);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener((android.view.View.OnClickListener) this);
sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String voeding = sqlVoeding.getText().toString();
String Kcal = sqlKcal.getText().toString();
String eenheid = sqlEenheid.getText().toString();
Database entry = new Database(SQLite.this);
entry.open();
entry.createEntry(voeding, Kcal, eenheid);
entry.close();
}catch (Exception e ){
didItWork = false;
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heak Yeay");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
Intent i = new Intent(this, SQLView.class);
startActivity(i);
}
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
I am having my database file(Voedsel.rar), in assets/databases/Voedsel.rar.
To write to your database, try a method like this:
public void insertVoeding(String product, String eenheid, String kcal) {
ourDatabase.execSQL("INSERT INTO Voeding (Product, Eenheid, Kcal) VALUES (?, ?, ?)",
new String[] {product, eenheid, kcal});
}
The question marks are replaced by the values in the string array. Your column names cannot be inserted using the string array, because the execSQL method puts quotation marks around these values. The query will fail if you try.
There are two ways to read from a database (may even be two ways to write to it, too). I personally prefer using raw queries, like this one to get the entire database:
public Cursor getEntireDB() {
return ourDatabase.rawQuery("SELECT * FROM Voeding");
}
You can then use the cursor in a CursorAdapter to create a list.

java.lang.NullPointerException when adding data to sqlite

I am getting Nullpointerexception error when checked rdio4
Codes:
Answerpage.java
package com.example.psikotestproject;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class AnswerPage extends Activity{
#Override
protected void onDestroy() {
super.onDestroy();
}
DbHelper dbhelper;
SQLiteDatabase db;
Context contextim;
int i=1;
int obko=0;
int soma=0;
int kadu=0;
int depr=0;
int foan=0;
static float somahesap=0.0f;
static float obkohesap=0.0f;
static float kaduhesap=0.0f;
static float deprhesap=0.0f;
static float foanhesap=0.0f;
//dizim
final String questions[]={
"Baş ağrısı" ,
"Sinirlilik ya da içinin titremesi",
"Zihinden atamadığınız tekrarlayan, hoşa gitmeyen düşünceler",
"Baygınlık ya da baş dönmesi",
"Cinsel arzu ve ilginin kaybı",
"Başkaları tarafından eleştirilme duygusu",
"Herhangi bir kimsenin düşüncelerinizi kontrol edebileceği
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.answerpage);
//component tanımları
final TextView txtquestion=(TextView)findViewById(R.id.txtquestion);
final RadioGroup rdiogroup=(RadioGroup)findViewById(R.id.rdiogroup);
final RadioButton rdio0=(RadioButton)findViewById(R.id.rdio0);
final RadioButton rdio1=(RadioButton)findViewById(R.id.rdio1);
final RadioButton rdio2=(RadioButton)findViewById(R.id.rdio2);
final RadioButton rdio3=(RadioButton)findViewById(R.id.rdio3);
final RadioButton rdio4=(RadioButton)findViewById(R.id.rdio4);
final Button btndigersoru=(Button)findViewById(R.id.btndigersoru);
final Button btnoncekisoru=(Button)findViewById(R.id.btnoncekisoru);
txtquestion.setText(questions[i-1]);
//diğersorubutonclick
btndigersoru.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if(rdio0.isChecked()||rdio1.isChecked()||rdio2.isChecked()||rdio3.isChecked()||rdio4.isChecked())
{
txtquestion.setText(questions[i]);
if(rdio0.isChecked()==true)
{
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
if(rdio1.isChecked()==true)
{
if(i==1||i==4||i==12||i==27||i==40||i==42||i==48||i==52||i==53||i==56||i==58)
soma++;
if(i==3||i==9||i==10||i==28||i==38||i==45||i==46||i==51||i==55||i==65)
obko++;
if(i==6||i==21||i==34||i==36||i==37||i==41||i==61||i==69||i==73)
kadu++;
if(i==4||i==5||i==15||i==20||i==22||i==26||i==29||i==30||i==31||i==32||i==54||i==71||i==79)
depr++;
if(i==13||i==25||i==47||i==50||i==70||i==75||i==82)
foan++;
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
if(rdio2.isChecked()==true)
{
if(i==1||i==4||i==12||i==27||i==40||i==42||i==48||i==52||i==53||i==56||i==58)
soma=soma+2;
if(i==3||i==9||i==10||i==28||i==38||i==45||i==46||i==51||i==55||i==65)
obko=obko+2;
if(i==6||i==21||i==34||i==36||i==37||i==41||i==61||i==69||i==73)
kadu=kadu+2;
if(i==4||i==5||i==15||i==20||i==22||i==26||i==29||i==30||i==31||i==32||i==54||i==71||i==79)
depr=depr+2;
if(i==13||i==25||i==47||i==50||i==70||i==75||i==82)
foan=foan+2;
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
if(rdio3.isChecked()==true)
{
if(i==1||i==4||i==12||i==27||i==40||i==42||i==48||i==52||i==53||i==56||i==58)
soma=soma+3;
if(i==3||i==9||i==10||i==28||i==38||i==45||i==46||i==51||i==55||i==65)
obko=obko+2;
if(i==6||i==21||i==34||i==36||i==37||i==41||i==61||i==69||i==73)
kadu=kadu+2;
if(i==4||i==5||i==15||i==20||i==22||i==26||i==29||i==30||i==31||i==32||i==54||i==71||i==79)
depr=depr+2;
if(i==13||i==25||i==47||i==50||i==70||i==75||i==82)
foan=foan+3;
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
if(rdio4.isChecked()==true)
{
if(i==1||i==4||i==12||i==27||i==40||i==42||i==48||i==52||i==53||i==56||i==58)
soma=soma+4;
if(i==3||i==9||i==10||i==28||i==38||i==45||i==46||i==51||i==55||i==65)
obko=obko+4;
if(i==6||i==21||i==34||i==36||i==37||i==41||i==61||i==69||i==73)
kadu=kadu+4;
if(i==4||i==5||i==15||i==20||i==22||i==26||i==29||i==30||i==31||i==32||i==54||i==71||i==79)
depr=depr+4;
if(i==13||i==25||i==47||i==50||i==70||i==75||i==82)
foan=foan+4;
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
}
if(i<16)
i++;
else{}
if(i>1)
{
btnoncekisoru.setVisibility(View.VISIBLE);
}
if(i>=9)
//if(i>=90)
{
//En son hesaplar
somahesap=(float) (soma/11.0);
obkohesap=(float) (obko/10.0);
kaduhesap=(float) (kadu/9.0);
deprhesap=(float) (depr/13.0);
foanhesap=(float) (foan/7.0);
Intent finishingActivity=new Intent("com.example.psikotestproject.RESULTPAGE");
startActivity(finishingActivity);
}
}
});
//btnoncekibutonclick
btnoncekisoru.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
rdiogroup.clearCheck();
dbhelper.getKayitlar(i-1);
txtquestion.setText(questions[i-1]);
i--;
//rdiogroup.check(secili[i]);
if(i<=0)
{
btnoncekisoru.setVisibility(View.INVISIBLE);
}
}
});
}
Dbhelper.java
public class DbHelper extends SQLiteOpenHelper {
// Tüm Static değişkenler
// Database Versiyonu
private static final int DATABASE_VERSION = 1;
// Database Adı
private static final String DATABASE_NAME = "dbSecimler";
// Kayitlar Tablosunun Adı
private static final String TABLE_NAME = "Secimler";
// Kayitlar Tablosunun Kolon Adları
private static final String KEY_CEVAP = "Cevaplar";
// Yapılandırıcı metod
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Database Oluşturma işlemi.
#Override
public void onCreate(SQLiteDatabase db) {
String create_table = "CREATE TABLE " + TABLE_NAME + "(id INTEGER PRİMARY KEY AUTOINCREMENT"
+ KEY_CEVAP + " INTEGER," + ")";
db.execSQL(create_table);
}
// Database Yükseltme işlemi.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Varsa şayet eski tabloyu sil.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Tekrar tablo oluştur.
onCreate(db);
}
// Yeni Kayıt Eklemek.
void addKayitlar(int i) {
SQLiteDatabase db= this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CEVAP, i);
// Ekleme işlemi...
db.insert(TABLE_NAME, null , values);
db.close(); // Açık olan database i kapat.
}
//İstenilen Kaydı Getirmek.
Kayitlar getKayitlar(int i) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] {KEY_CEVAP},null, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Kayitlar kayit = new Kayitlar(Integer.parseInt(cursor.getString(1)));
// return Kayitlar
return kayit;
}
}
Errors on LogCat
threadid=1: thread exiting with uncaught exception (group=0x4001d800)
FATAL EXCEPTION: main
java.lang.NullPointerExceptionat com.example.psikotestproject.AnswerPage$1.onClick(AnswerPage.java:282)
-
-
-
and 282 is: dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
rdiogroup.getCheckedRadioButtonId() not null I'm sure.I think I have an error about saving database.What can I solve?
It seems that you are missing findViewById() for the view for which you have implemented onClickListener.

How to use edittext.getText().toString()

I want to make it so that there is a ListView with a Button above it. The users clicks that button, and it opens a dialog with an EditText and an OK and Cancel button. When the user clicks OK, whatever text is entered into the EditText gets put into the SQLiteDatabase, which is reflected in the ListView.
I've already set up my SQLiteDatabase and have set an adapter for the List to show the SQLiteDatabase, but I need to figure out how to use the edittext.getText().toString() method to add to the SQLiteDatabase. I will need a code example.
If you need it, here's my main .java:
package com.gantt.shoppinglist;
import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class ShoppingList extends ListActivity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DataHelper dataHelper = new DataHelper(this);
ListView lv = (ListView) findViewById(android.R.id.list);
SimpleCursorAdapter adapter = null;
final SQLiteDatabase db = dataHelper.selectAll();
Cursor c = db.rawQuery("SELECT DISTINCT oid as _id,name FROM table1 ORDER BY name", null);
if (c.moveToFirst()) {
String[] columnNames = new String[]{"name"};
int[] list = new int[]{android.R.id.list};
adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, c, columnNames, list);
}
lv.setAdapter(adapter);
Button button1main = (Button) findViewById(R.id.add);
button1main.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog additem = new Dialog(ShoppingList.this);
additem.setContentView(R.layout.maindialog);
final EditText et = (EditText)additem.findViewById(R.id.edittext);
additem.setTitle("Type your item");
additem.setCancelable(true);
et.setHint("Type the name of an item...");
Button button = (Button) additem.findViewById(R.id.cancel);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
additem.dismiss();
}
});
additem.show();
Button ok = (Button) additem.findViewById(R.id.ok);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
et.getText().toString();
additem.dismiss();
et.setText("");
}
});
}
});
}
}
Here is my DataHelper class:
package com.gantt.shoppinglist;
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;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class DataHelper {
public static final String DATABASE_NAME = "items.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "table1";
public static final String KEY_ROWID = "_id";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public SQLiteDatabase selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return db;
}
public static String getDatabaseName() {
return DATABASE_NAME;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, getDatabaseName(), null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name 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(db);
}
}
}
Using the current methods you have, and assuming that you understand the code that you used for the database adapter, just do this:
String item = et.getText().toString();// these two lines are the
dataHelper.insert(item); // only change you have to do
additem.dismiss();
et.setText("");
After doing this, you have to call the notifyDataSetChanged method of your SimpleCursorAdapter object.
A simple sample method for your DataHelper class:
public long createUser(String email, String password, String fullName) {
ContentValues initialValues = new ContentValues();
initialValues.put("email", email);
initialValues.put("password", password);
initialValues.put("fullName", fullName);
return mDb.insert(TABLE_NAME, null, initialValues);
}

Categories

Resources