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.
Related
when I use this code to store image and restore it from SQLite . it insert only one image (the first one ) and when i restore the image by id it also restore the first image only .
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="24dp"
android:hint="enter name"
android:id="#+id/nametxt"
android:layout_marginTop="350dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="24dp"
android:hint="enter id"
android:id="#+id/idtxt"
android:layout_marginTop="420dp"
/>
<Button
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Image Sqlite"
android:id="#+id/button"
android:layout_below="#+id/imageView"
android:layout_marginTop="75dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Image From Sqlite"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_marginTop="42dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageView
android:background="#color/colorPrimaryDark"
android:layout_width="120dp"
android:layout_height="120dp"
android:id="#+id/imageView2"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:background="#color/colorAccent"
android:layout_width="120dp"
android:layout_height="120dp"
android:id="#+id/imageView"
android:scaleType="fitCenter"
android:maxHeight="120dp"
android:maxWidth="120dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
MainActivity.java
package com.example.mahmoudbelal.navigator;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
static EditText name,id;
static ImageView Img,Img2;
Button Save,Get;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id= (EditText) findViewById(R.id.idtxt);
Img = (ImageView) findViewById(R.id.imageView);
Img2 = (ImageView) findViewById(R.id.imageView2);
Save = (Button) findViewById(R.id.button);
Get = (Button) findViewById(R.id.button2);
name= (EditText) findViewById(R.id.nametxt);
Img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Img.buildDrawingCache();
Bitmap bitmap=Img.getDrawingCache();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] img = bos.toByteArray();
DBAdapter D=new DBAdapter();
D.open(MainActivity.this);
String myname=name.getText().toString();
String myid=id.getText().toString();
D.insert_user_data(myid,myname,img);
Toast.makeText(MainActivity.this, "Inserted Data well !", Toast.LENGTH_SHORT).show();
name.setText(" ");
id.setText(" ");
}catch (Exception e){
Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
//------------------------------------------------------------------------------------//\
Get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBAdapter D=new DBAdapter();
D.open(MainActivity.this);
String use_id=id.getText().toString();
D.Get_user_data(use_id);
if (DBAdapter.ok.equals("1")){
// Img2.setImageBitmap(DBAdapter.bmp);
// Toast.makeText(MainActivity.this, "name is = "+DBAdapter.s, Toast.LENGTH_SHORT).show();
name.setText(""+DBAdapter.s);
}else
{
Toast.makeText(MainActivity.this, "Error y m3lm ", Toast.LENGTH_SHORT).show();
} }
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == this.RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
//-0-------------------------------------------------------------------------------------------------------------
Uri photoUri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA};
Cursor actualimagecursor = managedQuery(photoUri, proj, null, null, null);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
//--------------------------------------------------------------------------------------------
cursor.close();
Img.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
Toast.makeText(MainActivity.this, "Image Uploaded", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "You haven't picked Image", Toast.LENGTH_LONG).show();
}}
}
DBAdapter.java
package com.example.mahmoudbelal.navigator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class DBAdapter {
// first step:create table
static Bitmap bmp;
static String s="";
private int version=1;
private String DatabaseName="DNAA";
private String TableName="user";
static String ok;
// -------------------------------------------------- //
private String create_table = "CREATE TABLE IF NOT EXISTS user(id varchar,name varchar,img blob);";
// second step:helper class
class DbHellper extends SQLiteOpenHelper{
public DbHellper(Context context){
super(context , DatabaseName , null , 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 "+TableName);
onCreate(db);
}
}
private DbHellper DB_helper;
private SQLiteDatabase db;
public DBAdapter open(Context conn){
DB_helper = new DbHellper(conn);
db = DB_helper.getWritableDatabase();
return this;
// activity
}
private void close (){
db.close();
}
int i = 0;
public void insert_user_data (String id, String name, byte[] ii){
ContentValues cv = new ContentValues();
cv.put("id" , id);
cv.put("name" , name);
cv.put("img" , ii);
db.insert(TableName, null, cv);
}
public void updateSection(String username , String password , int rowId){
ContentValues cv = new ContentValues();
cv.put("username" , username);
cv.put("password" , password);
db.update(TableName, cv, "_id =" + rowId, null);
}
// Login method
public void Get_user_data (String id){
Cursor c = db.rawQuery("SELECT name,img FROM user where id='"+id+"'", null);
if (c.moveToFirst()) {
s= c.getString(0);
byte[] i=c.getBlob(1);
bmp= BitmapFactory.decodeByteArray(i,0,i.length);
MainActivity.Img2.setImageBitmap(bmp);
ok="1";
} else {
ok="0";
}
}
// delete data
public void deleteSection(int rowId){
db.delete(TableName, "_id =" + rowId, null);
}
public Cursor getAllSections (){
return db.query(TableName,new String []{"username","password"},null,null,null,null,null);
}
public Cursor getSection (String whereClause){
return db.query(TableName,new String []{"_id","name","devices"},whereClause,null,null,null,null);
}
}
this may help you
String[] columns =
{MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,null,null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
System.out.println("==here you will get all the images path ;=> "+imageUrls.get(i));
}
for your reference check this :
http://www.technotalkative.com/android-select-multiple-photos-from-gallery/
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>
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();
}
I am currently using Java Eclipse to make an android app. This app has an SQLite database that contains data. I can view this data in a list. And i can also add items to this database fine. I am now tring to delete a specific row from the database. But whenever i try to it deletes all the rows as oppose to the one the user has selected.
Here is my adapter:
package com.example.beer_budget3;
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;
import android.widget.EditText;
public class DatabaseSetup2
{
// These are the names of the columns the table will contain
public static final String KEY_ROWID = "_id";
public static final String KEY_PUBNAME = "Pub_Name";
public static final String KEY_LOCATION = "Location";
public static final String KEY_PRICE = "Price";
private static final String DATABASE_NAME = "CillinsAssignment";
private static final String DATABASE_TABLE = "Beer_Budget";
private static final int DATABASE_VERSION = 1;
// This is the string containing the SQL database create statement
private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE +
"( " +KEY_ROWID + " integer primary key autoincrement, "+KEY_PUBNAME +" text not null, "+KEY_LOCATION+" text not null, "+KEY_PRICE+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;// utility class that makes it easy to create and maintain an SQLLite database
private SQLiteDatabase db;//Class containing methods to manage a local SQLLite Database file
// constructor for your class
public DatabaseSetup2(Context ctx)
{
// Context is a way that Android transfers info about Activities and apps.
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
// This is the helper class that will create the dB if it doesn’t exist and
//upgrades it if the structure has changed. It needs a constructor, an
//onCreate() method and an onUpgrade() method
private static class DatabaseHelper extends SQLiteOpenHelper
{
// constructor for your dB helper class. This code is standard. You’ve set
//up the parameter values for the constructor already…database name,etc
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// The “Database_create” string below needs to contain the SQL
//statement needed to create the dB
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// If you want to change the structure of your database, e.g.
// Add a new column to a table, the code will go head..
//This method only triggers if the database version number has
//increased
Log.w("test", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Beer_Budget");
onCreate(db);
}
}// end of the help class
// from here on, include whatever methods will be used to access or change data
//in the database
//---opens the database--- any activity that uses the dB will need to do this
public DatabaseSetup2 open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- any activity that uses the dB will need to do this
public void close()
{
DBHelper.close();
}
//---insert a pub into the database---
public long insertPub(String Pub_Name, String Location, String Price)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PUBNAME, Pub_Name);
initialValues.put(KEY_LOCATION, Location);
initialValues.put(KEY_PRICE, Price);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
//---retrieves all the rows---
public Cursor getAllPubs()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE},
null,
null,
null,
null,
null);
}
//---retrieves a particular row---
public Cursor getPub(int _id) throws SQLException
{
Cursor mCursor = db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE
},
KEY_ROWID + "=" + _id,
null,
null,
null,
null
);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
Here is my deleting page:
package com.example.beer_budget3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
//Need to update delete layout after deleting row
public class Delete extends Activity
{
//Creating an object name for my database
DatabaseSetup2 db = new DatabaseSetup2(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the delete XML file
setContentView(R.layout.delete);//Put one of these in each class
//Delete button that has been created in the delete XML file
Button delete = (Button)findViewById(R.id.deletepub);
delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//This page links back to the MainMenu page
Intent i = new Intent(Delete.this, MainMenu.class);
//Calling the deleting function
deleting(v);
//Activating the intent
startActivity(i);
}
});
}
public void deleting(View v)
{
//Save user input into rowId
EditText pnametxt = (EditText)findViewById(R.id.delete1);
//Open the database
db.open();
String pname2 = pnametxt.getText().toString();
db.deletePub(pname2);
db.close();
}
}
And here is my XML file for the deleting page:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/background"
tools:context="com.example.beer_budget3.delete" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginBottom="20dp"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details"
android:layout_marginLeft="50dp"
android:layout_marginBottom="30dp"
android:textSize="25sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub"
android:textSize="20sp"/>
<EditText
android:id="#+id/delete1"
android:inputType="text"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/deletepub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="130dp"
android:onClick="delete"
android:text="#string/delete" />
</LinearLayout>
I personally think the error is in this line in the adapter:
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
Because i understand you have to be very specific with where you places your spaces and quotations. But i have changed this line of code around a few times and couldn't fix my problem.
Any advice would be much appreciated!
Your function here :
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ KEY_PUBNAME+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
should be
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "Pub_Name = '"+ Pub_Name+"' ", null) > 0;
//return db.delete(DB_TABLE, "name='"+ name+"'", null) > 0;
}
You specify the column name instead of the value
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.