The input does not show on the ListView - java

I followed this instruction http://www.vogella.com/tutorials/AndroidSQLite/article.html
Normally after I input a string(tag), it should be shown on the Listview, but instead I keep seeing the string that shows when there are no data in the database I created.
MainActivity.java
package ch.ethz.twimight.activities;
import android.app.ListActivity;
import android.os.Bundle;
import ch.ethz.twimight.R;
import ch.ethz.twimight.net.twitter.Tags;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MytagsActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int ACTIVITY_CREATE = 0;
private static final int DELETE_ID = Menu.FIRST + 1;
private SimpleCursorAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mytags);
this.getListView().setDividerHeight(2);
fillData();
registerForContextMenu(getListView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_tags, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Add:
createTodo();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Uri uri = Uri.parse(Tags.CONTENT_URI + "/"
+ info.id);
getContentResolver().delete(uri, null, null);
//fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createTodo() {
Intent i = new Intent(this, MyTagsActivity_D.class);
startActivity(i);
}
private void fillData() {
// Fields from the database (projection)
// Must include the _id column for the adapter to work
String[] from = new String[] { Tags.COL_TEXT };
// Fields on the UI to which we map
int[] to = new int[] { R.id.label };
//getLoaderManager().initLoader(0, null, this);
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.mytags_row, null, from,
to, 0);
setListAdapter(adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.delete_tag);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
String[] projection = { Tags.COL_ROW_ID, Tags.COL_TEXT};
CursorLoader cursorLoader = new CursorLoader(this,
Tags.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
// TODO Auto-generated method stub
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// TODO Auto-generated method stub
adapter.swapCursor(null);
}
}
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/no_tags" />
</LinearLayout>
layout_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="30dp"
android:layout_height="24dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:src="#drawable/ic_tag" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:lines="1"
android:text="#+id/TextView01"
android:textSize="24sp" >
</TextView>
</LinearLayout>
layout_edit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/addtag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/new_tag"
android:imeOptions="actionNext" >
</EditText>
</LinearLayout>
<Button
android:id="#+id/ilikeit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ilikeit" >
</Button>
</LinearLayout>
ContentProvider.java:
package ch.ethz.twimight.net.twitter;
import java.util.Arrays;
import java.util.HashSet;
import ch.ethz.twimight.data.DBOpenHelper;
import android.content.ContentProvider;
import android.content.ContentValues;
//import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
public class TagsContentProvider extends ContentProvider{
private static final String TAG = TagsContentProvider.class.getSimpleName();
private SQLiteDatabase database;
private DBOpenHelper dbHelper;
private static final UriMatcher tagsUriMatcher;
private static final int TAGS = 1;
private static final int TAGS_ID = 2;
static {
tagsUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
tagsUriMatcher.addURI(Tags.TAG_AUTHORITY, Tags.TAGS, TAGS);
tagsUriMatcher.addURI(Tags.TAG_AUTHORITY, Tags.TAGS + "/#", TAGS_ID);
#Override
public synchronized int delete(Uri uri, String arg1, String[] arg2) {
if (tagsUriMatcher.match(uri) != TAGS_ID)
throw new IllegalArgumentException("Unsupported URI: " + uri);
Log.d(TAG, "Delete TAGS_ID");
int nrRows = database.delete(DBOpenHelper.TABLE_TAGS, "_id=" + uri.getLastPathSegment(), null);
getContext().getContentResolver().notifyChange(Tags.CONTENT_URI, null);
return nrRows;
}
#Override
public String getType(Uri uri) {
switch (tagsUriMatcher.match(uri)) {
case TAGS:
return Tags.TAGS_CONTENT_TYPE;
case TAGS_ID:
return Tags.TAG_CONTENT_TYPE;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
private void checkColumns(String[] projection) {
String[] available = {DBOpenHelper.COL_ROW_ID };
if (projection != null) {
HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
// check if all columns which are requested are available
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}
}
#Override
public synchronized Uri insert(Uri uri, ContentValues values) {
//int uriType = tagsUriMatcher.match(uri);
// SQLiteDatabase sqlDB = database.getWritableDatabase();
//int rowsDeleted = 0;
long id = 0;
switch (tagsUriMatcher.match(uri)) {
case TAGS:
id = database.insert(DBOpenHelper.TABLE_TAGS, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(Tags.TAGS + "/" + id);
}
#Override
public boolean onCreate() {
dbHelper = DBOpenHelper.getInstance(getContext().getApplicationContext());
database = dbHelper.getWritableDatabase();
return true;
}
#Override
public synchronized Cursor query(Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) {
if (TextUtils.isEmpty(sortOrder))
sortOrder = Tags.DEFAULT_SORT_ORDER;
checkColumns(projection);
Cursor c = null;
String sql = null;
//Intent i = null;
switch (tagsUriMatcher.match(uri)) {
case TAGS:
Log.d(TAG, "Query TAGS");
c = database.query(DBOpenHelper.TABLE_TAGS, projection, where, whereArgs, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), Tags.CONTENT_URI);
break;
case TAGS_ID:
Log.d(TAG, "Query TAGS_ID");
sql = "SELECT * " + "FROM " + DBOpenHelper.TABLE_TAGS + " " + "WHERE " + DBOpenHelper.TABLE_TAGS + "._id="
+ uri.getLastPathSegment() + ";";
c = database.rawQuery(sql, null);
c.setNotificationUri(getContext().getContentResolver(), uri);
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
return c;
}
#Override
public synchronized int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int nrRows = database.update(DBOpenHelper.TABLE_TAGS, values, "_id=" + uri.getLastPathSegment(), null);
switch (tagsUriMatcher.match(uri)){
case TAGS:
nrRows = database.update(DBOpenHelper.TABLE_TAGS,
values,
selection,
selectionArgs);
break;
case TAGS_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
nrRows = database.update(DBOpenHelper.TABLE_TAGS,
values,
DBOpenHelper.COL_ROW_ID + "=" + id,
null);
} else {
nrRows = database.update(DBOpenHelper.TABLE_TAGS,
values,
DBOpenHelper.COL_ROW_ID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return nrRows;
}
}
And here is the logcat I got after I input a string:
W/ResourceType(10480): Skipping entry 0x1060072 in package table 0 because it is not complex!
D/TextView(10480): Constructor - Got appearance for textColorPrimaryInverse
D/TextView(10480): Constructor -- Got mEditTextBackgroundColor
W/IInputConnectionWrapper(10480): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(10480): endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(10480): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(10480): endBatchEdit on inactive InputConnection
I must have missed something...I am stucked here for two days...
I checked other example codes but still couldn't figure out what I've missed.
Please help, thank you.

Related

Event not saved in Calendar

I want to save an event in the calendar directly, without openning the calendar app. I have found that in some devices the event is not saved in calendar, but I am not getting any error in the logcat. This is the code that I am using,
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues()
values.put(CalendarContract.Events.DTSTART, DateBuilder.getStartDayCalendar());
values.put(CalendarContract.Events.DTEND, DateBuilder.getEndDayCalendar());
values.put(CalendarContract.Events.TITLE, "Title");
values.put(CalendarContract.Events.DESCRIPTION, "description");
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
Does anyone know what is happening?
Thanks!
UPDATE
In same devices you need to set up the status,Events.STATUS, Events.STATUS_CONFIRMED, that was the problem
Find the solution :
Follow the steps it will create event directly :
Manifest.xml
Add permissions in Manifest
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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="testpreference.com.testcalendar.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calendars" />
<Spinner
android:id="#+id/calendarid_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/newevent_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Event"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Spinner calendarIdSpinner;
private Hashtable<String,String> calendarIdTable;
private Button newEventButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendarIdSpinner = (Spinner) findViewById(R.id.calendarid_spinner);
newEventButton = (Button) findViewById(R.id.newevent_button);
newEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CalendarHelper.haveCalendarReadWritePermissions(MainActivity.this))
{
addNewEvent();
}
else
{
CalendarHelper.requestCalendarReadWritePermission(MainActivity.this);
}
}
});
calendarIdSpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
if (CalendarHelper.haveCalendarReadWritePermissions(this))
{
//Load calendars
calendarIdTable = CalendarHelper.listCalendarId(this);
updateCalendarIdSpinner();
}
}
private void updateCalendarIdSpinner()
{
if (calendarIdTable==null)
{
return;
}
List<String> list = new ArrayList<String>();
Enumeration e = calendarIdTable.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
list.add(key);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
calendarIdSpinner.setAdapter(dataAdapter);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode==CalendarHelper.CALENDARHELPER_PERMISSION_REQUEST_CODE)
{
if (CalendarHelper.haveCalendarReadWritePermissions(this))
{
Toast.makeText(this, (String)"Have Calendar Read/Write Permission.",
Toast.LENGTH_LONG).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void addNewEvent()
{
if (calendarIdTable==null)
{
Toast.makeText(this, (String)"No calendars found. Please ensure at least one google account has been added.",
Toast.LENGTH_LONG).show();
//Load calendars
calendarIdTable = CalendarHelper.listCalendarId(this);
updateCalendarIdSpinner();
return;
}
final long oneHour = 1000 * 60 * 60;
final long tenMinutes = 1000 * 60 * 10;
long oneHourFromNow = (new Date()).getTime() + oneHour;
long tenMinutesFromNow = (new Date()).getTime() + tenMinutes;
String calendarString = calendarIdSpinner.getSelectedItem().toString();
int calendar_id = Integer.parseInt(calendarIdTable.get(calendarString));
CalendarHelper.MakeNewCalendarEntry(this, "Test", "Add event", "Somewhere",tenMinutesFromNow,tenMinutesFromNow+oneHour,false,true,calendar_id,3);
}
}
Create class for calendar selection
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
private static final String TAG = "OnItemSelectedListener";
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.v(TAG,"onNohingSelected() called.");
}
}
CalendarHelper.java
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.TimeZone;
public class CalendarHelper {
//Remember to initialize this activityObj first, by calling initActivityObj(this) from
//your activity
private static final String TAG = "CalendarHelper";
public static final int CALENDARHELPER_PERMISSION_REQUEST_CODE = 99;
public static void MakeNewCalendarEntry(Activity caller,String title,String description,String location,long startTime,long endTime, boolean allDay,boolean hasAlarm, int calendarId,int selectedReminderValue) {
ContentResolver cr = caller.getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startTime);
values.put(Events.DTEND, endTime);
values.put(Events.TITLE, title);
values.put(Events.DESCRIPTION, description);
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.STATUS, Events.STATUS_CONFIRMED);
if (allDay)
{
values.put(Events.ALL_DAY, true);
}
if (hasAlarm)
{
values.put(Events.HAS_ALARM, true);
}
//Get current timezone
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Log.i(TAG, "Timezone retrieved=>"+TimeZone.getDefault().getID());
Uri uri = cr.insert(Events.CONTENT_URI, values);
Log.i(TAG, "Uri returned=>"+uri.toString());
// get the event ID that is the last element in the Uri
long eventID = Long.parseLong(uri.getLastPathSegment());
if (hasAlarm)
{
ContentValues reminders = new ContentValues();
reminders.put(Reminders.EVENT_ID, eventID);
reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
reminders.put(Reminders.MINUTES, selectedReminderValue);
Uri uri2 = cr.insert(Reminders.CONTENT_URI, reminders);
}
}
public static void requestCalendarReadWritePermission(Activity caller)
{
List<String> permissionList = new ArrayList<String>();
if (ContextCompat.checkSelfPermission(caller,Manifest.permission.WRITE_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
{
permissionList.add(Manifest.permission.WRITE_CALENDAR);
}
if (ContextCompat.checkSelfPermission(caller,Manifest.permission.READ_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
{
permissionList.add(Manifest.permission.READ_CALENDAR);
}
if (permissionList.size()>0)
{
String [] permissionArray = new String[permissionList.size()];
for (int i=0;i<permissionList.size();i++)
{
permissionArray[i] = permissionList.get(i);
}
ActivityCompat.requestPermissions(caller,
permissionArray,
CALENDARHELPER_PERMISSION_REQUEST_CODE);
}
}
public static Hashtable listCalendarId(Context c) {
if (haveCalendarReadWritePermissions((Activity)c)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst())
{
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String,String> calendarIdTable = new Hashtable<>();
do
{
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName,calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
return null;
}
public static boolean haveCalendarReadWritePermissions(Activity caller)
{
int permissionCheck = ContextCompat.checkSelfPermission(caller,
Manifest.permission.READ_CALENDAR);
if (permissionCheck== PackageManager.PERMISSION_GRANTED)
{
permissionCheck = ContextCompat.checkSelfPermission(caller,
Manifest.permission.WRITE_CALENDAR);
if (permissionCheck== PackageManager.PERMISSION_GRANTED)
{
return true;
}
}
return false;
}
}

when use below code to store image in sqlite, I get only first image , the application not restore to me the other images by the id

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/

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