I obviously new and have been trying to two days to figure out how to save the state of my main activity to no avail. I would appreciate any help. When I launch the ShowDetail activity and return to the main activity I have no data in the list. I have two xml files a main.xml and a item.xml file. main is just a listview and a textview. Item.xml is 3 textviews for the data in the list. Item Here is the code from my main activity:
public class main extends ListActivity {
private EventsData events;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
events = new EventsData(this);
try {
Cursor cursor = getEvents();
showEvents(cursor);
} finally {
events.close();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onRestart(){
super.onRestart();
}
private static String[] FROM = { CODE, EXCERPT, _ID, };
private static String ORDER_BY = CODE + " ASC";
private Cursor getEvents() {
SQLiteDatabase db = events.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
private static int[] TO = { R.id.code, R.id.excerpt, };
private void showEvents(Cursor cursor) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
private static String[] MIKEY = { _ID, CODE, DEFINITION };
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = ((CursorAdapter)getListAdapter()).getCursor();
cursor.getLong(2);
SQLiteDatabase db = events.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, MIKEY, "_id = "+cursor.getLong(2)+"", null, null, null, null);
c.moveToFirst();
Intent in1 = new Intent();
Bundle bun = new Bundle();
bun.putLong("id", c.getLong(0));
bun.putString("code", c.getString(1));
bun.putString("definition", c.getString(2));
in1.setClass(this, ShowDetail.class);
in1.putExtras(bun);
startActivity(in1);
}
}
I'd say you need to place your general actions into onResume() instead of in onCreate().
Maybe a look at the application lifecycle helps understanding what I mean:
http://developer.android.com/reference/android/app/Activity.html
Related
I have strange problem with my android app. I have some data and I saved that data in SQLite Database. And in this fragment I try to read my data from table using SimpleCursorAdapter
public class LogFragment extends Fragment{
private static SQLiteDatabase db;
private static SQLiteOpenHelper helper;
private static Context context;
private static ListView listView;
private static String senderOrReceiver;
private static SimpleCursorAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
adapter = new SimpleCursorAdapter(context, R.layout.log_message, null,
new String[]{Constants.COMMAND, Constants.VALUE, Constants.TIME_STAMP, Constants.MESSAGE_ID, Constants.SESSION_ID, Constants.PARAMS},
new int[]{R.id.command, R.id.value, R.id.time_stamp, R.id.message_id, R.id.session_id, R.id.params}, 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_log, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
listView = (ListView) view.findViewById(R.id.listView);
}
#Override
public void onDestroy() {
super.onDestroyView();
if(db != null){
db.close();
}
}
public static void readFromDatabase(String sender){
senderOrReceiver = sender;
new DatabaseTalker().execute();
}
private static class DatabaseTalker extends AsyncTask <Void, Void, Cursor>{
#Override
protected Cursor doInBackground(Void... params) {
helper = new Database(context);
db = helper.getReadableDatabase();
return db.query(Constants.TABLE_NAME, null, null, null, null, null, null);
}
#Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
adapter.changeCursor(cursor);
listView.setAdapter(adapter);
}
}
}
and here's what I got in my ListView . I have six fields (Command, Value, Time Stamp, MessageID, SessionID, Params) and as you can see only one field is filled (for example) Command: On, Value: , Time Stamp: , MessageID: , SessionID: , Params: . and so on... Why I get this result?
EDIT:
Here how I write my data to database
public void addInfo(Information info){
SQLiteDatabase db = this.getWritableDatabase();
addToTable(db, Constants.COMMAND, info.getCommand());
addToTable(db, Constants.VALUE, info.getValue());
addToTable(db, Constants.TIME_STAMP, info.getTimeStamp());
addToTable(db, Constants.MESSAGE_ID, info.getMessageID());
addToTable(db, Constants.SESSION_ID, info.getSessionID());
addToTable(db, Constants.PARAMS, info.getParams());
db.close();
}
private static void addToTable(SQLiteDatabase db, final String TAG, String value){
ContentValues values = new ContentValues();
values.put(TAG, value);
db.insert(Constants.TABLE_NAME, null, values);
}
Your each addToTable() call inserts a new row that contains just one column value.
To insert a row with all the values, add the values to the same ContentValues and call insert() once.
I am developping an Android app which loads reddits and put it in a db, I use an asynchron cursor loader in my fragment SubredditsFragment.class. This fragment contains an adapter, which has a cursor loader. When I stop or reset the loader, the loader needs to be swapped on my adapter.
public class SubRedditsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private List<SubRedditData> subRedditDataList;
private IntentFilter filter;
public static final String TAG = SubRedditsFragment.class.getName();
private SubredditAdapter adapter;
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = null;
String where = null;
String[] whereArgs = null;
String sortOrder = null;
Uri queryUri = RedditContentProvider.CONTENT_URI;
return new CursorLoader(getActivity(), queryUri, projection, where, whereArgs, sortOrder);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG,"Added broadcastreceiver");
getActivity().registerReceiver(receiver,filter);
adapter = new SubredditAdapter(getActivity().getApplicationContext(),subRedditDataList);
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
getLoaderManager().destroyLoader(loader.getId());
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
The problem is that I can't use the method adapter.swapCursor(), it's unknown for Android. I get the error message Cannot resolve method 'swapCursor(loader)'
add this code in your Adapter, mCursor is the global cursor variable
public void swapCursor(Cursor newCursor) {
// Always close the previous mCursor first
if (mCursor != null) mCursor.close();
mCursor = newCursor;
if (newCursor != null) {
// Force the RecyclerView to refresh
this.notifyDataSetChanged();
}
}
I have a listFragment and when an item of the list is clicked it starts a new activity. When back button is pressed, the list is shown again. Im using cursor Loaders so, I want to know if is there an easy way to refresh the cursor loader when back button is pressed. This is because the new activity changes the contents of the list.
Edit:
public class ListWordFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static String TAG = ListWordFragment.class.getSimpleName();
private CursorLoader cursorLoader;
// Loader
private static final int URL_LOADER = 0;
private SimpleCursorAdapter adapter;
public static LoaderManager mLoaderManager;
// ActionBar
private AutoCompleteTextView autoCompView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_words, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView list = getListView();
String[] from = new String[] { Word.NAME, Word.TYPE, Word.TRANSLATE };
int[] to = new int[] { R.id.textView_word, R.id.textView_type,
R.id.textView_translate };
adapter = new ListWordAdapter(getSherlockActivity(),
R.layout.row_list_words, null, from, to, 0);
setListAdapter(adapter);
mLoaderManager = getLoaderManager();
mLoaderManager.initLoader(URL_LOADER, null, this);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
fillRow(l, id, position, false);
}
private void fillRow(ListView l, long ide, int position, boolean firstCall) {
Cursor cursor = getActivity().getContentResolver().query(
Uri.withAppendedPath(WordListProvider.WORDS_CONTENT_URI,
String.valueOf(ide)), null, null, null, null);
if(cursor.moveToFirst()){
String id = cursor.getString(cursor.getColumnIndex(Word.ID));
String name = cursor.getString(cursor.getColumnIndex(Word.NAME));
String type = cursor.getString(cursor.getColumnIndex(Word.TYPE));
String translate = cursor.getString(cursor
.getColumnIndex(Word.TRANSLATE));
String example = cursor.getString(cursor.getColumnIndex(Word.EXAMPLE));
String note = cursor.getString(cursor.getColumnIndex(Word.NOTE));
// Master/Detail
if ((getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
&& (getResources().getString(R.string.selected_configuration)
.equals(Constants.CONFIGURATION_LARGE))) {
WordDetailFragment frag = (WordDetailFragment) getFragmentManager()
.findFragmentById(R.id.word_detail_fragment);
if (frag != null) {
frag.setId(id);
frag.setName(name);
frag.setType(type);
frag.setTranslate(translate);
frag.setExample(example);
frag.setNote(note);
}
} else if (firstCall) {
// Do nothing
} else {
Intent i = new Intent(getActivity().getApplicationContext(),
WordDetailActivity.class);
i.putExtra(Word.ID, id);
i.putExtra(Word.NAME, name);
i.putExtra(Word.TYPE, type);
i.putExtra(Word.TRANSLATE, translate);
i.putExtra(Word.EXAMPLE, example);
i.putExtra(Word.NOTE, note);
startActivity(i);
}
cursor.close();
}
}
public void onWordSaved() {
getLoaderManager().restartLoader(URL_LOADER, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle) {
String[] projection = { Word.ID, Word.NAME, Word.TYPE, Word.TRANSLATE,
Word.EXAMPLE, Word.NOTE };
/* Takes action based on the ID of the Loader that's being created */
switch (loaderID) {
case URL_LOADER:
// Returns a new CursorLoader
cursorLoader = new CursorLoader(getSherlockActivity(), // Parent
// activity
// context
WordListProvider.WORDS_CONTENT_URI, // Table to query
projection, // Projection to return
null, // No selection clause
null, // No selection arguments
null // Default sort order
);
return cursorLoader;
default:
// An invalid id was passed in
return null;
}
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
Try adding to your Fragment class:
#Override
protected void onResume()
{
super.onResume();
getLoaderManager().restartLoader(URL_LOADER, null, this);
}
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
To clear up your efficiency concern: When you call the initial init, it will start, but restartLoader on the same ID will automatically cancel that previous request and start a new one. So it won't get executed fully twice on activity start up.
More info in Google Loader Dev Doco.
My SimpleCursorAdapter does not display any data from the ArrayList that I pass into it! Why is this and how do I fix it?
Here's my ListFragment, you can see the SimpleCursorAdapter being used in the onViewCreated() method.
public class CourseListFragment extends SherlockListFragment {
SQLiteDatabase db;
DbHelper dbHelper;
private static String courseName;
ArrayList<String> courseItems;
SimpleCursorAdapter adapter;
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(String id);
}
/**
* A dummy implementation of the {#link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
#Override
public void onItemSelected(String id) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public CourseListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState
.getInt(STATE_ACTIVATED_POSITION));
}
dbHelper = new DbHelper(getActivity());
db = dbHelper.getWritableDatabase();
courseItems = new ArrayList<String>();
String[] projection = new String[] {DbHelper.COURSE_NAME, DbHelper.C_ID};
String[] from = new String[] { DbHelper.COURSE_NAME };
Cursor cursor = db.query(DbHelper.TABLE_NAME, projection, null, null, null, null, null);
// Fields on the UI to which we map
int[] to = new int[] { getListView().getId() };
int layout = (Build.VERSION.SDK_INT >= 11) ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
adapter = new SimpleCursorAdapter(getActivity(), layout, cursor, from, to, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
// The problem starts here
SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
getListView(),
new SwipeDismissListViewTouchListener.OnDismissCallback() {
public void onDismiss(ListView listView,
int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
removeCourse(position);
adapter.notifyDataSetChanged();
}
}
});
getListView().setOnTouchListener(touchListener);
getListView().setOnScrollListener(touchListener.makeScrollListener());
adapter.notifyDataSetChanged();
}
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
String[] projection = { DbHelper.COURSE_NAME };
Cursor c = db.query(DbHelper.TABLE_NAME, projection, null, null, null,
null, null);
c.moveToFirst();
while (c.moveToNext()) {
courseName = c.getString(c.getColumnIndex(DbHelper.COURSE_NAME));
courseItems.add(courseName);
}
c.close();
adapter.notifyDataSetChanged();
}
public void addCourse() {
String[] projection = { DbHelper.COURSE_NAME };
Cursor c = db.query(DbHelper.TABLE_NAME, projection, null, null, null,
null, null);
c.moveToLast();
courseName = c.getString(c.getColumnIndex(DbHelper.COURSE_NAME));
courseItems.add(courseName);
c.close();
adapter.notifyDataSetChanged();
}
public void removeCourse(int position) {
String[] projection = { DbHelper.C_ID, DbHelper.COURSE_NAME };
Cursor c = db.query(DbHelper.TABLE_NAME, projection, null, null, null,
null, null);
c.moveToPosition(position);
db.delete(DbHelper.TABLE_NAME, DbHelper.C_ID + "=" + position,
null);
c.close();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
#Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
#Override
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(null);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(
activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
public void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
}
Thanks! Much appreciated!
*Edit: Updated code using SimpleCursorAdapter*
public class CourseListFragment extends SherlockListFragment {
SQLiteDatabase db;
DbHelper dbHelper;
private static String courseName;
ArrayList<String> courseItems;
SimpleCursorAdapter adapter;
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(String id);
}
/**
* A dummy implementation of the {#link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
#Override
public void onItemSelected(String id) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public CourseListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState
.getInt(STATE_ACTIVATED_POSITION));
}
dbHelper = new DbHelper(getActivity());
db = dbHelper.getWritableDatabase();
courseItems = new ArrayList<String>();
final String[] projection = new String[] {DbHelper.COURSE_NAME, DbHelper.C_ID};
Cursor cursor = db.query(DbHelper.TABLE_NAME, projection, null, null, null, null, null);
// Fields on the UI to which we map
final String[] from = new String[] { DbHelper.COURSE_NAME };
final int[] to = new int[] { R.id.internalEmpty };
final int layout = (Build.VERSION.SDK_INT >= 11) ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
adapter = new SimpleCursorAdapter(getActivity(), layout, cursor, from, to, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
// The problem starts here
SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
getListView(),
new SwipeDismissListViewTouchListener.OnDismissCallback() {
public void onDismiss(ListView listView,
int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
removeCourse(position);
Cursor c = db.query(DbHelper.TABLE_NAME, projection, null, null, null, null, null);
adapter = new SimpleCursorAdapter(getActivity(), layout, c, from, to, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
}
}
});
getListView().setOnTouchListener(touchListener);
getListView().setOnScrollListener(touchListener.makeScrollListener());
adapter.notifyDataSetChanged();
}
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
String[] projection = { DbHelper.COURSE_NAME };
Cursor c = db.query(DbHelper.TABLE_NAME, projection, null, null, null,
null, null);
c.moveToFirst();
while (c.moveToNext()) {
courseName = c.getString(c.getColumnIndex(DbHelper.COURSE_NAME));
courseItems.add(courseName);
}
c.close();
adapter.notifyDataSetChanged();
}
public void addCourse() {
String[] projection = { DbHelper.COURSE_NAME };
Cursor c = db.query(DbHelper.TABLE_NAME, projection, null, null, null,
null, null);
c.moveToLast();
courseName = c.getString(c.getColumnIndex(DbHelper.COURSE_NAME));
courseItems.add(courseName);
c.close();
adapter.notifyDataSetChanged();
}
public void removeCourse(int position) {
String[] projection = { DbHelper.C_ID, DbHelper.COURSE_NAME };
Cursor c = db.query(DbHelper.TABLE_NAME, projection, null, null, null,
null, null);
c.moveToPosition(position);
db.delete(DbHelper.TABLE_NAME, DbHelper.C_ID + "=" + position,
null);
c.close();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
#Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
#Override
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(null);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(
activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
public void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
}
int[] to = new int[] { getListView().getId() };
that line is wrong. and i cant imagine what's happening behind the scenes. the int[] to is supposed to be for example
int[] to = new int[] {R.id.text1};
the id of the textView in the int layout parameter that you passed to the SimpleCursorAdapter, that you want the columns of String[] from to be written to. i suggest you find out the textView id contents of:
int layout = (Build.VERSION.SDK_INT >= 11) ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
Then make a conditional statement just like that.
EDIT use the following line
int[] to = new int[] {android.R.id.text1};
My goal is to swipe lists horizontally , which are filled by public class ClientsManagerOpenHandler extends SQLiteOpenHelper.
I try to reach this goal by working with viewpager and ListFragments. If you have an other solution please tell me.
Now the problem:
If I try to call from the following PageListFragment.java, data from ClientsManagerOpenHandler the program crashes at:
dbCursorTerminAnsicht = openHandler.queryTabelle("terminansicht");
Maybe I cannot call an extended SQLiteOpenHelper within ListFragment? But how I get the data from sqlite into my lists, and when I swipe horizontally to change data...
Please help. I have tried anything, but I really need help now.
public class PageListFragment extends ListFragment implements OnClickListener,
LoaderCallbacks<Cursor> {
private Calendar cal = Calendar.getInstance();
private ClientsManagerOpenHandler openHandler;
public static final String PREFS_NAME ="MyPrefsFile";
SharedPreferences prefs;`
private Cursor dbCursorTerminAnsicht;
private Integer intVerdienst = 0;
private String queryVerdienst;
private SimpleCursorAdapter mCursorAdapter;
private ListView listViewTermine;
private final int listNr;
private final String[] fruit = { "Bananen", "Apfle", "Erdbeere",
"Kirschen", "Mangos" };
private Uri[] mMediaSource = {null, MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI};
public PageListFragment(int nr) {
this.listNr = nr;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//!!!!! after the next line the program crashes. Even I have set breakpoints at ClientsManagerOpenHandler
//I cannot see anything in the debugger (Debugger: Source not found...)
dbCursorTerminAnsicht = openHandler.queryTabelle("terminansicht");
if (listNr == 0) {
ArrayAdapter<String> openHandler = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1, fruit);
setListAdapter(openHandler);
} else if (listNr == 1) {
mCursorAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, null,
new String[] { MediaStore.Audio.Artists.ARTIST },
new int[] { android.R.id.text1 }, 0);
setListAdapter(mCursorAdapter);
getLoaderManager().initLoader(0, null, this);
} else if (listNr == 2) {
openHandler = new ClientsManagerOpenHandler(getActivity());
String query = "projekte, klienten, termine WHERE termine.KLIENTID = klienten._id AND termine.PROJEKTID = projekte._id ORDER BY BEGINN ASC;";
MyDataAdapter myClientsadapter = new MyDataAdapter (
getActivity(),
R.layout.terminzeile,
// android.R.layout.two_line_list_item,
dbCursorTerminAnsicht,
new String[] { openHandler.BEGINN , openHandler.ENDE, openHandler.NACHNAME, openHandler.VORNAME, openHandler.PROJEKT, openHandler.BEZAHLT},
// fields,
// new int[] {R.id.editTextNachname, R.id.editTextVorname }
new int[] {R.id.textViewBeginn, R.id.textViewEnde, R.id.textViewNachname, R.id.textViewVorname, R.id.textViewProjekt,R.id.checkBoxBezahlt }
);
myClientsadapter.setViewBinder(new MyDataAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(columnIndex == 13) {
String strBeginn = cursor.getString(columnIndex);
CheckBox cb = (CheckBox) view;
int intbezahlt = cursor.getInt(13);
int index = cursor.getColumnIndex("SATZ");
Integer intSatz = cursor.getInt(index);
if (index>0) {
if (intbezahlt>0){
intVerdienst = intVerdienst + intSatz;
}
}
cb.setChecked(intbezahlt > 0);
return true;
}
String str = cursor.getString(columnIndex);
return false;
}
});
//TerminlisteRefresh("");
setListAdapter(myClientsadapter);
getLoaderManager().initLoader(0, null, this);
}
}
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Loader<Cursor> loader = new CursorLoader(getActivity(), mMediaSource[listNr],
null, null, null, null);
return loader;
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
public void onLoaderReset(Loader<Cursor> arg0) {
mCursorAdapter.swapCursor(null);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
It appears that you are trying to access openHandler before you have defined it:
dbCursorTerminAnsicht = openHandler.queryTabelle("terminansicht");
...
openHandler = new ClientsManagerOpenHandler(getActivity());
This might work better:
openHandler = new ClientsManagerOpenHandler(getActivity());
dbCursorTerminAnsicht = openHandler.queryTabelle("terminansicht");