This is the code:
TodoTable.java:
public class TodoTable {
// Database table
public static final String TABLE_TODO = "todo";
public static final String COLUMN_ID_U = "_id";
public static final String COLUMN_CATEGORY = "category";
public static final String COLUMN_SUMMARY = "summary";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_SATZE = "satze";
// Database creation SQL statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_TODO
+ "("
+ COLUMN_ID_U + " integer primary key autoincrement, "
+ COLUMN_CATEGORY + " text not null, "
+ COLUMN_SUMMARY + " text not null, "
+ COLUMN_DESCRIPTION + " text not null, "
+ COLUMN_SATZE + " text not null"
+ ");";
public static void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
public static void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(TodoTable.class.getName(), "Upgrading database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
onCreate(database);
}}
TodoDetailAktivity.java:
public class TodoDetailActivity extends Activity {
private Spinner mCategory;
private EditText mTitleText;
private EditText mBodyText;
private EditText mSatzText;
private EditText mPauseText;
private EditText mWDHText;
private EditText mGewichtText;
private Uri todoUri;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.todo_edit);
mCategory = (Spinner) findViewById(R.id.category);
mTitleText = (EditText) findViewById(R.id.todo_edit_summary);
mBodyText = (EditText) findViewById(R.id.todo_edit_description);
mSatzText = (EditText) findViewById(R.id.editTextsatz);
Button confirmButton = (Button) findViewById(R.id.todo_edit_button);
Bundle extras = getIntent().getExtras();
// Check from the saved Instance
todoUri = (bundle == null) ? null : (Uri) bundle
.getParcelable(MyTodoContentProvider.CONTENT_ITEM_TYPE);
// Or passed from the other activity
if (extras != null) {
todoUri = extras
.getParcelable(MyTodoContentProvider.CONTENT_ITEM_TYPE);
fillData(todoUri);
}
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (TextUtils.isEmpty(mTitleText.getText().toString())) {
makeToast();
} else {
setResult(RESULT_OK);
finish();
}
}
});
}
private void fillData(Uri uri) {
String[] projection = { TodoTable.COLUMN_SUMMARY,
TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_CATEGORY };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
String category = cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_CATEGORY));
for (int i = 0; i < mCategory.getCount(); i++) {
String s = (String) mCategory.getItemAtPosition(i);
if (s.equalsIgnoreCase(category)) {
mCategory.setSelection(i);
}
}
mTitleText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_SUMMARY)));
mBodyText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_DESCRIPTION)));
mSatzText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_SATZE)));
// Always close the cursor
cursor.close();
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putParcelable(MyTodoContentProvider.CONTENT_ITEM_TYPE, todoUri);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
private void saveState() {
String category = (String) mCategory.getSelectedItem();
String summary = mTitleText.getText().toString();
String description = mBodyText.getText().toString();
String satze = mSatzText.getText().toString();
// Only save if either summary or description
// is available
if (description.length() == 0 && summary.length() == 0 && satze.length() == 0) {
return;
}
ContentValues values = new ContentValues();
values.put(TodoTable.COLUMN_CATEGORY, category);
values.put(TodoTable.COLUMN_SUMMARY, summary);
values.put(TodoTable.COLUMN_DESCRIPTION, description);
values.put(TodoTable.COLUMN_SATZE, satze);
if (todoUri == null) {
// New todo
todoUri = getContentResolver().insert(MyTodoContentProvider.CONTENT_URI, values);
} else {
// Update todo
getContentResolver().update(todoUri, values, null, null);
}
}
private void makeToast() {
Toast.makeText(TodoDetailActivity.this, "Please maintain a summary",
Toast.LENGTH_LONG).show();
}}
TodosOverviewAktivity.java:
/*
* TodosOverviewActivity displays the existing todo items
* in a list
*
* You can create new ones via the ActionBar entry "Insert"
* You can delete existing ones via a long press on the item
*/
#TargetApi(11)
public class TodosOverviewActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
private static final int DELETE_ID = Menu.FIRST + 1;
// private Cursor cursor;
private SimpleCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.todo_list);
this.getListView().setDividerHeight(1);
fillData();
registerForContextMenu(getListView());
}
// Create the menu based on the XML defintion
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listmenu, menu);
return true;
}
// Reaction to the menu selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.insert:
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(MyTodoContentProvider.CONTENT_URI + "/"
+ info.id);
getContentResolver().delete(uri, null, null);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createTodo() {
Intent i = new Intent(this, TodoDetailActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
// Opens the second activity if an entry is clicked
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, TodoDetailActivity.class);
Uri todoUri = Uri.parse(MyTodoContentProvider.CONTENT_URI + "/" + id);
i.putExtra(MyTodoContentProvider.CONTENT_ITEM_TYPE, todoUri);
// Activity returns an result if called with startActivityForResult
startActivityForResult(i, ACTIVITY_EDIT);
}
// Called with the result of the other activity
// requestCode was the origin request code send to the activity
// resultCode is the return code, 0 is everything is ok
// intend can be used to get data
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
private void fillData() {
// Fields from the database (projection)
// Must include the _id column for the adapter to work
String[] from = new String[] { TodoTable.COLUMN_SUMMARY };
// Fields on the UI to which we map
int[] to = new int[] { R.id.label };
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.todo_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.menu_delete);
}
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = { TodoTable.COLUMN_ID_U, TodoTable.COLUMN_SUMMARY };
CursorLoader cursorLoader = new CursorLoader(this,
MyTodoContentProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// data is not available anymore, delete reference
adapter.swapCursor(null);
}}
MyTodoContentProvider.java:
public class MyTodoContentProvider extends ContentProvider {
// database
private TodoDatabaseHelper database;
// Used for the UriMacher
private static final int TODOS = 10;
private static final int TODO_ID = 20;
private static final String AUTHORITY = "de.vogella.android.todos.contentprovider";
private static final String BASE_PATH = "todos";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/todos";
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/todo";
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(AUTHORITY, BASE_PATH, TODOS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", TODO_ID);
}
#Override
public boolean onCreate() {
database = new TodoDatabaseHelper(getContext());
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// Uisng SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// Check if the caller has requested a column which does not exists
checkColumns(projection);
// Set the table
queryBuilder.setTables(TodoTable.TABLE_TODO);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case TODOS:
break;
case TODO_ID:
// Adding the ID to the original query
queryBuilder.appendWhere(TodoTable.COLUMN_ID_U + "="
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = database.getWritableDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection,
selectionArgs, null, null, sortOrder);
// Make sure that potential listeners are getting notified
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = database.getWritableDatabase();
int rowsDeleted = 0;
long id = 0;
switch (uriType) {
case TODOS:
id = sqlDB.insert(TodoTable.TABLE_TODO, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH + "/" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = database.getWritableDatabase();
int rowsDeleted = 0;
switch (uriType) {
case TODOS:
rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO, selection,
selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO,
TodoTable.COLUMN_ID_U + "=" + id,
null);
} else {
rowsDeleted = sqlDB.delete(TodoTable.TABLE_TODO,
TodoTable.COLUMN_ID_U + "=" + id
+ " and " + selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = database.getWritableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case TODOS:
rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO,
values,
selection,
selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO,
values,
TodoTable.COLUMN_ID_U + "=" + id,
null);
} else {
rowsUpdated = sqlDB.update(TodoTable.TABLE_TODO,
values,
TodoTable.COLUMN_ID_U + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
private void checkColumns(String[] projection) {
String[] available = { TodoTable.COLUMN_CATEGORY,
TodoTable.COLUMN_SUMMARY, TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_SATZE, TodoTable.COLUMN_ID_U };
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");
}
}
}
}
TodoDatabaseHelper.java:
public class TodoDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "todotable.db";
private static final int DATABASE_VERSION = 1;
public TodoDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
TodoTable.onCreate(database);
}
// Method is called during an upgrade of the database,
// e.g. if you increase the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
TodoTable.onUpgrade(database, oldVersion, newVersion);
}
}
The most of code I have copied from: http://www.vogella.com/articles/AndroidSQLite/article.html#todo
But I get the errormessage (LogCat):
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.de.vogella.android.todos/com.example.de.vogella.android.todos.TodoDetailActivity}: java.lang.IllegalArgumentException: column 'satze' does not exist
Can anybody find a mistake in the code?
Thanks
Here is your bug:
private void fillData(Uri uri) {
String[] projection = { TodoTable.COLUMN_SUMMARY,
TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_CATEGORY }; //add satze here!
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
String category = cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_CATEGORY));
for (int i = 0; i < mCategory.getCount(); i++) {
String s = (String) mCategory.getItemAtPosition(i);
if (s.equalsIgnoreCase(category)) {
mCategory.setSelection(i);
}
}
mTitleText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_SUMMARY)));
mBodyText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_DESCRIPTION)));
mSatzText.setText(cursor.getString(cursor
.getColumnIndexOrThrow(TodoTable.COLUMN_SATZE)));//you don't have satze in projection!
// Always close the cursor
cursor.close();
}
}
You are trying to read TodoTable.COLUMN_SATZE but you forgot about it in projection:
Please change this line:
String[] projection = { TodoTable.COLUMN_SUMMARY,
TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_CATEGORY };
into this:
String[] projection = { TodoTable.COLUMN_SUMMARY,
TodoTable.COLUMN_DESCRIPTION, TodoTable.COLUMN_CATEGORY, TodoTable.COLUMN_SATZE };
In your CREATE TABLE statement you need spaces between your column names and column types.
Related
I created an app to set reminders. For that I use two fragments: one to show the list of reminders and another one to create and edit a specific reminder.
When I edit the reminder, I have issues showing the already saved data from the SQLite Database (saving seems to work fine). I managed to show the title of the reminder by sending it from the list of reminders using arguments. However, I think it would make more sense to directly access the database from the edit fragment. I already tried different methods, but I think I am not accessing the ReminderProvider class correctly. I tried to create a method getTitel in the ReminderProvider classe which is used to handle the database, but I would then need to create an instance of the class and this is where I get lost since I don't instantiate it correctly (I get an NPE).
I would also like to access the db to show the date and time that have been saved before (I haven't been able to solve that with the arguments yet).
I have the same issue with the notification: I get a notification at the indicated time, but the notification does not show the title of the reminder. I can then access the reminder into the edit fragment, but then also I don't see the already saved data - another reason why I would like to load it directly from the database.
I have searched a lot here but didn't not find the answer (or couldn't transfer it to my case). I am still a beginner so I would appreciate any help. Thanks! (And sorry if this is a really stupid question...)
My code for the classes ReminderEditFragment and ReminderProvider is below (I also have the following classes: ReminderListFragment to show all reminders, ReminderListActivity to handle the ListFragment, ReminderEditActivity, ReminderManager, OnAlarmReceiver, OnBootReceiver, ReminderService, als well as fragments for the date- and timepicker)
ReminderEditFragment:
public class ReminderEditFragment extends Fragment implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:mm";
private Calendar mCalendar;
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateButtons();
}
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hour);
mCalendar.set(Calendar.MINUTE, minute);
updateButtons();
}
private void updateButtons() {
//Text des TimeButtons setzen
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String timeForButton = null;
timeForButton = timeFormat.format(mCalendar.getTime());
mTimeButton.setText(timeForButton);
//Text des DateButtons setzen
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = null;
dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
public static final String DEFAULT_EDIT_FRAGMENT_TAG = "editFragmentTag";
private EditText mReminderTitle;
private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private Button mDeleteButton;
private long mRowID;
private TextView mTextOldDate;
private TextView mOldDate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
if (arguments != null) {
mRowID = arguments.getLong(ReminderProvider.COLUMN_ID);
}
if (savedInstanceState != null && savedInstanceState.containsKey(CALENDAR)) {
mCalendar = (Calendar) savedInstanceState.getSerializable(CALENDAR);
} else{
mCalendar = Calendar.getInstance();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.reminder_edit, container, false);
mReminderTitle = v.findViewById(R.id.editText_reminder);
mDateButton = v.findViewById(R.id.button_reminder_date);
mTimeButton = v.findViewById(R.id.button_reminder_time);
if (mRowID != 0) {
Bundle arguments = getArguments();
String reminderTitle = arguments.getString(ReminderProvider.COLUMN_TITLE);
//I have also tried different versions of the following, but here I get the NPE
//Cursor c = (Cursor) new ReminderProvider().getTitle(mRowID);
//String reminderTitle = new ReminderProvider().getTitle(mRowID);
mReminderTitle.setText(reminderTitle);
}
mConfirmButton = v.findViewById(R.id.button_confirm);
mDeleteButton = v.findViewById(R.id.button_delete);
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePicker();
}
});
mTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
showTimePicker();
}
});
mConfirmButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View view) {
ContentValues values = new ContentValues();
values.put(ReminderProvider.COLUMN_ID, mRowID);
values.put(ReminderProvider.COLUMN_TITLE, mReminderTitle.getText().toString());
values.put(ReminderProvider.COLUMN_DATE_TIME, mCalendar.getTimeInMillis());
if (mRowID == 0) {
Uri itemUri = getActivity().getContentResolver().insert(ReminderProvider.CONTENT_URI, values);
mRowID = ContentUris.parseId(itemUri);
} else {
int count = getActivity().getContentResolver().update(ContentUris.withAppendedId(ReminderProvider.CONTENT_URI, mRowID),
values, null, null);
if (count != 1)
throw new IllegalStateException(mRowID + " konnte nicht aktualisiert werden.");
}
Toast.makeText(getActivity(), getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
getActivity().finish();
new ReminderManager(getActivity()).setReminder(mRowID, mCalendar);
}
});
mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRowID != 0) {
getActivity().getContentResolver().delete(ContentUris.withAppendedId(ReminderProvider.CONTENT_URI, mRowID), null, null);
Toast.makeText(getActivity(), getString(R.string.task_deleted_message), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
});
return v;
}
//Dialogkonstanten
static final String YEAR = "year";
static final String MONTH = "month";
static final String DAY = "day";
static final String HOUR = "hour";
static final String MINS = "mins";
static final String CALENDAR = "calendar";
private void showDatePicker() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
DialogFragment newFragment = new DatePickerDialogFragment();
Bundle args = new Bundle();
args.putInt(YEAR, mCalendar.get(Calendar.YEAR));
args.putInt(MONTH, mCalendar.get(Calendar.MONTH));
args.putInt(DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
newFragment.setArguments(args);
newFragment.show(ft, "datePicker");
}
private void showTimePicker() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
DialogFragment newFragment = new TimePickerDialogFragment();
Bundle args = new Bundle();
args.putInt(HOUR, mCalendar.get(Calendar.HOUR_OF_DAY));
args.putInt(MINS, mCalendar.get(Calendar.MINUTE));
newFragment.setArguments(args);
newFragment.show(ft, "timePicker");
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Calendar-Instanz speichern, falls Aenderungen vorgenommen wurden
outState.putSerializable(CALENDAR, mCalendar);
}
}
ReminderProvider:
public class ReminderProvider extends ContentProvider {
//ContentProvider URI und Quelle
public static String AUTHORITY = "com.example.mareike.remindme2.ReminderProvider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/reminder");
//Fuer Begriffe oder Suche nach Definitionen verwendete MIME Typen
public static final String REMINDERS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.com.example.mareike.remindme2.reminder";
public static final String REMINDER_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.com.example.mareike.remindme2.reminder";
//Datenbank Konstanten
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "reminder";
//Datenbanken Spalten
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATE_TIME = "reminder_date_time";
public static final String COLUMN_TITLE = "title";
//SQL Anweisung zusammensetzen
private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE +
" (" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE +
" text not null, " + COLUMN_DATE_TIME + " integer not null);";
//UriMatcher-Zeug
private static final int LIST_REMINDER = 0;
private static final int ITEM_REMINDER = 1;
private static final UriMatcher sURIMatcher = buildUriMatcher();
private SQLiteDatabase mDb;
//Erstellt ein UriMatcher-Objekt fuer Suchvorschlaege und Kurzabfragen
private static UriMatcher buildUriMatcher() {
UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(AUTHORITY, "reminder", LIST_REMINDER);
matcher.addURI(AUTHORITY, "reminder/#", ITEM_REMINDER);
return matcher;
}
#Override
public boolean onCreate() {
mDb = new DatabaseHelper(getContext()).getWritableDatabase();
return true;
}
#Override
public Cursor query(Uri uri, String[] ignored1, String ignored2, String[] ignored3, String ignored4) {
String[] projection = new String[]{ReminderProvider.COLUMN_ID, ReminderProvider.COLUMN_TITLE, ReminderProvider.COLUMN_DATE_TIME};
//UriMatcher verwenden, um den Abfragetyp festzustellen und die Datenbankanfrage entsprechend zu formatieren
Cursor c;
switch(sURIMatcher.match(uri)) {
case LIST_REMINDER:
c = mDb.query(ReminderProvider.DATABASE_TABLE, projection, null, null, null, null, null);
break;
case ITEM_REMINDER:
c = mDb.query(ReminderProvider.DATABASE_TABLE, projection, ReminderProvider.COLUMN_ID + "=?", new String[]{Long.toString(ContentUris.parseId(uri))},
null, null, null, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
}
break;
default:
throw new IllegalArgumentException("Unbekannte URI: " + uri);
}
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
#Override
public Uri insert (Uri uri, ContentValues values) {
values.remove(ReminderProvider.COLUMN_ID);
long id = mDb.insertOrThrow(ReminderProvider.DATABASE_TABLE, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
}
#Override
public int delete(Uri uri, String ignored1, String[] ignored2) {
int count = mDb.delete(ReminderProvider.DATABASE_TABLE, ReminderProvider.COLUMN_ID + "=?", new String[]{Long.toString(ContentUris.parseId(uri))});
if (count > 0)
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public int update(Uri uri, ContentValues values, String ignored1, String[] ignored2) {
int count = mDb.update(ReminderProvider.DATABASE_TABLE, values, COLUMN_ID + "=?", new String[]{Long.toString(ContentUris.parseId(uri))});
if (count > 0)
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
//Methode zur Abfrage der unterstuetzten Typen. Sie wird auch in der Methode query() genutzt, um den Typ der empfangenen Uri festzustellen
#Override
public String getType(Uri uri) {
switch (sURIMatcher.match(uri)) {
case LIST_REMINDER:
return REMINDERS_MIME_TYPE;
case ITEM_REMINDER:
return REMINDER_MIME_TYPE;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
//I also tried the following method(s) to be accessed from ReminderEditFragment
//Methode, um mit ID Titel abzufragen
//public Cursor fetchTitle (int id) {
// return mDb.rawQuery("SELECT title FROM data WHERE _id = " +id, null);
//}
public String getTitle(long id) {
String stringTitle = "kein Titel vorhanden";
int intId = (int)id;
Cursor cursor = mDb.rawQuery ("SELECT title FROM data WHERE _id = " +id, null);
if (cursor.moveToFirst()) {
do {
stringTitle = cursor.getString(cursor.getColumnIndex("title"));
}
while(cursor.moveToNext());
}
cursor.close();
return stringTitle;
}
public 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) {
throw new UnsupportedOperationException();
}
}
}
I managed to to solve the issue not by using a constructur, but by adding query method for each of the three fields using the content_uri to the ReminderEditFragment class:
public String savedDate (long id) {
//Abfrage
String[] projection = {
ReminderProvider.COLUMN_ID,
ReminderProvider.COLUMN_TITLE,
ReminderProvider.COLUMN_DATE_TIME
};
Uri singleUri = ContentUris.withAppendedId(ReminderProvider.CONTENT_URI, mRowID);
Cursor cursor = getActivity().getContentResolver().query(
singleUri,
projection,
null,
null,
null);
cursor.moveToFirst();
//Date und Time setzen
String dateS = cursor.getString(2);
long dateJavaTimestamp = Long.parseLong(dateS);
Date date = new Date(dateJavaTimestamp);
String savedDate = new SimpleDateFormat(DATE_FORMAT).format(date);
cursor.close();
return savedDate;
}
public String savedTime (long id) {
//Abfrage
String[] projection = {
ReminderProvider.COLUMN_ID,
ReminderProvider.COLUMN_TITLE,
ReminderProvider.COLUMN_DATE_TIME
};
Uri singleUri = ContentUris.withAppendedId(ReminderProvider.CONTENT_URI, mRowID);
Cursor cursor = getActivity().getContentResolver().query(
singleUri,
projection,
null,
null,
null);
cursor.moveToFirst();
//Date und Time setzen
String dateS = cursor.getString(2);
long dateJavaTimestamp = Long.parseLong(dateS);
Date date = new Date(dateJavaTimestamp);
String savedTime = new SimpleDateFormat(TIME_FORMAT).format(date);
cursor.close();
return savedTime;
}
Maybe this helps someone with a similar issue.
I am trying to code my own content provider for users. When I try to verify if the user exists,when the DBHelper tries to create the database, it throws a null exception.
Here is the content provider:
public class MyUserProvider extends ContentProvider {
private UserDBHelper db;
private static final int USERS = 10;
private static final int USER_ID = 20;
private static final String AUTHORITY =
"net.ifo420.ritc.agenda.userprovider";
private static final String BASE_PATH = "users";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/users";
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/user";
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, USERS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", USER_ID);
}
public MyUserProvider() {
}
#Override
public boolean onCreate() {
db = new UserDBHelper(getContext());
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
checkColumns(projection);
queryBuilder.setTables(UserTable.TABLE);
int uriType = uriMatcher.match(uri);
switch (uriType) {
case USERS:
break;
case USER_ID:
queryBuilder.appendWhere(UserTable.COLUMN_ID + " = " + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Uknown uri " + uri);
}
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor cursor = queryBuilder.query(db1, projection, selection, selectionArgs,
null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = uriMatcher.match(uri);
SQLiteDatabase database = db.getReadableDatabase();
long id = 0;
switch (uriType) {
case USERS:
id = database.insert(UserTable.TABLE, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH + "/" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = uriMatcher.match(uri);
SQLiteDatabase sqLiteDatabase = db.getReadableDatabase();
int rowsDeleted = 0;
switch (uriType) {
case USERS:
rowsDeleted = sqLiteDatabase.delete(UserTable.TABLE, selection,
selectionArgs);
break;
case USER_ID:
String id = uri.getLastPathSegment();
if(TextUtils.isEmpty(selection)) {
rowsDeleted = sqLiteDatabase.delete(UserTable.TABLE,
UserTable.COLUMN_ID + " = " + id, null);
} else {
rowsDeleted = sqLiteDatabase.delete(UserTable.TABLE,
UserTable.COLUMN_ID + " = " + id + " and " +
selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = uriMatcher.match(uri);
SQLiteDatabase sqLiteDatabase = db.getReadableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case USERS:
rowsUpdated = sqLiteDatabase.update(UserTable.TABLE,
values,
selection,
selectionArgs);
break;
case USER_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqLiteDatabase.update(UserTable.TABLE,
values,
UserTable.COLUMN_ID + "=" + id,
null);
} else {
rowsUpdated = sqLiteDatabase.update(UserTable.TABLE,
values,
UserTable.COLUMN_ID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
private void checkColumns(String[] projection) {
String[] available = {UserTable.COLUMN_USERNAME, UserTable.COLUMN_PASSWORD,
UserTable.COLUMN_ID};
if (projection != null) {
HashSet<String> requestedColumns =
new HashSet<String>(Arrays.asList(projection));
HashSet<String> availableColumns =
new HashSet<String>(Arrays.asList(available));
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}
}
Here is my DBHelper
public class UserDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "agenda.db";
private static final int DB_VERSION = 1;
public UserDBHelper (Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
UserTable.onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
UserTable.onUpgrade(db, oldVersion, newVersion);
}
Here is the sample code I am using to verify if the user exists (sorry a bit is in french):
public void onClick(View view) {
switch (view.getId()) {
case R.id.boutonLogin:
if (userExists()) {
Toast.makeText(this, "L'utilisateur existe.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "L'utilisateur n'existe pas.", Toast.LENGTH_SHORT).show();
}
}
private boolean userExists() {
String username = nomUtilisateur.getText().toString();
String password = motPasse.getText().toString();
Cursor users = userProvider.query(MyUserProvider.CONTENT_URI,
null,
" WHERE username = " + nomUtilisateur.getText().toString() +
" AND password = " + motPasse.getText().toString(), null, null);
if (users.getCount() != 0) {
return true;
} else {
return false;
}
Here is what the logcat gives me:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase net.info420.ritc.agendacegep.UserDBHelper.getReadableDatabase()' on a null object reference
at net.info420.ritc.agendacegep.MyUserProvider.query(MyUserProvider.java:70)
at net.info420.ritc.agendacegep.LoginActivity.utilisateurExiste(LoginActivity.java:69)
at net.info420.ritc.agendacegep.LoginActivity.onClick(LoginActivity.java:57)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
You can't directly instantiate and call a ContentProvider- you have to go through a content resolver. Otherwise it doesn't go through the provider's lifecycle and onCreate isn't called.
Well, I got my own answer. Yes I couldn't instantiate my ContentProvider, but it was not only that. I changed my code and realised that I only did not really undertand the selection and selectionArgs parameters in the query.
So it went from:
private boolean userExists() {
String username = nomUtilisateur.getText().toString();
String password = motPasse.getText().toString();
Cursor users = userProvider.query(MyUserProvider.CONTENT_URI,
null,
" WHERE username = " + nomUtilisateur.getText().toString() +
" AND password = " + motPasse.getText().toString(), null, null);
if (users.getCount() != 0) {
return true;
} else {
return false;
}
}
To :
private boolean userExists() {
String username = nomUtilisateur.getText().toString();
String password = motPasse.getText().toString();
String[] selection = {username, password};
Cursor users = getApplicationContext().getContentResolver().query
(Agenda.UserEntry.CONTENT_URI,
null,
"username = ? AND password = ?", selection, null);
if (users.getCount() != 0) {
return true;
} else {
return false;
}
}
So, the cursor was null because I did not make a correct query and that is why my database was not created: because i did not need it at the end in my code.
i can't get my data to show on my ListView. i created database handler with a query that says: "SELECT * FROM TABLE_NAME WHERE COLUMN_USERNAME = '"+Username+"'". i want to show Data that have the username i want only. But i cant seem to get it work. here is the code.
ViewEvent class with the List View
public class ViewEvent extends Activity {
private static String z = "";
private static final int _EDIT = 0, _DELETE = 1; // constants to be used later
static int longClickedItemIndex;
static List<Event> events = new ArrayList<Event>();
ArrayAdapter<Event> eventsAdapter;
ListView listViewEvents;
static DatabaseHandlerEvent helper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_event);
Typeface myTypeFace = Typeface.createFromAsset(getAssets(), "Type Keys Filled.ttf");
TextView myTextview = (TextView) findViewById(R.id.textViewHead4);
myTextview.setTypeface(myTypeFace);
helper = new DatabaseHandlerEvent(getApplicationContext());
listViewEvents = (ListView) findViewById(R.id.listView);
registerForContextMenu(listViewEvents);
listViewEvents.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
}
);
populateList();
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Username = prfs.getString("Username", "");
if (helper.getEventCount() != 0 && events.size() == 0) {
events.addAll(helper.getAllEvent(Username));
}
}
public void registerForContextMenu(View view) {
view.setOnCreateContextMenuListener(this);
}
public void onButtonClick(View v){
if(v.getId() == R.id.bSignoutb){
Toast so = Toast.makeText(ViewEvent.this, "Signing out.. Redirecting to Login Page..." , Toast.LENGTH_SHORT);
so.show();
Intent i = new Intent(ViewEvent.this, MainActivity.class);
startActivity(i);
}
if(v.getId() == R.id.Bback){
Intent i = new Intent(ViewEvent.this, CreateEvent.class);
startActivity(i);
}
}
private void populateList() {
eventsAdapter = new eventListAdapter();
listViewEvents.setAdapter(eventsAdapter);
}
public class eventListAdapter extends ArrayAdapter<Event> {
public eventListAdapter() {
super(ViewEvent.this, R.layout.listview_event, events);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listview_event, parent, false);
}
Event currentEvent = events.get(position);
TextView name = (TextView) view.findViewById(R.id.textViewEventName);
name.setText(currentEvent.getName());
TextView location = (TextView) view.findViewById(R.id.textViewLocation);
location.setText(currentEvent.getLocation());
TextView date = (TextView) view.findViewById(R.id.textViewDate);
date.setText(currentEvent.getDate());
TextView description = (TextView) view.findViewById(R.id.textViewDescription);
description.setText(currentEvent.getDescription());
TextView time = (TextView) view.findViewById(R.id.textViewTime);
time.setText(currentEvent.getTime());
TextView testnia = (TextView) view.findViewById(R.id.testnia);
testnia.setText(currentEvent.getUsername());
return view;
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.huhu);// find a suitable icon
menu.setHeaderTitle("Event options:");
menu.add(Menu.NONE, _EDIT, Menu.NONE, "Edit Event");
menu.add(Menu.NONE, _DELETE, Menu.NONE, "Delete Event");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case _EDIT:
// editing a contact
Intent editContactIntent = new Intent(getApplicationContext(), EditEvent.class);
startActivityForResult(editContactIntent, 2); // reqcode=2
break;
case _DELETE:
helper.deleteEvent(events.get(longClickedItemIndex));
events.remove(longClickedItemIndex);
eventsAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
}
And this is my DataBaseHelperEvent class
public class DatabaseHandlerEvent extends SQLiteOpenHelper {
static DatabaseHelperUser helper;
Event event;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Events";
private static final String TABLE_NAME = "Events";
private static final String COLUMN_ID = "id",
COLUMN_NAME = "name", COLUMN_LOCATION = "location", COLUMN_DATE = "date",
COLUMN_TIME ="time", COLUMN_DESCRIPTION = "description", COLUMN_USERNAME = "username";
SQLiteDatabase db;
public DatabaseHandlerEvent(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " + COLUMN_LOCATION + " TEXT, " +
COLUMN_DATE + " TEXT, " + COLUMN_TIME + " TEXT, " +
COLUMN_DESCRIPTION + " TEXT, " + COLUMN_USERNAME + " TEXT)"
);
}
public long createEvent (Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
values.put(COLUMN_USERNAME, event.getUsername());
long result = db.insert(TABLE_NAME, null, values);
db.close();
return result;
}
public int updateEvent(Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
int rowsAffected = db.update(TABLE_NAME, values, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
public List<Event> getAllEvent(String Username) {
List<Event> events = new ArrayList<Event>();
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE "+COLUMN_USERNAME+" = "+ "'"+Username+"'", null);
if (cursor.moveToFirst()) {
do {
events.add(new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4),
cursor.getString(5), cursor.getString(6)));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return events;
}
public int getEventCount() {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public int deleteEvent(Event event) {
db = this.getWritableDatabase();
int rowsAffected = db.delete(TABLE_NAME, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
So whenever i show my ListView, it will show nothing. How can i show the data that only have a specific username i want? thanks! Sorry for my bad english
The error occurs when the app starts.
Tried to define:
queryBuilder.setTables(Constants.NOTES_TABLE);
but that gives an error saying
android.database.sqlite.SQLiteException: no such column:
The complete error:
Caused by: java.lang.IllegalStateException: Invalid tables
at android.database.sqlite.SQLiteDatabase.findEditTable(SQLiteDatabase.java:973)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:400)
at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:294)
at com.hackathon.hackmsit.data.NoteContentProvider.query(NoteContentProvider.java:70)
at android.content.ContentProvider.query(ContentProvider.java:1000)
at android.content.ContentProvider$Transport.query(ContentProvider.java:214)
at android.content.ContentResolver.query(ContentResolver.java:478)
at android.content.ContentResolver.query(ContentResolver.java:422)
at com.hackathon.hackmsit.data.NoteManager.getAllNotes(NoteManager.java:60)
at com.hackathon.hackmsit.fragments.NoteListFragment.setupList(NoteListFragment.java:98)
at com.hackathon.hackmsit.fragments.NoteListFragment.onCreateView(NoteListFragment.java:54)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:511)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6057)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1319)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5287)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:114)
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private com.mikepenz.materialdrawer.Drawer result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
DatabaseHelper databaseHelper = new DatabaseHelper(this);
databaseHelper.getWritableDatabase();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.withActionBarDrawerToggle(true)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.title_home).withIcon(FontAwesome.Icon.faw_home).withIdentifier(1),
//new PrimaryDrawerItem().withName(R.string.title_editor).withIcon(FontAwesome.Icon.faw_edit).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.title_settings).withIcon(FontAwesome.Icon.faw_list).withIdentifier(2)
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int i, IDrawerItem drawerItem) {
if (drawerItem != null && drawerItem instanceof Nameable){
String name = ((Nameable)drawerItem).getName().getText(MainActivity.this);
mToolbar.setTitle(name);
}
if (drawerItem != null){
int selectedScreen = drawerItem.getIdentifier();
switch (selectedScreen){
case 1:
//go to List of Notes
openFragment(new NoteListFragment(), "Notes");
break;
/*case 2:
//go the editor screen
startActivity(new Intent(MainActivity.this, NoteEditorActivity.class));*/
case 2:
//go to settings screen, yet to be added
//this will be your home work
Toast.makeText(MainActivity.this, "Settings Clicked", Toast.LENGTH_SHORT).show();
break;
}
}
return false;
}
})
.withOnDrawerListener(new Drawer.OnDrawerListener() {
#Override
public void onDrawerOpened(View view) {
KeyboardUtil.hideKeyboard(MainActivity.this);
}
#Override
public void onDrawerClosed(View view) {
}
#Override
public void onDrawerSlide(View view, float v) {
}
})
.withFireOnInitialOnClick(true)
.withSavedInstance(savedInstanceState)
.build();
if (savedInstanceState == null){
result.setSelection(1);
}
}
#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);
}
private void openFragment(final Fragment fragment, String title){
getSupportFragmentManager()
.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
getSupportActionBar().setTitle(title);
}
}
NoteContentProvider.java:
public class NoteContentProvider extends ContentProvider {
private DatabaseHelper dbHelper;
private static final String BASE_PATH_NOTE = "notes";
private static final String AUTHORITY = "com.hackathon.hackmsit.data.provider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_NOTE);
private static final int NOTE = 100;
private static final int NOTES = 101;
private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
static {
URI_MATCHER.addURI(AUTHORITY, BASE_PATH_NOTE, NOTES);
URI_MATCHER.addURI(AUTHORITY, BASE_PATH_NOTE + "/#", NOTE);
}
private SQLiteDatabase db;
private void checkColumns(String[] projection) {
if (projection != null) {
HashSet<String> request = new HashSet<>(Arrays.asList(projection));
HashSet<String> available = new HashSet<>(Arrays.asList(Constants.COLUMNS));
if (!available.containsAll(request)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}
}
#Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
db = dbHelper.getWritableDatabase();
return (db == null)? false:true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(Constants.NOTES_TABLE);
checkColumns(projection);
int type = URI_MATCHER.match(uri);
switch (type){
case NOTE:
//there is not to do if the query is for the table
break;
case NOTES:
queryBuilder.appendWhere(Constants.COLUMN_ID + " = " + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int type = URI_MATCHER.match(uri);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Long id;
switch (type){
case NOTES:
id = db.insert(Constants.NOTES_TABLE, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH_NOTE + "/" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int type = URI_MATCHER.match(uri);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int affectedRows;
switch (type) {
case NOTES:
affectedRows = db.delete(Constants.NOTES_TABLE, selection, selectionArgs);
break;
case NOTE:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
affectedRows = db.delete(Constants.NOTES_TABLE, Constants.COLUMN_ID + "=" + id, null);
} else {
affectedRows = db.delete(Constants.NOTES_TABLE, Constants.COLUMN_ID + "=" + id + " and " + selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return affectedRows;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int type = URI_MATCHER.match(uri);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int affectedRows;
switch (type) {
case NOTES:
affectedRows = db.update(Constants.NOTES_TABLE, values, selection, selectionArgs);
break;
case NOTE:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
affectedRows = db.update(Constants.NOTES_TABLE, values, Constants.COLUMN_ID + "=" + id, null);
} else {
affectedRows = db.update(Constants.NOTES_TABLE, values, Constants.COLUMN_ID + "=" + id + " and " + selection, selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return affectedRows;
}
}
DatabaseHelper.java:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "notes.db";
private static final int DATABASE_VERSION = 3;
private static final String CREATE_TABLE_NOTE = "create table "
+ Constants.NOTES_TABLE
+ "("
+ Constants.COLUMN_ID + " integer primary key autoincrement, "
+ Constants.COLUMN_TITLE + " text not null, "
+ Constants.COLUMN_CONTENT + " text not null, "
+ Constants.COLUMN_MODIFIED_TIME + " integer not null, "
+ Constants.COLUMN_CREATED_TIME + " integer not null " + ");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_NOTE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Constants.NOTES_TABLE);
onCreate(db);
}
}
Manifest entry:
<provider
android:name=".data.NoteContentProvider"
android:authorities="com.hackathon.hackmsit.data.provider"
android:exported="false" />
Edit:
Constants.java:
public class Constants {
public static final String NOTES_TABLE = "notes";
public static final String COLUMN_ID = "_id";
//public final static String COLUMN_NAME = "name";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_CONTENT = "content";
public static final String COLUMN_MODIFIED_TIME = "modified_time";
public static final String COLUMN_CREATED_TIME = "created_time";
public static final String[] COLUMNS = {
Constants.COLUMN_ID,
Constants.COLUMN_TITLE,
Constants.COLUMN_CONTENT,
Constants.COLUMN_MODIFIED_TIME,
Constants.COLUMN_CREATED_TIME
};
}
Any help is appreciated.
android.database.sqlite.SQLiteException: no such column:
At First Modify your CREATE TABLE Statement
String CREATE_TABLE_NOTE = "CREATE TABLE " + Constants.NOTES_TABLE + "("
+ Constants.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Constants.COLUMN_TITLE + " TEXT Default 'Unknown', "
+ Constants.COLUMN_CONTENT + " TEXT Default 'Unknown', "
+ Constants.COLUMN_MODIFIED_TIME + " INTEGER, "
+ Constants.COLUMN_CREATED_TIME + " INTEGER )";
Then Un-install old App & Run Again .
I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, int port, int passive) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
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_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView
.findViewById(R.id.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);