SQLite database queries very slow (SQLite Asset Helper) - android

I'm working on a app where saxophone players can choose a saxophone (soprano, alto, tenor or baritone). The database should output all the music pieces that are available for that specific saxophone, together with the composer and publisher.
I've used a prepopulated db (created with SQLite Manager) and used the SQLite Asset Helper.
The database (so far) has some 600 records.
Whenever I query the database (let's say on 'alto'), it takes some 10 seconds before the results are found.
I've tried many things: indexing (both in the db file as in the Java code), changed between sqlite-file and db-file, tried on a real device instead of emulator etc, etc.
Nothing seems to work... I hope someone out there can help me on this...
I use two java classes: MyDatabase and SQLiteOpenHelper. If you need more info, please let me know.
MyDatabase class:
package com.example.musicrepertoiredatabase2;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class MyDatabase extends SQLiteAssetHelper {
SqliteAssetHelper helper = new SqliteAssetHelper();
private static final String DATABASE_NAME = "saxophone_repertoire.sqlite";
private static final String TABLE_NAME = "repertoire";
private static final int DATABASE_VERSION = 1;
private static final String ID = "id";
private static final String COMPOSER = "composer";
private static final String TITLE = "title";
private static final String PUBLISHER = "publisher";
private static final String SAXOPHONE = "saxophone";
private static final String ACCOMPANIMENT = "form";
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String saxSort = SqliteAssetHelper.chooseSax;
String composer = SqliteAssetHelper.chooseComposer;
Cursor result = db.rawQuery("SELECT Composer, id FROM " + TABLE_NAME
+ " WHERE " + SAXOPHONE + "='" + saxSort + "'", null);
return result;
}
}
My SQLiteAssetHelper class:
package com.example.musicrepertoiredatabase2;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SqliteAssetHelper extends ActionBarActivity implements
OnItemSelectedListener, OnClickListener {
TextView composer, title, saxophone, accompaniment, showInfo, count;
EditText etComposer, etTitle;
Spinner spinnerSaxophone, spinnerAccompaniment;
Button search, clear;
String[] arraySaxophone = { "Soprano", "Alto", "Tenor", "Baritone" };
String[] arrayAccompaniment = { "Solo", "Piano" };
public static String chooseSax = null;
public static String chooseComposer = null;
Handler updateBarHandler;
private MyDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateBarHandler = new Handler();
spinnerSaxophone = (Spinner) findViewById(R.id.spinner_saxophone);
spinnerSaxophone.setOnItemSelectedListener(this);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySaxophone);
spinnerSaxophone.setAdapter(adapter1);
spinnerAccompaniment = (Spinner) findViewById(R.id.spinner_accompaniment);
spinnerAccompaniment.setOnItemSelectedListener(this);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayAccompaniment);
spinnerAccompaniment.setAdapter(adapter2);
etComposer = (EditText) findViewById(R.id.et_composer);
etComposer.setHint(Html.fromHtml("<small>"
+ getString(R.string.hint_composer) + "<small>"));
etTitle = (EditText) findViewById(R.id.et_title);
etTitle.setHint(Html.fromHtml("<small>"
+ getString(R.string.hint_title) + "<small>"));
search = (Button) findViewById(R.id.btn_search);
clear = (Button) findViewById(R.id.btn_clear);
search.setOnClickListener(this);
clear.setOnClickListener(this);
showInfo = (TextView) findViewById(R.id.tv_showinfo);
count = (TextView) findViewById(R.id.tv_count);
db = new MyDatabase(this);
}
public void launchRingDialog() {
final ProgressDialog ringProgressDialog = ProgressDialog.show(this,
"Searching database...", "Please wait...", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable(){
#Override
public void run(){
try{
Thread.sleep(5000);
}catch (Exception e){
}
ringProgressDialog.dismiss();
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
int choosePositionSax = spinnerSaxophone.getSelectedItemPosition();
switch (choosePositionSax) {
case 0:
chooseSax = "Soprano";
break;
case 1:
chooseSax = "Alto";
break;
case 2:
chooseSax = "Tenor";
break;
case 3:
chooseSax = "Baritone";
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_search:
launchRingDialog();
chooseComposer = etComposer.getText().toString();
Cursor result = db.getData();
if (result.getCount() == 0) {
Toast.makeText(this, "Nothing found", Toast.LENGTH_SHORT)
.show();
}
launchRingDialog();
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()) {
//buffer.append("Title: " + result.getString(2) + "\n");
buffer.append("Composer: " + result.getString(1) + "\n\n");
showInfo.setText(buffer);
int countFiles = result.getCount();
count.setText(Integer.toString(countFiles));
}
break;
case R.id.btn_clear:
showInfo.setText("");
etComposer.setText("");
etComposer.requestFocus();
break;
default:
break;
}
}
}

Well you have to wait for 5 seconds, why =) ?
Thread.sleep(5000);
Delete this line and your query will be faster!
I have seen that you have launchRingDialog() declared two times in your code so you have to wait for 10 seconds. Your query should last no more than milliseconds so probably you don´t need any ProgressDialog.

I'd suggest adding an index to your table:
Create Index IF NOT EXISTS _index_saxophone on T_ResultsSummary(saxophone);

Related

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

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

Unfortunately this app has stopped working (SQLiteDatabase) [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
I have this problem: I wrote an app, but the SQLiteDatabase isn't working.
My database class code:
package com.example.frauprinzssapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class database extends SQLiteOpenHelper{
public static final String DB_NAME = "users.db";
public static final String DB_TABLENAME = "users_table";
public static final String COL_1 = "id";
public static final String COL_2 = "name";
public static final String COl_3 = "class";
public static final String COL_4 = "right";
public database(Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+DB_TABLENAME+"(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, class TEXT, right INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST "+DB_TABLENAME);
onCreate(db);
}
public boolean insertdata(String name, String clas){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_2, name);
cv.put(COl_3, clas);
cv.put(COL_4, 0);
long result = db.insert(DB_TABLENAME, null, cv);
if (result == -1){
return false;
}else{
return true;
}
}
}
The main code is:
package com.example.frauprinzssapp;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {
List<String> addusers = new ArrayList<String>();
database myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myDb = new database(this);
}
//-----change view voids-----
public void main(View view){
setContentView(R.layout.main);
}
public void adduser(View view){
setContentView(R.layout.adduser);
}
public void removeuser(View view){
setContentView(R.layout.removeuser);
}
//------actions------
public void add(){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
if (name.toString() == null || clas.toString() == null){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
try{
myDb.insertdata(name.toString(), clas.toString());
Toast.makeText(Main.this, "added user "+name.toString()+"!", Toast.LENGTH_LONG);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
}
}
public void remove(){
}
public void show(){
}
}
I used the
android:onClick="add"
to make so that the add() void runs
please now it just puts random stuff into the sqlite pleaseeeee help
try it....
//------actions------
public void add(){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
String name1 = name.getText().toString();
String clas1 = clas.getText().toString();
if (name1.equals("") || clas1.equals("")){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
try{
myDb.insertdata(name1, clas1);
Toast.makeText(Main.this, "added user "+name1+"!", Toast.LENGTH_LONG);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
}
}

Unable to add ArrayList to internal database android and creating a recycler view

I am trying to create a recycler view after adding data via ArrayList to an sqlite database but I am getting null pointer exception while fetching the data from the database and displaying the recycler view via the adapter.
Here is the code for my internal database :
package com.packr.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import com.packr.classes.Shipment;
import com.packr.logging.L;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by arindam.paaltao on 04-Aug-15.
*/
public class DBShipments {
public static final int MY_SHIPMENTS = 0;
private ShipmentsHelper mHelper;
private SQLiteDatabase mDatabase;
public DBShipments(Context context) {
mHelper = new ShipmentsHelper(context);
mDatabase = mHelper.getWritableDatabase();
}
public void insertShipment(ArrayList<Shipment> shipmentArrayList, boolean clearPrevious) {
if (clearPrevious) {
deleteShipments();
}
//create a sql prepared statement
String sql = "INSERT INTO " + (ShipmentsHelper.TABLE_MY_SHIPMENTS) + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?);";
//compile the statement and start a transaction
SQLiteStatement statement = mDatabase.compileStatement(sql);
mDatabase.beginTransaction();
for (int i = 0; i < shipmentArrayList.size(); i++) {
Shipment current = shipmentArrayList.get(i);
statement.clearBindings();
//for a given column index, simply bind the data to be put inside that index
statement.bindString(2,current.getRecipientName());
statement.bindString(3,current.getRecipientContact());
statement.bindString(4, current.getItemQuantity());
statement.bindString(5, current.getItemType());
statement.bindString(6, current.getDeliveryType());
statement.bindString(7, current.getStreetNo());
statement.bindString(8, current.getRoute());
statement.bindString(9, current.getState());
statement.bindString(10, current.getCity());
statement.bindString(11, current.getPostalCode());
statement.bindDouble(12,current.getLatitude());
statement.bindDouble(13, current.getLongitude());
statement.execute();
}
//set the transaction as successful and end the transaction
L.m("inserting entries " + shipmentArrayList.size() + new Date(System.currentTimeMillis()));
mDatabase.setTransactionSuccessful();
mDatabase.endTransaction();
}
public ArrayList<Shipment> readShipments() {
ArrayList<Shipment> shipmentArrayList = new ArrayList<>();
//get a list of columns to be retrieved, we need all of them
String[] columns = {
ShipmentsHelper.COLUMN_ID,
ShipmentsHelper.COLUMN_RECIPIENT_NAME,
ShipmentsHelper.COLUMN_RECIPIENT_CONTACT,
ShipmentsHelper.COLUMN_ITEM_QUANTITY,
ShipmentsHelper.COLUMN_ITEM_TYPE,
ShipmentsHelper.COLUMN_DELIVERY_TYPE,
ShipmentsHelper.COLUMN_STREET_NO,
ShipmentsHelper.COLUMN_ROUTE,
ShipmentsHelper.COLUMN_LOCALITY,
ShipmentsHelper.COLUMN_CITY,
ShipmentsHelper.COLUMN_POSTAL_CODE,
ShipmentsHelper.COLUMN_LATITUDE,
ShipmentsHelper.COLUMN_LONGITUDE
};
Cursor cursor = mDatabase.query((ShipmentsHelper.TABLE_MY_SHIPMENTS), columns, null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
L.m("loading entries " + cursor.getCount() + new Date(System.currentTimeMillis()));
do {
//create a new movie object and retrieve the data from the cursor to be stored in this movie object
Shipment shipment = new Shipment();
//each step is a 2 part process, find the index of the column first, find the data of that column using
//that index and finally set our blank movie object to contain our data
shipment.setRecipientName(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_RECIPIENT_NAME)));
shipment.setRecipientContact(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_RECIPIENT_CONTACT)));
shipment.setItemQuantity(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_ITEM_QUANTITY)));
shipment.setItemType(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_ITEM_TYPE)));
shipment.setDeliveryType(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_DELIVERY_TYPE)));
shipment.setStreetNo(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_STREET_NO)));
shipment.setRoute(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_ROUTE)));
shipment.setCity(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_LOCALITY)));
shipment.setState(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_CITY)));
shipment.setPostalCode(cursor.getString(cursor.getColumnIndex(ShipmentsHelper.COLUMN_POSTAL_CODE)));
shipment.setLatitude(cursor.getDouble(cursor.getColumnIndex(ShipmentsHelper.COLUMN_LATITUDE)));
shipment.setLongitude(cursor.getDouble(cursor.getColumnIndex(ShipmentsHelper.COLUMN_LONGITUDE)));
//add the task to the list of task objects which we plan to return
shipmentArrayList.add(shipment);
}
while (cursor.moveToNext());
}
return shipmentArrayList;
}
public void deleteShipments() {
mDatabase.delete((ShipmentsHelper.TABLE_MY_SHIPMENTS), null, null);
}
private static class ShipmentsHelper extends SQLiteOpenHelper {
public static final String TABLE_MY_SHIPMENTS = "my_shipments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_RECIPIENT_NAME = "recipientName";
public static final String COLUMN_RECIPIENT_CONTACT = "recipientContact";
public static final String COLUMN_ITEM_QUANTITY = "itemQuantity";
public static final String COLUMN_ITEM_TYPE = "itemType";
public static final String COLUMN_DELIVERY_TYPE = "deliveryType";
public static final String COLUMN_STREET_NO = "streetNo";
public static final String COLUMN_ROUTE = "route";
public static final String COLUMN_LOCALITY = "locality";
public static final String COLUMN_CITY = "city";
public static final String COLUMN_POSTAL_CODE = "postalCode";
public static final String COLUMN_LATITUDE = "latitude";
public static final String COLUMN_LONGITUDE = "longitude";
private static final String CREATE_TABLE_MY_SHIPMENTS = "CREATE TABLE " + TABLE_MY_SHIPMENTS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_RECIPIENT_NAME + " TEXT," +
COLUMN_RECIPIENT_CONTACT + " TEXT," +
COLUMN_ITEM_QUANTITY + " TEXT," +
COLUMN_ITEM_TYPE + " TEXT," +
COLUMN_DELIVERY_TYPE + " TEXT," +
COLUMN_STREET_NO + " TEXT," +
COLUMN_ROUTE + " TEXT," +
COLUMN_LOCALITY + " TEXT," +
COLUMN_CITY + " TEXT," +
COLUMN_POSTAL_CODE + " TEXT," +
COLUMN_LATITUDE + " TEXT," +
COLUMN_LONGITUDE + " TEXT" +
");";
private static final String DB_NAME = "my_shipments_db";
private static final int DB_VERSION = 1;
private Context mContext;
public ShipmentsHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE_MY_SHIPMENTS);
L.m("create table shipments executed");
} catch (SQLiteException exception) {
L.t(mContext, exception + "");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
L.m("upgrade table shipments executed");
db.execSQL(" DROP TABLE " + TABLE_MY_SHIPMENTS + " IF EXISTS;");
onCreate(db);
} catch (SQLiteException exception) {
L.t(mContext, exception + "");
}
}
}
}
I have initialized the recycler view and fetching the recycler view from the internal database if it is not empty in this activity :
package com.packr.activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.packr.R;
import com.packr.adapters.ShipmentsAdapter;
import com.packr.classes.Packr;
import com.packr.classes.SharedPreferenceClass;
import com.packr.classes.Shipment;
import com.packr.database.DBShipments;
import com.packr.logging.L;
import java.util.ArrayList;
public class MyShipmentsActivity extends AppCompatActivity {
private static final String STATE_SHIPMENTS = "state_shipments";
private Toolbar toolbar;
private RecyclerView mRecyclerView;
private ShipmentsAdapter mShipmentAdapter;
private SharedPreferenceClass preferenceClass;
private Button addShipment;
private LinearLayout askForPickup;
private MyShipmentsActivity activity;
private ArrayList<Shipment> shipmentArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_shipments);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("My shipments");
setSupportActionBar(toolbar);
initialize();
onClick();
if (savedInstanceState != null) {
//if this fragment starts after a rotation or configuration change, load the existing movies from a parcelable
shipmentArrayList = savedInstanceState.getParcelableArrayList(STATE_SHIPMENTS);
} else {
shipmentArrayList = Packr.getWritableDatabase().readShipments();
if (shipmentArrayList.isEmpty()) {
L.T(getApplicationContext(), "No shipments found");
}
}
mRecyclerView = (RecyclerView) findViewById(R.id.shipments_recycler_view);
mShipmentAdapter = new ShipmentsAdapter(getApplicationContext(), activity);
mRecyclerView.setAdapter(mShipmentAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mShipmentAdapter.setShipmentArrayList(shipmentArrayList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my_shipments, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void initialize() {
addShipment = (Button) findViewById(R.id.add_shipment);
askForPickup = (LinearLayout) findViewById(R.id.askForPickup);
}
public void onClick() {
addShipment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!shipmentArrayList.isEmpty()) {
Intent intent = new Intent(MyShipmentsActivity.this, DeliveryAddressSearchActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(MyShipmentsActivity.this, PickupAddressSearchActivity.class);
startActivity(intent);
}
}
});
askForPickup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (shipmentArrayList.isEmpty()) {
L.T(getApplicationContext(), "No shipments found");
}
}
});
}
}
I want to insert data to the internal database from this activity. I have initialized the adapter here but getting a null pointer exception when I am trying to set the Arraylist to the adapter here.
Here is the code of the activity :
package com.packr.activities;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import com.avast.android.dialogs.fragment.SimpleDialogFragment;
import com.avast.android.dialogs.iface.ISimpleDialogListener;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import com.packr.R;
import com.packr.adapters.ShipmentsAdapter;
import com.packr.classes.Packr;
import com.packr.classes.Shipment;
import com.packr.database.DBShipments;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class ItemDetailsActivity extends AppCompatActivity implements ISimpleDialogListener, ImageChooserListener {
private Toolbar toolbar;
private ImageChooserManager imageChooserManager;
private SeekBar seekBar;
private RadioGroup radioGroup;
private TextView addImage;
private Bitmap myBitmap;
private ShipmentsAdapter mShipmentAdapter;
private ImageView itemImage;
private TextInputLayout itemDescriptionText, quantityText, valueOfItemText;
private EditText itemDescription, quantity, valueOfItem;
private TextView weightUnit, weightValue, selectWeight;
private ArrayList<Shipment> shipmentArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_details);
initialize();
onClick();
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Item details");
setSupportActionBar(toolbar);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.parcelRadioButton) {
weightUnit.setText("kg");
selectWeight.setText("Select weight of item");
if (seekBar.getVisibility() == View.GONE) {
seekBar.setVisibility(View.VISIBLE);
}
seekBar.setProgress(5);
weightValue.setText(String.valueOf(seekBar.getProgress()));
} else {
seekBar.setVisibility(View.GONE);
weightUnit.setText("gm");
selectWeight.setText("Permitted weight");
weightValue.setText("upto 500");
}
}
});
seekBar.setProgress(1);
seekBar.incrementProgressBy(5);
seekBar.setMax(15);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress = progress / 5;
progress = progress * 5;
weightValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_item_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_done) {
if (validationCheck()) {
Shipment shipment = new Shipment();
shipment.setRecipientName(getIntent().getExtras().getString("recipientName"));
shipment.setRecipientContact(getIntent().getExtras().getString("recipientContact"));
shipment.setCity(getIntent().getExtras().getString("city"));
shipment.setState(getIntent().getExtras().getString("state"));
shipment.setStreetNo(getIntent().getExtras().getString("street"));
shipment.setPostalCode(getIntent().getExtras().getString("pincode"));
shipmentArrayList.add(shipment);
**mShipmentAdapter.setShipmentArrayList(shipmentArrayList);
Packr.getWritableDatabase().insertShipment(shipmentArrayList, true);**
Intent intent = new Intent(ItemDetailsActivity.this, MyShipmentsActivity.class);
startActivity(intent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void initialize() {
seekBar = (SeekBar) findViewById(R.id.seekBar);
weightUnit = (TextView) findViewById(R.id.weightUnit);
weightValue = (TextView) findViewById(R.id.weightValue);
radioGroup = (RadioGroup) findViewById(R.id.radioPackageSize);
selectWeight = (TextView) findViewById(R.id.selectWeight);
addImage = (TextView) findViewById(R.id.addImage);
itemImage = (ImageView) findViewById(R.id.item_image);
itemDescriptionText = (TextInputLayout) findViewById(R.id.item_description_text_input_layout);
quantityText = (TextInputLayout) findViewById(R.id.item_quantity_text_input_layout);
valueOfItemText = (TextInputLayout) findViewById(R.id.item_value_text_input_layout);
itemDescription = (EditText) findViewById(R.id.item_description_edit_text);
quantity = (EditText) findViewById(R.id.item_quantity_edit_text);
valueOfItem = (EditText) findViewById(R.id.item_value_edit_text);
}
public void onClick() {
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDialogFragment.createBuilder(getApplicationContext(), getSupportFragmentManager()).setTitle("Choose item image").setMessage(R.string.selectImage).setNegativeButtonText("Gallery").setPositiveButtonText("Camera").show();
}
});
}
public Boolean validationCheck() {
if (itemDescription.getText().length() == 0) {
itemDescriptionText.setErrorEnabled(true);
itemDescriptionText.setError("Please provide an item description");
} else if (quantity.getText().length() == 0) {
quantityText.setErrorEnabled(true);
quantityText.setError("Provide item quantity");
} else if (valueOfItem.getText().length() == 0) {
valueOfItemText.setErrorEnabled(true);
valueOfItemText.setError("Please provide value of item");
} else {
return true;
}
return false;
}
public void chooseImage() {
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_PICK_PICTURE);
imageChooserManager.setImageChooserListener(this);
try {
imageChooserManager.choose();
} catch (Exception e) {
e.printStackTrace();
}
}
public void snapImage() {
imageChooserManager = new ImageChooserManager(this, ChooserType.REQUEST_CAPTURE_PICTURE);
imageChooserManager.setImageChooserListener(this);
try {
imageChooserManager.choose();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onNegativeButtonClicked(int i) {
chooseImage();
}
#Override
public void onNeutralButtonClicked(int i) {
}
#Override
public void onPositiveButtonClicked(int i) {
snapImage();
}
#Override
public void onImageChosen(ChosenImage chosenImage) {
myBitmap = BitmapFactory.decodeFile(chosenImage.getFileThumbnail());
runOnUiThread(new Runnable() {
public void run() {
itemImage.setImageBitmap(myBitmap);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK &&
(requestCode == ChooserType.REQUEST_PICK_PICTURE ||
requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
imageChooserManager.submit(requestCode, data);
}
}
#Override
public void onError(String s) {
}
}
This is the error message I am getting :
Process: com.packr, PID: 11838
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.packr/com.packr.activities.MyShipmentsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2190)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2239)
at android.app.ActivityThread.access$800(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5047)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.packr.adapters.ShipmentsAdapter.setShipmentArrayList(ShipmentsAdapter.java:72)
at com.packr.activities.MyShipmentsActivity.onCreate(MyShipmentsActivity.java:66)
at android.app.Activity.performCreate(Activity.java:5249)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2239)
            at android.app.ActivityThread.access$800(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5047)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
            at dalvik.system.NativeStart.main(Native Method)
It was a silly mistake from my end.
1) I did not initialize the adapter in itemDetails activity
2) Secondly the data being passed in the intent was null.
Fixing the above things solved the issue.

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.

can't jump from one activity to the next

Hey everyone,
I cannot jump from my launch-activity to my second activity and i don't know why. this is the error i get:
02-22 11:43:04.858: ERROR/AndroidRuntime(18335): java.lang.RuntimeException: Unable to start activity ComponentInfo{android.Database/android.Database.projects}: android.database.sqlite.SQLiteException: no such column: _id: , while compiling: SELECT _id, Name, Comment, projects
this is my launch-activity:
package android.Database;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class projectsDatabase extends Activity {
/** Called when the activity is first created. */
SQLiteDatabase myDB = null;
final static String MY_DB_NAME ="projectsDatabase";
final static String MY_DB_TABLE = "projects";
static final int MENU_PROJECTS = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onCreateDBAndDBTabled();
setContentView(R.layout.main);
}
private void onCreateDBAndDBTabled(){
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE
+ " ( _id integer primary key autoincrement,"+
"Name varchar(100),"+
"Comment varchar(128),"+
"BookingDetails varchar(255),"+
"ProjectKind integer(3))"
+";");
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_PROJECTS, 0, R.string.menuProjects)
.setShortcut('1', 'f')
.setIcon(R.drawable.icon);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_PROJECTS:
Intent iProjects= new Intent(this, projects.class);
startActivity(iProjects);
return true;
}
return false;
}
}
and this is the actiity i want to start when the menu-button is clicked:
package android.Database;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
public class projects extends ListActivity {
SQLiteDatabase myDB = null;
static final int MENU_NEW_PROJECT = 0;
public void onCreate(Bundle icicle){
super.onCreate(icicle);
myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);
Cursor c = myDB.rawQuery("SELECT _id, ColumnName, ColumnComment, " + projectsDatabase.MY_DB_TABLE + ";", null);
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter (this,
android.R.layout.simple_list_item_1,
c,
new String[] {"_id"},
new int []{android.R.id.text1});
adapter.setViewBinder (new ViewBinder (){
#Override
public boolean setViewValue(View view, Cursor theCursor, int column){
String ColumnName = theCursor.getString(1);//Name
String ColumnComment = theCursor.getString(2);//Comment
((TextView)view).setText(ColumnName + "," + ColumnComment);
return true;
}
});
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long _id){
super.onListItemClick(l, v, position, _id);
Intent i = new Intent(this, projects_New.class);
i.putExtra("_id", _id);
this.startActivity(i);
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_NEW_PROJECT, 0, R.string.menuNewProject)
.setShortcut('1', 'n')
.setIcon(android.R.drawable.ic_menu_add);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case MENU_NEW_PROJECT:
Intent iProjects_New = new Intent (this, projects_New.class);
startActivity (iProjects_New);
return true;
}
return false;
}
}
I really hope you can help me out again ;)
--------------------------------------------Edit-------------------------------------------
now i can save data but can't select anything from my listview... here is the code for my projects_new.class :
package android.Database;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class projects_New extends Activity{
SQLiteDatabase myDB = null;
static final int MENU_INSERT_PROJECT = 0;
static final int MENU_UPDATE_PROJECT = 0;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_new);
Spinner s1 = (Spinner) findViewById(R.id.cb_ProjectKind);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this,
R.array.ProjectKind,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
if(getIntent().hasExtra("_id") == true){
long l = getIntent().getExtras().getLong("_id");
myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);
Cursor myCursor = myDB.rawQuery("SELECT _id, ColumnName, ColumnComment, ColumnBookingDetails, ColumnProjectKind FROM"
+ projectsDatabase.MY_DB_TABLE + "WHERE _id = " +l+ "", null);
startManagingCursor(myCursor);
int ColumnName = myCursor.getColumnIndex("ColumnName");
int ColumnComment = myCursor.getColumnIndex("ColumnComment");
int ColumnBookingDetails = myCursor.getColumnIndex("ColumnBookingDetails");
int ColumnProjectKind = myCursor.getColumnIndex("ColumnProjectKind");
myCursor.moveToFirst();
if (myCursor != null) {
if(myCursor.isFirst()){
EditText eName = (EditText)findViewById(R.id.ed_Name);
eName.setText(myCursor.getString(ColumnName));
EditText eComment = (EditText)findViewById(R.id.ed_Comment);
eComment.setText(myCursor.getString(ColumnComment));
EditText eBookingDetails = (EditText)findViewById(R.id.ed_BookingDetails);
eBookingDetails.setText (myCursor.getString(ColumnBookingDetails));
Spinner sProjectKind = (Spinner)findViewById(R.id.cb_ProjectKind);
sProjectKind.setSelection(myCursor.getInt(ColumnProjectKind), true);
}
}
}
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
if(getIntent().hasExtra("_id")== true)
{
menu.add(0,MENU_UPDATE_PROJECT, 0, R.string.menuUpdate)
.setShortcut('1', 's')
.setIcon(android.R.drawable.ic_menu_save);
}
else
{
menu.add(0, MENU_INSERT_PROJECT, 0, R.string.menuInsert)
.setShortcut('1', 's')
.setIcon(android.R.drawable.ic_menu_save);
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case MENU_INSERT_PROJECT:
EditText Name = (EditText)findViewById(R.id.ed_Name);
EditText Comment = (EditText)findViewById(R.id.ed_Comment);
EditText BookingDetails = (EditText)findViewById(R.id.ed_BookingDetails);
Spinner ProjectKind = (Spinner)findViewById(R.id.cb_ProjectKind);
int i = ProjectKind.getSelectedItemPosition();
if(Name.length()!= 0)
{
myDB = this.openOrCreateDatabase(projectsDatabase.MY_DB_NAME, MODE_PRIVATE, null);
if(getIntent().hasExtra("id")== true)//update
{
long l = getIntent().getExtras().getLong("_id");
myDB.execSQL("UPDATE "+ projectsDatabase.MY_DB_TABLE+" SET "+
"name = '"+Name.getText().toString()+"', "+
"Comment = '"+Comment.getText().toString()+"', "+
"BookingDetails ='"+BookingDetails.getText().toString()+"', "+
"ProjectKind ='"+i+"', "+
"WHERE _id = "+l+";");
}
else //insert
{
myDB.execSQL("INSERT INTO "+ projectsDatabase.MY_DB_TABLE +"(Name, Comment, BookingDetails, ProjectKind)"
+"VALUES ('"+Name.getText().toString()+"', "+
"'"+Comment.getText().toString()+"', "+
"'"+BookingDetails.getText().toString()+"', "+
"'"+i+"')");
}
finish();
return true;
}
else
{
Toast toast = Toast.makeText(this, "Please enter a name for this Project!" , Toast.LENGTH_SHORT);
toast.show();
}
}
return false;
}
}
Thank you so much for all your effort and help :)
In your Projects class you defined the following line
Cursor c = myDB.rawQuery("SELECT _id, ColumnName,
ColumnComment, " + projectsDatabase.MY_DB_TABLE + ";", null);
because it' says, there's no colunm _id in your table, so pls check that _id is a column in your table.
Pls ensure a clolun _id exists or not

Categories

Resources