Problems with onListItemClick (mNotesCursor) - java

i am using the developer.android Notepad tutorial (http://developer.android.com/training/notepad/notepad-ex2.html)
to create a Noteapp,
but i have problems with the onItemClick and i cant figure out, where the problem lies.
My Code
public class MainActivity extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
public static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private int mNoteNumber = 1;
private NotesDbAdapter mDbHelper;
public static String notesstring;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
ImageButton b = (ImageButton) findViewById(R.id.add);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Intent i = new Intent(MainActivity.this, NoteScreen.class);
//startActivity(i);
createNote();
}
});
}
private void fillData() {
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainactivitymenu, menu);
return result;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId() ) {
case INSERT_ID:
createNote();
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Settings.class);
startActivity(i);
return true;
/*case R.id.action_new:
Intent e = new Intent(MainActivity.this, NoteScreen.class);
startActivity(e);
return true;
*/
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteNote(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createNote() {
Intent i = new Intent (this, NoteScreen.class);
startActivityForResult(i, ACTIVITY_CREATE);
/*String noteName = "Note " + mNoteNumber++;
mDbHelper.createNote(noteName, "");
fillData();*/
}
And this is the part where the Errors are:
#Override
protected void onListItemClick(ListView list, View v, int position, long id) {
super.onListItemClick(list, v, position, id);
Cursor c = mNotesCurser;
c.moveToPosition(position);
Intent i = new Intent(this, NoteScreen.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
switch(requestCode) {
case ACTIVITY_CREATE:
String title = extras.getString(NotesDbAdapter.KEY_TITLE);
String body = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.createNote(title, body);
fillData();
break;
case ACTIVITY_EDIT:
Long rowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (rowId != null) {
String editTitle = extras.getString(NotesDbAdapter.KEY_TITLE);
String editBody = extras.getString(NotesDbAdapter.KEY_BODY);
mDbHelper.updateNote(rowId, editTitle, editBody);
}
fillData();
break;
}
}
}
mNotesCurser cannot be resolved to a variable
Any idea how to fix this?

Change
protected void onListItemClick(ListView 1, View v, int position, long id)
to
protected void onListItemClick(ListView list, View v, int position, long id)
and use list variable to communicate with ListView.
Note : never use numbers as a single character for variable name. Java restrict that.
And before start creating apps for android, i recommend to you read at least one book about Java.

Replace your code with :
#Override
protected void onListItemClick(ListView listView, View v, int position, long id) {
super.onListItemClick(listView, v, position, id);
Java doesn't allow to declare variables only with numbers.
A variable's name can be any legal identifier — an unlimited-length
sequence of Unicode letters and digits, beginning with a letter, the
dollar sign "$", or the underscore character "_".

Related

How can I add a delete notes funcation to my app

I'm creating a app that is for notes. I'm trying to figure out how to create a function that will delete the Note by having an option in a menu inside of the edit portion of the app that you can press and then it will delete the note. Can someone please point me in the right direction to doing something like this? I have included my code below for both my main activity Java file and my editor activity file
Main
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_note) {
// Going from MainActivity to NotesEditorActivity
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set == null) {
notes.add("Welcome To Notes!!!!!");
} else {
notes = new ArrayList(set);
}
// Using custom listView Provided by Android Studio
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Going from MainActivity to NotesEditorActivity
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int itemToDelete = i;
// To delete the data from the App
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
}).setNegativeButton("No", null).show();
return true;
}
});
}
}
Editer
public class NoteEditorActivity extends AppCompatActivity {
int noteId;
static ArrayList<String> notes = new ArrayList<>();
#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.
if (item.getItemId() == R.id.add_note) {
}
int id = item.getItemId();
if(id == android.R.id.home){
Intent i= new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//To have the back button!!
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_note_editor);
EditText editText = findViewById(R.id.editText);
Intent intent = getIntent();
noteId = intent.getIntExtra("noteId", -1);
if (noteId != -1) {
editText.setText(MainActivity.notes.get(noteId));
} else {
MainActivity.notes.add("");
noteId = MainActivity.notes.size() - 1;
MainActivity.arrayAdapter.notifyDataSetChanged();
}
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// add your code here
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
MainActivity.notes.set(noteId, String.valueOf(charSequence));
MainActivity.arrayAdapter.notifyDataSetChanged();
// Creating Object of SharedPreferences to store data in the phone
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
#Override
public void afterTextChanged(Editable editable) {
// add your code here
}
});
}
}

Attempt to invoke virtual method 'java.lang.String java.util.HashSet.toString(). getting null pointer exception

android studio doesnt show any error while typing, this error comes only when running. Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.util.HashSet.toString()' on a null object reference
problem should be in one of these three lines
HashSet set = (HashSet) sharedPreferences.getStringSet("notes", null);
Log.i("test", set.toString());
if (set == null) {
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_note) {
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
Log.i("test", set.toString());
if (set == null) {
notes.add("Example note");
} else {
notes = new ArrayList(set);
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int itemToDelete = i;
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
}
)
.setNegativeButton("No", null)
.show();
return true;
}
});
}
}
//2nd class
public class NoteEditorActivity extends AppCompatActivity {
int noteId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_editor);
EditText editText = (EditText) findViewById(R.id.editText);
Intent intent = getIntent();
noteId = intent.getIntExtra("noteId", -1);
if (noteId != -1) {
editText.setText(MainActivity.notes.get(noteId));
} else {
MainActivity.notes.add("");
noteId = MainActivity.notes.size() - 1;
MainActivity.arrayAdapter.notifyDataSetChanged();
}
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
MainActivity.notes.set(noteId, String.valueOf(charSequence));
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
// problem is here. "set" object is null.
Log.i("test", set.toString());
if (set == null) {
notes.add("Example note");
} else {
notes = new ArrayList(set);
}
change to
if (set == null) {
notes.add("Example note");
} else {
notes = new ArrayList(set);
// suggestion use Log.d("test", set.toString()); since d -> debug, i->
// information
Log.i("test", set.toString());
}
You have to test if its null befote using it
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set == null) {
notes.add("Example note");
} else {
Log.i("test", set.toString());
notes = new ArrayList(set);
}

ListView Adapter - OnClick to launch a new Activity & OnLongClick to launch a ContextActionBar

Onclick and OnlongClick doesn't work, I am using AppCompatActivity to support KitKat. I am not sure why it's not working. Is it the adapter OR the view? I know I am using deprecated adapter, but I am using it for a purpose.
The code below:
public class MainActivity extends AppCompatActivity {
ActionMode mActionMode;
private CartDbAdapter dba;
private Cursor cursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
databaseview();
}
else {
setContentView(R.layout.cart);
dba = new CartDbAdapter(this);
dba.open();
}
private void databaseview(){
cursor = dba.fetchAllBooks();
ListView listView = (ListView) findViewById(list);
startManagingCursor(cursor);
String [] from = new String[] {BookContract.TITLE , BookContract.AUTHORS };
int [] to = new int [] {android.R.id.text1 , android.R.id.text2 };
SimpleCursorAdapter databaseAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, cursor, from, to);
listView.setAdapter(databaseAdapter);
listView.setOnLongClickListener(longListener);
listView.setOnClickListener(clickListener);
}
View.OnLongClickListener longListener = new View.OnLongClickListener() {
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
mActionMode = MainActivity.this.startSupportActionMode(callback);
view.setSelected(true);
return true;
}
};
View.OnClickListener clickListener = new View.OnClickListener(){
public void onClick(View view) {
Intent viewIntent = new Intent(MainActivity.this, BookActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable(BookActivity.KEY, dba.fetchBook(view.getId()));
viewIntent.putExtras(bundle);
startActivity(viewIntent);
}
};
private ActionMode.Callback callback = new ActionMode.Callback() {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextbar_menu, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
mode.finish();
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
Thank you!
I just solved this issue by using setOnItemClickListener and setOnItemLongClickListener with ListView Adapter..
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(arg0.getContext(), ((TextView)arg1).getText(), Toast.LENGTH_SHORT).show();
return false;
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View itemView, int index,
long id) {
}
});

Issue with setting and opening fragments in Android App

I am having a issue, as my app is crashing instead of opening the fragments. I have a ListActivity, that takes you to another activity; and in that other activity, there are two fragments. The ListActivity is expecting a result from one of the fragments.
My code was working prior to adding the fragments! However the fragments are no longer showing up and the app closes...does anyone possibly know what my issue could be? And any advice on how to take this issue? I sincerely appreciate all and any help, thank you! My code is below.
The ListActivity.java:
public class LyricList extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private LyricsDbAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lyriclist);
mDbHelper = new LyricsDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor lyricsCursor = mDbHelper.fetchAllLyrics();
startManagingCursor(lyricsCursor);
String[] from = new String[]{LyricsDbAdapter.KEY_TITLE};
int[] to = new int[]{R.id.text1};
SimpleCursorAdapter lyrics =
new SimpleCursorAdapter(this, R.layout.lyrics_row, lyricsCursor, from, to);
setListAdapter(lyrics);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createLyric();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteLyric(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createLyric() {
Intent i = new Intent(this, NextActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, NextActivity.class);
i.putExtra(LyricsDbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
}
The other activity class that should be opening via the listActivity:
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab one = actionBar.newTab().setText("Lyric Editor");
Tab two = actionBar.newTab().setText("Loops");
one.setTabListener(new MyTabListener(new LyricEditorFragment()));
two.setTabListener(new MyTabListener(new LoopsFragment()));
actionBar.addTab(one);
actionBar.addTab(two);
}
public class MyTabListener implements TabListener{
Fragment fragment;
public MyTabListener(Fragment f){
fragment = f;
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.replace(R.id.frame1, fragment);
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.remove(fragment);
}
}
}
Not sure if you want to see the fragment class, but here is this just incase:
public class LyricEditorFragment extends Fragment {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private LyricsDbAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new LyricsDbAdapter(getActivity());
mDbHelper.open();
mTitleText = (EditText) getView().findViewById(R.id.title);
mBodyText = (EditText) getView().findViewById(R.id.body);
Button confirmButton = (Button) getView().findViewById(R.id.confirm);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(LyricsDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getActivity().getIntent().getExtras();
mRowId = extras != null ? extras.getLong(LyricsDbAdapter.KEY_ROWID)
: null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor lyric = mDbHelper.fetchLyric(mRowId);
getActivity().startManagingCursor(lyric);
mTitleText.setText(lyric.getString(
lyric.getColumnIndexOrThrow(LyricsDbAdapter.KEY_TITLE)));
mBodyText.setText(lyric.getString(
lyric.getColumnIndexOrThrow(LyricsDbAdapter.KEY_BODY)));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(LyricsDbAdapter.KEY_ROWID, mRowId);
}
#Override
public void onPause() {
super.onPause();
saveState();
}
#Override
public void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createLyric(title, body);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateLyric(mRowId, title, body);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_lyriceditor, container, false);
return view;
}
}
The problem is that you are getting a View from the activity which will return null.. you need to create/inflate the view from the onCreateView..
click here and follow the steps on how to create and use a view from fragment..
Click Here

open a menu in ListActivity with onListItemClick

I'm trying to show a menu once the user longclick an entry in my ListActivity but I cant figure it out. Unfourtenatly lists have been always a hard nut for me to crack and I'm still learning.
package android.GUI;
public class Shifts extends ListActivity implements OnClickListener,
SimpleGestureListener {
private Typeface tf = Entry.tf, tf2 = Entry.tf2;
public static int count = 1;
int dbHourTime = 0;
private SimpleGestureFilter detector;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.shifts);
detector = new SimpleGestureFilter(this, this);
DBAdapter DB = new DBAdapter(this);
DB.open();
Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
count = cursor.getPosition();
int g = count;
cursor.moveToNext();
String[] columns = new String[] { DB.KEY_DATE, DB.KEY_HOURS,
DB.KEY_DAY, DB.KEY_ROWID, DB.KEY_START, DB.KEY_END };
int[] to = new int[] { R.id.dateDisp, R.id.shiftDisp, R.id.day,
R.id.rawId, R.id.start, R.id.finish };
ListView ls = getListView();
TextView SF = (TextView) findViewById(R.id.total);
SF.setTypeface(tf);
TextView sum = (TextView)findViewById(R.id.sum);
sum.setTypeface(tf);
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.list_entry, cursor, columns, to);
this.setListAdapter(mAdapter);
}
#Override
protected void onListItemClick(ListView ls, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(ls, v, position, id);
CharSequence text = "Clicked";
final int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_shifts_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.back:
finish();
return true;
case R.id.clear:
DBAdapter DB = new DBAdapter(this);
DB.open();
DB.deleteAll();
startActivity(getIntent());
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Main.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Entry.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_DOWN:
break;
case SimpleGestureFilter.SWIPE_UP:
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
#Override
public void onListItemClick(ListActivity l, View v, int position, long id) {
// TODO Auto-generated method stub
}
}
This needs to be outside of your onCreate():
#Override // the error is with this method decleration
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(ls, v, position, id);
}
You're creating the onListItemClick method inside the onCreate method. Move it outside the onCreate method :)

Categories

Resources