Android: Retrieving Data and Display in ListView - java

I am very new to Android development and a bit rusty on my Java so please bear with me. I am trying to accomplish the following:
Upon launching the app all the users courses and info will populate in the main activity and a button option to add a new course will be present. Initially no courses will show until they are added.
Clicking add course will present a new activity and upon saving data entry a new course record will be inserted into the DB. Control will move back to the Main Activity where the listview will refresh with the newly added course. Below are the 4 classes and two layouts I'm working with.
PROBLEM: At this point I'm unsuccessful at confirming that data was inserted and pulling that data back out and displaying it on screen. I think I've identified the issue being that the course_list is not being populated with courses, but since I"m not getting any errors I'm struggling to identify the real problem. Any insight or guidance would be greatly appreciated!
MainActivity.Java
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
private ListView courseListView;
private ArrayList<Course> course_list = new ArrayList<Course>();
private ArrayList<String> course_names = new ArrayList<String>();
private ArrayAdapter<String> ap;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
courseListView = (ListView) findViewById(R.id.course_list);
// Init database
db = new DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
initAdapter();
}
#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_main, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Called when Add Course button is pressed
public void onClick( View v ) {
Intent intent = new Intent(v.getContext(), AddCourseActivity.class);
v.getContext().startActivity(intent);
}
//
private void initAdapter() {
if( course_list.size() != 0) {
course_list.clear();
course_list = db.getCourses();
for (int i = 0; i < course_list.size(); ++i) {
course_names.add(course_list.get(i).getCourseName());
}
ap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, course_names);
courseListView.setAdapter(ap);
}
}
}
DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "Courses";
public static final String COURSE_TABLE = "MyCourses";
public static final String KEY_COURSE_NUM = "CourseNum";
public static final String KEY_COURSE_NAME = "CourseName";
public static final String KEY_COURSE_DESC = "CourseDesc";
public static final String KEY_DATE = "Date";
public static final String KEY_TIME = "Time";
public static final String KEY_INSTRUCTOR = "Instructor";
private ArrayList<Course> courseList = new ArrayList<Course>();
// Constructor, Create DB
public DatabaseHelper( Context context ) {
super(context, DATABASE_NAME, null, 1) ;
}
// Create the MyCourses table
public void onCreate( SQLiteDatabase db ) {
db.execSQL("CREATE TABLE " + COURSE_TABLE + " (_id INTEGER PRIMARY KEY, "
+ KEY_COURSE_NUM + " TEXT, "
+ KEY_COURSE_NAME + " TEXT, "
+ KEY_COURSE_DESC + " TEXT, "
+ KEY_DATE + " TEXT, "
+ KEY_TIME + " TEXT, "
+ KEY_INSTRUCTOR + " TEXT)");
}
// Upgrade the MyCourses table
public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) {
// Drop older table if it exists
db.execSQL("DROP TABLE IF EXISTS " + COURSE_TABLE);
// Create table again
onCreate(db);
}
// Add a new course
public void addCourse( Course course ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_COURSE_NUM, course.getCourseNum());
contentValues.put(KEY_COURSE_NAME, course.getCourseName());
contentValues.put(KEY_COURSE_DESC, course.getCourseDesc());
contentValues.put(KEY_DATE, course.getCourseDate());
contentValues.put(KEY_TIME, course.getCourseTime());
contentValues.put(KEY_INSTRUCTOR, course.getCourseInstructor());
db.insert(COURSE_TABLE, null, contentValues);
db.close();
}
// Get all courses, assign to array of course objects an return array
public ArrayList<Course> getCourses() {
courseList.clear();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + COURSE_TABLE, null);
// Loop through cursor, extract data and assign to item Course object
if( cursor.getCount()!=0) {
if( cursor.moveToFirst() ) {
do {
Course item = new Course();
item.setCourseNum(cursor.getString(cursor.getColumnIndex(KEY_COURSE_NUM)));
item.setCourseName(cursor.getString(cursor.getColumnIndex(KEY_COURSE_NAME)));
item.setCourseDesc(cursor.getString(cursor.getColumnIndex(KEY_COURSE_DESC)));
item.setCourseDate(cursor.getString(cursor.getColumnIndex(KEY_DATE)));
item.setCourseTime(cursor.getString(cursor.getColumnIndex(KEY_TIME)));
item.setCourseInstructor(cursor.getString(cursor.getColumnIndex(KEY_INSTRUCTOR)));
// Add the object to the courseList array of Courses
courseList.add(item);
} while( cursor.moveToNext());
}
}
cursor.close();
db.close();
return courseList;
}
}
Course.java
public class Course {
private String courseNum;
private String courseName;
private String courseDesc;
private String date;
private String time;
private String instructor;
// Empty constructor
public Course() {
}
// Constructor for new course
public Course(Course course) {
this.courseNum = course.courseNum;
this.courseName = course.courseName;
this.courseDesc = course.courseDesc;
this.date = course.date;
this.time = course.time;
this.instructor = course.instructor;
}
// Get courseNum
public String getCourseNum() {
return courseNum;
}
// Set courseNum
public void setCourseNum( String courseNum ) {
this.courseNum = courseNum;
}
// Get courseName
public String getCourseName() {
return courseName;
}
// Set courseName
public void setCourseName( String courseName ) {
this.courseName = courseName;
}
// Get courseDesc
public String getCourseDesc() {
return courseDesc;
}
// Set courseDesc
public void setCourseDesc( String courseDesc ) {
this.courseDesc = courseDesc;
}
// Get date
public String getCourseDate() {
return date;
}
// Set date
public void setCourseDate( String date ) {
this.date = date;
}
// Get time
public String getCourseTime() {
return time;
}
// Set time
public void setCourseTime( String time ) {
this.time = time;
}
// Get instructor
public String getCourseInstructor() {
return instructor;
}
// Set instructor
public void setCourseInstructor( String instructor ) {
this.instructor = instructor;
}
}
AddCourseActivity.java
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class AddCourseActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_course);
}
#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_add_course, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Called when Save button is pressed
public void saveCourse(View v) {
Course c = new Course();
DatabaseHelper db = new DatabaseHelper(this);
EditText num = (EditText) findViewById(R.id.courseNum);
c.setCourseNum(num.getText().toString());
EditText name = (EditText) findViewById(R.id.courseName);
c.setCourseName(name.getText().toString());
EditText desc = (EditText) findViewById(R.id.courseDesc);
c.setCourseDesc(desc.getText().toString());
EditText date = (EditText) findViewById(R.id.courseDate);
c.setCourseDate(date.getText().toString());
EditText time = (EditText) findViewById(R.id.courseTime);
c.setCourseTime(time.getText().toString());
EditText inst = (EditText) findViewById(R.id.courseInstructor);
c.setCourseInstructor(inst.getText().toString());
db.addCourse(c);
// Return to Main Activity
Intent intent = new Intent(v.getContext(), MainActivity.class);
v.getContext().startActivity(intent);
}
// Called when Cancel button is pressed
public void cancel(View v) {
// Return to Main Activity
Intent intent = new Intent(v.getContext(), MainActivity.class);
v.getContext().startActivity(intent);
}
}
Activity_Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="My Courses"
android:textColor="#FFFFFF"
android:textSize="30dp"
android:background="#000000"/>
<Button
android:id="#+id/addCourse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add Course"
android:onClick="onClick"/>
<ListView
android:id="#+id/course_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
Activity_Add_Course.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Add New Course"
android:textColor="#FFFFFF"
android:textSize="30dp"
android:background="#000000"/>
<EditText
android:id="#+id/courseNum"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course #"/>
<EditText
android:id="#+id/courseName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course Name"/>
<EditText
android:id="#+id/courseDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="6"
android:hint="Course Description"/>
<EditText
android:id="#+id/courseDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course Date"/>
<EditText
android:id="#+id/courseTime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course Time"/>
<EditText
android:id="#+id/courseInstructor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Course Instructor"/>
<Button
android:id="#+id/saveCourse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="saveCourse"/>
<Button
android:id="#+id/cancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"
android:onClick="cancel"/>
</LinearLayout>

Related

Beginner level SQLite Android App no print result

this app Able to run however it cannot print the data from the database,
i also dont know if the data is able to insert or not.
This is MainActivity.java
package com.zikri.sqlitetuto3;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText dataET;
Button addB, delB;
TextView dataTV;
MyDBHandler dbHandler;
String getProduct;
Products products;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAndroidApp();
}
public void startAndroidApp(){
dbHandler = new MyDBHandler(this,null,null,1);
dataET = (EditText) findViewById(R.id.dataET);
addB = (Button) findViewById(R.id.addB);
delB = (Button) findViewById(R.id.delB);
dataTV = (TextView) findViewById(R.id.dataTV);
getProduct = dataET.getText().toString();
PrintProduct();
addB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddProduct(getProduct);
}
});
delB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DelProduct(getProduct);
}
});
}
public void PrintProduct(){
dataTV.setText(dbHandler.PrintProduct());
dataET.setText("");
}
public void AddProduct(String p){
products = new Products(p);
dbHandler.AddProduct(products);
PrintProduct();
}
public void DelProduct(String p){
dbHandler.DelProduct(p);
PrintProduct();
}
}
This is MyDBHandler.java
package com.zikri.sqlitetuto3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "products.db";
private static final String PRODUCT_TABLE = "product";
private static final String COL_ID = "id";
private static final String COL_PRODUCTNAME = "product_name";
public MyDBHandler(Context context,
String name,SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE "+PRODUCT_TABLE+" ("+
COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
COL_PRODUCTNAME+" TEXT"+");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
String query = "DROP IF EXIST "+PRODUCT_TABLE;
db.execSQL(query);
onCreate(db);
}
public void AddProduct(Products products){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_PRODUCTNAME,products.get_productname());
db.insert(PRODUCT_TABLE,null,values);
db.close();
}
public void DelProduct(String product){
SQLiteDatabase db = getWritableDatabase();
String query = "DELETE FROM "+PRODUCT_TABLE+
"WHERE "+COL_PRODUCTNAME+" = "+product+";";
db.execSQL(query);
db.close();
}
public String PrintProduct(){
SQLiteDatabase db = getWritableDatabase();
String printproductstring = "";
String query = "SELECT * FROM "+PRODUCT_TABLE+";";
Cursor cur = db.rawQuery(query,null);
cur.moveToFirst();
while(cur.moveToNext()){
printproductstring =
printproductstring+cur.getString(cur.getColumnIndex("product_name"));
printproductstring = printproductstring + "\n";
}
db.close();
return printproductstring;
}
}
This is Product.java
package com.zikri.sqlitetuto3;
public class Products {
private int _ID;
private String _productname;
public Products() {}
public Products(String productname) {
this._productname = productname;
}
public void set_ID(int _ID) {
this._ID = _ID;
}
public int get_ID() {
return _ID;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public String get_productname() {
return _productname;
}
}
this is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.zikri.sqlitetuto3.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/dataET" />
<Button
android:text="INSERT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/dataET"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/addB" />
<Button
android:text="Delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/addB"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/delB" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/dataTV" />
it it very difficult to see database in android is stoered or not you can see eror on logcate if no error means it is stored but not every time .if you want still you have to see in devide manager its difficult onother solution tack one rooted mobile and intrall root brouser go to android folder inside android folder go to dada inside again go to data and then your package name then database then see there is any file which name related to your database copy this into pc and download sqllite brouser . this long process you can do you will get 100% chance to get database file.if it is created
You should take input when the button is clicked otherwise getProduct will always be empty
addB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProduct = dataET.getText().toString();
// ^^^ fetch value when button is clicked
AddProduct(getProduct);
}
});
and do the same while deletion
delB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProduct = dataET.getText().toString();
// ^^^ fetch value when button is clicked
DelProduct(getProduct);
}
});
Furthermore you can confirm the successful insertion of data by the return value of insert which is long type and defined as
the row ID of the newly inserted row, or -1 if an error occurred
so use it
long id = db.insert(PRODUCT_TABLE,null,values);
// you can now check the value of id through Logs or Toast
db.close();

Image not inserting in sqlite database android

Anyone Please Help me. I am trying to create a dictionary application in which i want to save words ,their meanings and picture with every word. I am trying to save all the words,images and meanings in sqlite database. The problem is that when i click on any word in the listview it shows me the word and definition but the image field is blank.Here is my class in which i am creating my database.
public class DictionaryDataBase extends SQLiteOpenHelper {
byte[][] img = {
DbBitmapUtility.getBytes(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)),
DbBitmapUtility.getBytes(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)),
DbBitmapUtility
.getBytes(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)) };
public DictionaryDataBase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE Dict_Table (id INTEGER PRIMARY KEY, word TEXT NOT NULL, definition TEXT NOT NULL, image BLOB NOT NULL);");
try {
new DictionaryDB(context).addEntry(words, def, db, img);
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
and this is the add entry method:
public void addEntry(String[] word, String[] def, SQLiteDatabase db, byte[][] img) throws SQLiteException {
for (int i = 0; i < word.length; i++) {
db.execSQL("INSERT INTO Dict_Table VALUES (" + i + 1 + ", '" + word[i] + "', '" + def[i] + "', '" + img[i]
+ "');");
}
and this is the method which i am using to get the image:
public byte[] Getimage() throws SQLException {
dbhelper = new DictionaryDataBase(context);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * FROM Dict_Table WHERE word='" + MainActivity.item + "'", null);//MainActivity.item is the item which was clicked in the list view
res.moveToFirst();
byte[] img = res.getBlob(res.getColumnIndex(IMG_COL));
if (!res.isClosed()) {
res.close();
}
return img;
}
DbBitmapUtility.java:
public class DbBitmapUtility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
activity_meaning.xml(This is the layout file for my words definition and image):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.shehryar.dictionary.Meaning"
android:background="#2196F3" >
<TextView
android:id="#+id/tvword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Word"
android:textStyle="bold"
android:textSize="20dip"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/tvdefinition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvword"
android:layout_below="#+id/tvword"
android:layout_marginTop="14dp"
android:text="Definition"
android:textColor="#android:color/white"/>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvdefinition"
android:layout_below="#+id/tvdefinition"
android:layout_marginTop="30dp"
android:src="#drawable/abc_btn_radio_material" />
<TextView
android:id="#+id/tvcheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView1"
android:layout_below="#+id/imageView1"
android:layout_marginTop="40dp"
android:text="TextView" />
This is the onitemclick method of my listview which shows the list of words.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
try {
item =(String) parent.getItemAtPosition(position);
String def = db.GetDefinition();
img=db.Getimage();
Bundle basket = new Bundle();
basket.putString("word", item);
basket.putString("def", def);
basket.putByteArray("img", img);
Intent a= new Intent(this,Meaning.class);
a.putExtras(basket);
startActivity(a);
//Toast.makeText(this, def, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
and this is the meaning activity in which the result is showed:
Meaning.java:
package com.shehryar.dictionary;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
public class Meaning extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meaning);
String word,def;
byte[] img;
Bundle extras=getIntent().getExtras();
word=extras.getString("word");
def=extras.getString("def");
img=extras.getByteArray("img");
Bitmap image=DbBitmapUtility.getImage(img);
TextView tvword=(TextView) findViewById(R.id.tvword);
TextView tvdef=(TextView) findViewById(R.id.tvdefinition);
TextView tvcheck= (TextView) findViewById(R.id.tvcheck);
ImageView iv= (ImageView) findViewById(R.id.imageView1);
tvword.setText(word);
tvdef.setText(def);
iv.setImageBitmap(image);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.meaning, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you need any other information I will provide it to you but please help me in this case. Its since 2-3 days, I have been stuck here.
Ideally you should not be doing it in SQLite. SQLite is a light DB with merely 250KB of size. When it comes to dictionary, SQLite wont be able to fulfil your desired request.
Try saving it on Server or Internal memory and save URL or path respectively in DB.

showing the content of the table in database a list cannot be undone

I have just started to learn programming and I try to build a simple database for my exercise and I try to show all the content of the table in my database into a list in another layout but I don't know why the content isn't showing up in the list.. please help me ..
here is my apps sample
here is my activity for putting all the content in the list:
package com.DennisTA;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class DaftarIstilah extends Activity{
private DataKamus dbhelper;
private SQLiteDatabase db = null;
private ListView listContent = null;
private Cursor kamusCursor = null;
CustomCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbhelper = new DataKamus(this);
setContentView(R.layout.daftaristilah);
listContent = (ListView) findViewById(R.id.list1);
isDataListView();
}
private void isDataListView() {
try {
db = dbhelper.getWritableDatabase();
kamusCursor = db.query("kamus", new String[] { "_id", "inggris",
"arti", "penjelasan" }, "_id>0", null, null, null, null);
// startManagingCursor( jasaCursor);
/*
* Create an array to specify the fields we want to display in the
* list (only the 'inggris,arti,penjelasan' column in this case)
*/
String[] from = new String[] { "inggris", "arti", "penjelasan" };
/*
* and an array of the fields we want to bind those fieiplds to (in
* this case just the textView 'inggris,arti,penjelasan' from our new row.xml
* layout above)
*/
int[] to = new int[] { R.id.inggris, R.id.arti, R.id.penjelasan };
/* Now create a simple cursor adapter.. */
adapter = new CustomCursorAdapter(this, R.layout.baris, kamusCursor,
from, to);
// listView.setAdapter(adapter);
listContent.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
} catch (Exception e) {
}
}
protected class CustomCursorAdapter extends SimpleCursorAdapter {
private int layout;
private LayoutInflater inflater;
private Context context;
public CustomCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super (context, layout, c, from, to);
this.layout = layout;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Log.d("NewView", "*****xxx");
View v = inflater.inflate(R.layout.baris, parent, false);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
// 1 is the column where you're getting your data from
String inggris = c.getString(1);
String penjelasan = c.getString(3);
String arti = c.getString(2);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.inggris);
TextView des_text = (TextView) v.findViewById(R.id.penjelasan);
TextView id_text = (TextView) v.findViewById(R.id.arti);
des_text.setText(penjelasan);
id_text.setText(arti);
if (name_text != null) {
name_text.setText(inggris);
}
}
}
}
here is my baris.xml sample :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:paddingBottom="5sp"
android:paddingTop="5sp" >
<TextView
android:id="#+id/inggris"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/arti"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/inggris" />
<TextView
android:id="#+id/penjelasan"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/arti" />
</RelativeLayout>
here is my daftar istilah.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text = "Inggris"
android:textSize="20sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:text = "Arti"
android:textSize="20sp" />
<TextView
android:id="#+id/textView3"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView2"
android:text = "Penjelasan"
android:textSize="20sp" />
<ListView android:id="#+id/list1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight = "1"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"/>
</RelativeLayout>
here is my class that contain the database:
package com.DennisTA;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataKamus extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbkamus";
public static final String INGGRIS= "inggris";
public static final String ARTI = "arti";
public static final String PENJELASAN = "penjelasan";
//Constructor DataKamus untuk initiate database
public DataKamus(Context context) {
super(context, DATABASE_NAME, null, 1);
}
//method createTable untuk membuat table kamus
public void createTable(SQLiteDatabase db){
db.execSQL("DROP TABLE IF EXISTS kamus");
db.execSQL("CREATE TABLE if not exists kamus (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"inggris TEXT, arti TEXT, penjelasan TEXT);");
}
//method generateData untuk mengisikan data ke kamus.
public void generateData(SQLiteDatabase db){
ContentValues cv=new ContentValues();
cv.put(INGGRIS, "run");
cv.put(ARTI, "lari");
cv.put(PENJELASAN, "laufen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "walk");
cv.put(ARTI, "jalan");
cv.put(PENJELASAN, "gehen");
db.insert("kamus", INGGRIS, cv);
cv.put(INGGRIS, "read");
cv.put(ARTI, "membaca");
cv.put(PENJELASAN, "lesen");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
createTable(db);
generateData(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), "Oncreate", Toast.LENGTH_SHORT).show();
createTable(db);
generateData(db);
}
}
here is my main activity :
package com.DennisTA;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db = null;
private Cursor kamusCursor = null;
private EditText txtInggris;
private EditText txtArti;
private EditText txtPenjelasan;
private DataKamus datakamus = null;
public static final String INGGRIS = "inggris";
public static final String ARTI = "arti";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datakamus = new DataKamus(this);
db = datakamus.getWritableDatabase();
setContentView(R.layout.activity_main);
txtInggris = (EditText) findViewById(R.id.txtInggris);
txtArti = (EditText) findViewById(R.id.txtArti);
txtPenjelasan = (EditText) findViewById(R.id.txtPenjelasan);
}
public void getTerjemahan(View view) {
String bhsindonesia = "";
String bhsjerman="";
String englishword = txtInggris.getText().toString();
kamusCursor = db.rawQuery("SELECT _ID, INGGRIS, INDONESIA, JERMAN " + "FROM kamus where INGGRIS='" + englishword + "' ORDER BY INGGRIS", null);
if (kamusCursor.moveToFirst()) {
for (; !kamusCursor.isAfterLast();
kamusCursor.moveToNext()) {
bhsindonesia = kamusCursor.getString(2);
bhsjerman = kamusCursor.getString(3);
}
}else{
Toast.makeText(getBaseContext(), "Terjemahan Tidak ditemukan", Toast.LENGTH_SHORT).show();
}
txtArti.setText(bhsindonesia);
txtPenjelasan.setText(bhsjerman);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
kamusCursor.close();
db.close();
}catch (Exception e){
}
}
}
Retrieving from database as follows:
String selectQuery = "SELECT * FROM " + Variables.TABLE_ORDER
+ " WHERE " + Variables.TABLE_ORDER_CATEGORY ;
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Food_Id", cursor.getString(0));
cart_Array_List.add(map);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
}
Try extending a BaseAdapter and ovverride the following method:
#Override
public int getCount() {
return arraylist.size();
}

Android - Reading a text file and displaying all items or selected items (using query)

I would like to create a programm that reads a plain text file then either lists all the items in the text file or lists items depending on what the user types in and which button is pressed. I haven't been able to run it yet, as there are a number of errors. I have attempted to use the developer.android.com website, youTube and google to find solutions but the more I adjust the code the worse the problems seem to get. Below are the pieces of code I have come up with so far, including the text file, the manifest and fragment files.
info_sample.txt
Equipment Type Equipment ID Location Status Time
Infusion Pump 1234 2 On 12:00
Hoist 3645 1 Off 13:00
Bed 2563 3 Occupied 14:00
fragment_cemmain.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="clinical.equipment.monitor.CEMMainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/equiptype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/equiptype" />
<EditText
android:id="#+id/equiptypetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/equiptype"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/equipid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/equiptypetext"
android:layout_marginTop="28dp"
android:text="#string/equipid" />
<EditText
android:id="#+id/equipidtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/equipid"
android:ems="10" />
<Button
android:id="#+id/findequip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/equipidtext"
android:text="#string/findequip"
android:onClick="findequip" />
<Button
android:id="#+id/listallequip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/findequip"
android:layout_alignBottom="#+id/findequip"
android:layout_toRightOf="#+id/findequip"
android:text="#string/listallequip"
android:onClick="listallequip" />
<Button
android:id="#+id/refreshall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/linearLayout1"
android:layout_alignParentLeft="true"
android:layout_marginBottom="27dp"
android:onClick="refreshall"
android:text="#string/refresh" />
<Button
android:id="#+id/cleartext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/findequip"
android:layout_marginTop="56dp"
android:onClick="cleartext"
android:text="#string/cleartext" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
CEMMainActivity.java
package clinical.equipment.monitor;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.os.Build;
import android.provider.ContactsContract;
public class CEMMainActivity extends ActionBarActivity {
public class ListViewLoader extends ListActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
// This is the Adapter being used to display the list's data
SimpleCursorAdapter mAdapter;
// These are the Contacts rows that we will retrieve
static final String[] PROJECTION = new String[] {ContactsContract.Data._ID,
ContactsContract.Data.DISPLAY_NAME};
// This is the select criteria
static final String SELECTION = "((" +
ContactsContract.Data.DISPLAY_NAME + " NOTNULL) AND (" +
ContactsContract.Data.DISPLAY_NAME + " != '' ))";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cemmain);
if (savedInstanceState == null) {// action if app does not start up correctly
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
// Clears all text in EditText fields
Button clearalltext = (Button) findViewById(R.id.cleartext);
clearalltext.setOnClickListener(new OnClickListener() {
public void onClick(View c) {
ViewGroup group = (ViewGroup) findViewById(R.id.cleartext);
clearText(group);
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
clearText((ViewGroup)group);
}
}
});
//Action once Find button is clicked
Button findequip = (Button)findViewById(R.id.findequip);
findequip.setOnClickListener(new OnClickListener() {
public void onClick(View f) {
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Cursor c = db.getWordMatches(query, null);
//process Cursor and display results
}
}
}
}
});
// ignores the text fields and lists all equipment in virtual table
Button listalldatabase = (Button)findViewById(R.id.listallequip);
listalldatabase.setOnClickListener(new OnClickListener(){// may need correction
public void onClick(View l) {
//meant to call DatabaseOpenHelper class
}
} );
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cemmain, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_cemmain,
container, false);
return rootView;
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="clinical.equipment.monitor"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="clinical.equipment.monitor.CEMMainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
DatabaseOpenHelper.java
package clinical.equipment.monitor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class DatabaseOpenHelper {
private static final String TAG = "ListAllEquipment";
//The columns to be included in table
public static final String COL_TYPE = "EQUIPMENT TYPE";
public static final String COL_ID = "ID";
public static final String COL_LOCATION = "LOCATION";
public static final String COL_STATUS = "STATUS";
public static final String COL_TIME = "TIME";
private static final String DATABASE_NAME = "EQUIPMENT LIST";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final DatabaseOpenHelper mDatabaseOpenHelper;
public DatabaseOpenHelper(Context context) {
// TODO Auto-generated constructor stub
}
public void Listalldatabase (Context context) {
mDatabaseOpenHelper = new DatabaseOpenHelper(context);
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +
COL_TYPE + ", " +
COL_ID + ", " + COL_LOCATION + ", " + COL_STATUS +", " + COL_TIME + ")";
DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelperContext = context;
}
// populate the virtual table
private void loadEquipmentList() {
new Thread(new Runnable() {
public void run() {
try {
loadType();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadType() throws IOException {
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.info_sample);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 5) continue;
long list = addItem(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim(), strings[4].trim());
if (list < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
public long addItem (String type; String id; String location; String status; String time); {
ContentValues initialValues = new ContentValues();
initialValues.put(COL_TYPE, type);
initialValues.put(COL_ID, id);
initialValues.put(COL_LOCATION, location);
initialValues.put(COL_STATUS, status);
initialValues.put(COL_TIME, time);
return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
}
#Override
public void onCreate(SQLiteDatabase list) {
SQLiteDatabase mDatabase = list;
mDatabase.execSQL(FTS_TABLE_CREATE);
loadEquipmentList();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
}
}
SearchForEquip.java
package clinical.equipment.monitor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.text.*;
import android.util.Log;
public class SearchForEquip {
String equiptypetext,equipidtext, input1, input2;
private boolean readytofind() {
String input1 = equiptypetext.toString();
String input2 = equipidtext.toString();
if ((input1 != null) && (input2 != null))
{ return ((input1 != null) &&( input2 != null));
}
else if ((input1 == null) && (input2 != null))
{ return (input2 != null);
}
else if ((input1 != null) && (input2 == null)) {
return (input1 != null);
}
else { return false;}
}
public class DatabaseOpen {
private static final String TAG = "FindEquipment";
//The columns to be included in table
public static final String COL_TYPE = "EQUIPMENT TYPE";
public static final String COL_ID = "ID";
public static final String COL_LOCATION = "LOCATION";
public static final String COL_STATUS = "STATUS";
public static final String COL_TIME = "TIME";
private static final String DATABASE_NAME = "EQUIPMENT FOUND";
private static final String FTS_VIRTUAL_TABLE = "FTS";
private static final int DATABASE_VERSION = 1;
private final static DatabaseOpen mDatabaseOpen;
public DatabaseOpen(Context item) {
// TODO Auto-generated constructor stub
}
public void DatabaseTable(Context item) {
mDatabaseOpen = new DatabaseOpen(item);
}
private static class DatabaseOpenHelper extends SQLiteOpenHelper {
private final Context mContext;
private SQLiteDatabase mSearch;
private static final String FTS_TABLE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
" USING fts3 (" +
COL_TYPE + ", " +
COL_ID + ", " + COL_LOCATION + ", " + COL_STATUS +", " + COL_TIME + ")";
private static final Context mHelper = null;
DatabaseOpen(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mHelper = item;
}
//here the code should compare the typed text to the text in the text file and return a match
public Cursor getMatches(String query, String[] columns) {
String selection1 = COL_TYPE + " MATCH ?";
String selection2 = COL_ID + "MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection1, selection2, selectionArgs, columns);
}
private Cursor query(String selection, String[] selectionArgs, String[] columns) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
Cursor cursor = builder.query(mDatabaseOpen.getReadableDatabase(),
columns, selection, selectionArgs, null, null, null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
// populate the virtual table
private void loadSearchList() {
new Thread(new Runnable() {
public void run() {
try {
loadType();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadEquip() throws IOException {
final Resources equip = mHelper.getResources();
InputStream inputStream = equip.openRawResource(R.raw.info_sample);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 5) continue;
long list = addItem(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim(), strings[4].trim());
if (list < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally { reader.close();}
public long addItem (String type, String id, String location, String status, String time) {
ContentValues initialValues = new ContentValues();
initialValues.put(COL_TYPE, type);
initialValues.put(COL_ID, id);
initialValues.put(COL_LOCATION, location);
initialValues.put(COL_STATUS, status);
initialValues.put(COL_TIME, time);
return mSearch.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
}

Unfortunately <app-name> has stopped

I have written a code for an app that is supposed to be for a Virtual Campus tour. I have shared below the various files (3 class files) and 3 xml files and all have no errors in them.
The app has installed on the emulator successfully but throws up the error mentioned in the heading.
I am very new to android and to java so any help will be really appreciated!
Can anyone spot where I have gone wrong?
Code for one class by the name BuildingEdit
package com.example.udbuildingtour;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class BuildingEdit extends Activity {
private EditText mNameText;
private EditText mLatText;
private EditText mLongiText;
private Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.building_edit);
setTitle(R.string.edit_building);
mNameText = (EditText) findViewById(R.id.name);
mLatText = (EditText) findViewById(R.id.lat);
mLongiText = (EditText) findViewById(R.id.longi);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
String name = extras.getString(BuildingsDbAdapter.KEY_BUILDINGNAME);
String lat = extras.getString(BuildingsDbAdapter.KEY_LAT);
String longi = extras.getString(BuildingsDbAdapter.KEY_LONGI);
mRowId = extras.getLong(BuildingsDbAdapter.KEY_ID);
if (name != null) {
mNameText.setText(name);
}
if (lat != null) {
mLatText.setText(lat);
}
if (longi != null) {
mLongiText.setText(longi);
}
}
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString(BuildingsDbAdapter.KEY_BUILDINGNAME, mNameText.getText().toString());
bundle.putString(BuildingsDbAdapter.KEY_LAT, mLatText.getText().toString());
bundle.putString(BuildingsDbAdapter.KEY_LONGI, mLongiText.getText().toString());
if (mRowId != null) {
bundle.putLong(BuildingsDbAdapter.KEY_ID, mRowId);
}
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}
});
}
}
Code for class UDBuildingTour
package com.example.udbuildingtour;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
public class UDBuildingTour extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private BuildingsDbAdapter mDbHelper;
private Cursor mBuildingsCursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.building_edit);
mDbHelper = new BuildingsDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createBuilding();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteBuilding(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createBuilding() {
Intent i = new Intent(this, BuildingEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = mBuildingsCursor;
c.moveToPosition(position);
Intent i = new Intent(this, BuildingEdit.class);
i.putExtra(BuildingsDbAdapter.KEY_ID, id);
i.putExtra(BuildingsDbAdapter.KEY_BUILDINGNAME, c.getString(
c.getColumnIndexOrThrow(BuildingsDbAdapter.KEY_BUILDINGNAME)));
i.putExtra(BuildingsDbAdapter.KEY_LAT, c.getString(
c.getColumnIndexOrThrow(BuildingsDbAdapter.KEY_LAT)));
i.putExtra(BuildingsDbAdapter.KEY_LONGI, c.getString(
c.getColumnIndexOrThrow(BuildingsDbAdapter.KEY_LONGI)));
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
switch(requestCode) {
case ACTIVITY_CREATE:
Long rowId = extras.getLong(BuildingsDbAdapter.KEY_ID);
String name = extras.getString(BuildingsDbAdapter.KEY_BUILDINGNAME);
String lat = extras.getString(BuildingsDbAdapter.KEY_LAT);
String longi = extras.getString(BuildingsDbAdapter.KEY_LONGI);
mDbHelper.createBuilding(rowId, name, lat, longi);
fillData();
break;
case ACTIVITY_EDIT:
Long Id = extras.getLong(BuildingsDbAdapter.KEY_ID);
if (Id != null) {
String editName = extras.getString(BuildingsDbAdapter.KEY_BUILDINGNAME);
String editLat = extras.getString(BuildingsDbAdapter.KEY_LAT);
String editLongi = extras.getString(BuildingsDbAdapter.KEY_LONGI);
mDbHelper.updateBuilding(Id, editName, editLat, editLongi);
}
fillData();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.udbuilding_tour, menu);
return true;
}
private void fillData() {
// TODO Auto-generated method stub
// Get all of the rows from the database and create the item list
mBuildingsCursor = mDbHelper.fetchAllBuildings();
startManagingCursor(mBuildingsCursor);
// Create an array to specify the fields we want to display in the list (only BUILDINGNAME)
String[] from = new String[]{BuildingsDbAdapter.KEY_BUILDINGNAME};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter building =
new SimpleCursorAdapter(this, R.layout.buildings_row, mBuildingsCursor, from, to);
setListAdapter(building);
}
}
Code for BuildingsDBAdapter
package com.example.udbuildingtour;
import java.io.BufferedReader;
import java.io.FileReader;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class BuildingsDbAdapter {
public static final String KEY_ID = "_id";
public static final String KEY_BUILDINGNAME = "name";
public static final String KEY_LAT = "lat";
public static final String KEY_LONGI = "longi";
private static final String TAG = "BuildingsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table buildings (_id integer primary key autoincrement, "
+ "title text not null, body text not null);";
private static final String DATABASE_NAME = "Buildings";
private static final String DATABASE_TABLE = "UDBuildings";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* #param ctx the Context within which to work
*/
public BuildingsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public BuildingsDbAdapter open() throws SQLException {
// TODO Auto-generated method stub
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean deleteBuilding(long id) {
// TODO Auto-generated method stub
return mDb.delete(DATABASE_TABLE, KEY_ID + "=" + id, null) > 0;
}
public long createBuilding(Long id, String name, String lat, String longi) {
// TODO Auto-generated method stub
ContentValues initialValues = new ContentValues();
try{
BufferedReader in = new BufferedReader(new FileReader("UDBuildings.txt"));
String s;
while((s = in.readLine()) != null){
String[] var = s.split(":");
//var[0]=ID,var[1]=Name etc etc
initialValues.put(KEY_BUILDINGNAME, var[1]);
initialValues.put(KEY_LAT, var[2]);
initialValues.put(KEY_LONGI, var[3]);
initialValues.put(KEY_ID, var[0]);
}
}catch(Exception e){
e.printStackTrace();
}
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
/**
* Return a Cursor over the list of all buildings in the database
*
* #return Cursor over all buildings
*/
public Cursor fetchAllBuildings() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_BUILDINGNAME,
KEY_LAT, KEY_LONGI}, null, null, null, null, null);
}
/**
* Return a Cursor positioned at the building that matches the given building id
*
* #param id of building to retrieve
* #return Cursor positioned to matching building, if found
* #throws SQLException if building could not be found/retrieved
*/
public Cursor fetchBuilding(long id) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ID,
KEY_BUILDINGNAME, KEY_LAT, KEY_LONGI}, KEY_ID + "=" + id, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* Update the building using the details provided. The building to be updated is
* specified using the id, and it is altered to use the name and lat, longi
* values passed in
*
* #param id of building to update
* #param name value to set building name to
* #param lat value to set building lat to
* #param longi value to set building longi to
* #return true if the building was successfully updated, false otherwise
*/
public boolean updateBuilding(Long rowId, String editName, String editLat, String editLongi) {
// TODO Auto-generated method stub
ContentValues args = new ContentValues();
args.put(KEY_BUILDINGNAME, editName);
args.put(KEY_LAT, editLat);
args.put(KEY_LONGI, editLongi);
return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
}
}
xml code for building_edit
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name" />
<EditText android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lat" />
<EditText android:id="#+id/lat" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="longi" />
<EditText android:id="#+id/longi" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical" />
<Button android:id="#+id/confirm"
android:text="confirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
xml code for buildings_row
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="#+id/text1" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
xml code for buildings_list
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView android:id="#+id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="no_buildings"/>
</LinearLayout>
androidmanifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.udbuildingtour"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.udbuildingtour.UDBuildingTour"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BuildingEdit"></activity>
</application>
</manifest>
android:id="#android:id/list"
and not this...
android:id="#+id/android:list"
in your ListView
I see two problems:
The UDBuildingTour activity is not using buildings_list as the content view. As a result, there is no ListView and the base ListActivity will throw an exception when you call setListAdapter(building); in fill_data. In onCreate(), you should change this:
setContentView(R.layout.building_edit);
to:
setContentView(R.layout.building_list);
As #stir-fried points out, the android:id attribute for the ListView in buildings_list should be #android:id/list, not #+id/android:list (which I'm surprised compiles). For a custom list activity layout, you need to use the predefined Android id for the ListView, not autogenerating your own id. Similarly, the empty-list view should have android:id=#android:id/empty, not #+id/android:empty.

Categories

Resources