I am getting a null pointer exception in the following statement :-
MenuSAP = (ShareActionProvider) item.getActionProvider(); in onCreateOptionsMenu(Menu menu) method.
MainActivity.java
public class MainActivity extends Activity {
protected static final int REQUEST_OK = 1;
ListView l1;
ArrayList<Array_songs> songlist;
EditText e1;
Song_adapter adp;
private ShareActionProvider MenuSAP;
ImageButton ib;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
//actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.drawable.iconw);
l1=(ListView)findViewById(R.id.lv1);
ib=(ImageButton)findViewById(R.id.ib1);
songlist=new ArrayList<Array_songs>();
e1= (EditText)findViewById(R.id.editText1);
e1.addTextChangedListener(tw);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
try{
startActivityForResult(i,REQUEST_OK );
}catch(ActivityNotFoundException r){
Toast.makeText(getApplicationContext(),"song cant be played", Toast.LENGTH_SHORT).show();
}
}
});
adp=new Song_adapter(MainActivity.this, songlist, this.getApplication());
l1.setAdapter(adp);
getSongList("");
l1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
int sCB = getVar();
if(sCB == 0) {
Array_songs slist = songlist.get(position);
String Song_Title = slist.get_title();
String Song_Artist = slist.get_artist();
long Song_ID = slist.get_id();
//Toast.makeText(getApplicationContext(), Song_Artist + Song_Title + String.valueOf(Song_ID), Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
Uri song_path = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Song_ID);
Intent musicplayer = new Intent(Intent.ACTION_VIEW);
musicplayer.setDataAndType(song_path, "audio/*");
try {
startActivity(musicplayer);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "Try Again", Toast.LENGTH_SHORT).show();
}
}
else
{
}
}
});
l1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
changeVar();
vibrate();
int select = l1.getSelectedItemPosition();
l1.setItemChecked(select, true);
adp.notifyDataSetChanged();
return false;
}
});
}
private void vibrate() {
Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(120);
}
private void changeVar() {
((SyncClass) this.getApplication()).setShowCheckBox(1);
}
private int getVar()
{
Integer sCB = Integer.parseInt(((SyncClass) this.getApplication()).getShowCheckBox());
return sCB;
}
TextWatcher tw=new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
songlist.clear();
adp.notifyDataSetChanged();
getSongList(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
protected void onActivityResult(int requestcode,int resultcode,Intent data){
super.onActivityResult(requestcode, resultcode, data);
if(requestcode==REQUEST_OK && resultcode==RESULT_OK){
ArrayList<String> ls=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
e1.setText(ls.get(0));
}
}
public void getSongList(String stitle){
ContentResolver cr= getContentResolver();
Uri music=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor mus=cr.query(music, null, null, null, null);
if(mus != null && mus.moveToFirst()){
int titleint=mus.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int artistint= mus.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int songid=mus.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do{
String songTitle=mus.getString(titleint);
String songArtist=mus.getString(artistint);
long songId=mus.getLong(songid);
if(songTitle.toUpperCase().contains(stitle.toUpperCase())){
songlist.add(new Array_songs(songId, songTitle, songArtist));
}
}while(mus.moveToNext());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
MenuSAP = new ShareActionProvider(this);
MenuSAP.setShareIntent(createShareIntent());
MenuSAP = (ShareActionProvider) item.getActionProvider();
return super.onCreateOptionsMenu(menu);
}
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/*");
shareIntent.putExtra(Intent.EXTRA_MIME_TYPES,"audio/*");
return shareIntent;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
int check;
check = getVar();
if(check == 1)
{
((SyncClass) this.getApplication()).setShowCheckBox(0);
adp.notifyDataSetChanged();
}
else
{
super.onBackPressed();
}
}
}
SongAdapter.java
public class Song_adapter extends BaseAdapter {
private ArrayList<Array_songs> song_ob;
private LayoutInflater inflator_ob;
private Application xyz;
//private int sCB = ((SyncClass) this.getApplication()).getSomeVariable();
public Song_adapter(Context c,ArrayList<Array_songs> songlist, Application a)
{
song_ob=songlist;
inflator_ob= LayoutInflater.from(c);
xyz = a;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return song_ob.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
LinearLayout lin_ob =(LinearLayout)inflator_ob.inflate(R.layout.song_content, parent,false) ;
Array_songs ars_ob= song_ob.get(position);
TextView title= (TextView)lin_ob.findViewById(R.id.song_name);
TextView artist= (TextView)lin_ob.findViewById(R.id.artist);
//CheckBox check = (CheckBox) lin_ob.findViewById(R.id.cbselect);
if(((SyncClass) xyz).getShowCheckBox() == "1")
{
lin_ob.findViewById(R.id.cbselect).setVisibility(View.VISIBLE);
}
else
{
lin_ob.findViewById(R.id.cbselect).setVisibility(View.GONE);
}
String stitle= ars_ob.get_title();
String sartist= ars_ob.get_artist();
title.setText(stitle);
artist.setText(sartist);
return lin_ob;
}
}
SyncClass.java
public class SyncClass extends Application {
private String showCheckBox = "0";
public String getShowCheckBox()
{
return showCheckBox;
}
public void setShowCheckBox(int showCheckBox)
{
this.showCheckBox = Integer.toString(showCheckBox);
}
}
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
<item
android:id="#+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="Share"
android:actionProviderClass="android.widget.ShareActionProvider" />
</menu>
Please do help. Am new to android and need help..!!
Instead of using getActionProvider, try to use
MenuItemCompat.setActionProvider(item, menuSAP);
Have a look at this answer for more informations :
why MenuItemCompat.getActionProvider returns null?
Related
Ok, what I'm trying to do is, something like a tag search function.
What I did was create Button ArrayList, and whenever a user tries to input ",", it automatically creates a button and inserts it into the ArrayList, which ultimately registers to the LinearLayout.
It creates well, but does not delete well.
I get the error that the index is out of bounds, but was in no luck of finding out which statement should I use. Could you help me?
Thx in advance.
public class MainActivity extends AppCompatActivity {
private ArrayList<Button> tagCollection = null;
private LinearLayout llTagCollection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tagCollection = new ArrayList<Button>();
initView();
}
#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);
}
public void initView() {
final EditText etSearch = (EditText) findViewById(R.id.ET_SEARCH);
// final TextView tvResult = (TextView) findViewById(R.id.TV_RESULT);
llTagCollection = (LinearLayout) findViewById(R.id.LL_BUTTON_COLLECTION);
View currentView = new View(getApplicationContext());
/*
if(tagCollection.size() != 0) {
tagCollection.get(currentView.getId()).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.get(v.getId()));
Log.e("Removed", String.valueOf(tagCollection.remove(tagCollection.get(v.getId()))));
// tagCollection.remove(this);
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
llTagCollection.addView(tagCollection.get(i));
i += 1;
}
}
});
}
*/
TextWatcher tagWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String convertedCharSequence = s.toString();
Log.e("ConvertedString", convertedCharSequence);
if (convertedCharSequence.length() > 0) {
String subString = convertedCharSequence.substring(convertedCharSequence.length() - 1);
Log.e("SubStringPosition", subString);
if (subString.equals(",")) {
// tvResult.setText(etSearch.getText().toString());
Button bTagButton = new Button(MainActivity.this);
bTagButton.setId(tagCollection.size());
bTagButton.setText(etSearch.getText().toString());
bTagButton.setBackgroundColor(Color.WHITE);
bTagButton.setTextColor(Color.BLACK);
/*
RelativeLayout.LayoutParams rlLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if(tagCollection.size() != 0){
rlLayoutParams.addRule(RelativeLayout.END_OF, tagCollection.get(0).getId());
}
bTagButton.setLayoutParams(rlLayoutParams);
*/
bTagButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.indexOf(this));
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
if(tagCollection.get(i) != null){
llTagCollection.addView(tagCollection.get(i));
}
i += 1;
}
}
});
tagCollection.add(bTagButton);
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
llTagCollection.addView(tagCollection.get(i));
i += 1;
}
// setContentView(rlTagCollection);
etSearch.setText("");
etSearch.setSelection(0);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
etSearch.addTextChangedListener(tagWatcher);
}
}
I solved it using indexOfChild function. It kept on throwing me indexOutOfBounds error. Thx
Because of the reputations, I can not add comment. SO I post here.
In the button click listener:
bTagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.indexOf(this));
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
if (tagCollection.get(i) != null) {
llTagCollection.addView(tagCollection.get(i));
}
i += 1;
}
}
});
You remove the button by tagCollection.remove(tagCollection.indexOf(this));. Here this means the OnClickListener instance, not the button clicked. SO you should remove buttons by:
tagCollection.remove(tagCollection.indexOf(v));
I have a listview implemented with its choice mode set to CHOICE_MODE_MULTIPLE_MODAL. Here is some of the code:
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int check = 0;
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
// TODO Auto-generated method stub
adapter.clearSelection();
}
#Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
check = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, arg1);
return true;
}
#Override
public boolean onActionItemClicked(final ActionMode arg0,
MenuItem arg1) {
// TODO Auto-generated method stub
if ((PinPad.mMediaPlayer != null)
&& (!PinPad.mMediaPlayer.isPlaying())) {
switch (arg1.getItemId()) {
case R.id.item_delete:
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(
R.layout.delete_confirmation, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainListActivity.this);
alertDialogBuilder.setView(dialogLayout);
final AlertDialog confirmationDialog = alertDialogBuilder
.create();
confirmationDialog.show();
Button buttonNo = (Button) dialogLayout
.findViewById(R.id.buttonNo);
Button buttonYes = (Button) dialogLayout
.findViewById(R.id.buttonYes);
buttonNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
weGotTheTime.clear();
weGotTheType.clear();
weGotTheDays.clear();
weGotTheRings.clear();
weGotTheIDs.clear();
confirmationDialog.dismiss();
adapter.clearSelection();
adapter.notifyDataSetChanged();
refreshListView();
check = 0;
arg0.finish();
}
});
buttonYes
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
databaseData.open();
databaseData.deleteEntries(
weGotTheTime, weGotTheType,
weGotTheDays);
databaseData.close();
new AlarmTask(MainListActivity.this,
weGotTheIDs, weGotTheDays,
weGotTheRings, weGotTheType,
weGotTheTime).cancelAl();
weGotTheTime.clear();
weGotTheType.clear();
weGotTheDays.clear();
weGotTheRings.clear();
weGotTheIDs.clear();
confirmationDialog.dismiss();
adapter.clearSelection();
adapter.notifyDataSetChanged();
refreshListView();
check = 0;
arg0.finish();
}
});
break;
}
return true;
} else if (PinPad.mMediaPlayer == null) {
switch (arg1.getItemId()) {
case R.id.item_delete:
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(
R.layout.delete_confirmation, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainListActivity.this);
alertDialogBuilder.setView(dialogLayout);
final AlertDialog confirmationDialog = alertDialogBuilder
.create();
confirmationDialog.show();
Button buttonNo = (Button) dialogLayout
.findViewById(R.id.buttonNo);
Button buttonYes = (Button) dialogLayout
.findViewById(R.id.buttonYes);
buttonNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
weGotTheTime.clear();
weGotTheType.clear();
weGotTheDays.clear();
weGotTheRings.clear();
weGotTheIDs.clear();
confirmationDialog.dismiss();
adapter.clearSelection();
adapter.notifyDataSetChanged();
refreshListView();
check = 0;
arg0.finish();
}
});
buttonYes
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
databaseData.open();
databaseData.deleteEntries(
weGotTheTime, weGotTheType,
weGotTheDays);
databaseData.close();
new AlarmTask(MainListActivity.this,
weGotTheIDs, weGotTheDays,
weGotTheRings, weGotTheType,
weGotTheTime).cancelAl();
weGotTheTime.clear();
weGotTheType.clear();
weGotTheDays.clear();
weGotTheRings.clear();
weGotTheIDs.clear();
confirmationDialog.dismiss();
adapter.clearSelection();
adapter.notifyDataSetChanged();
refreshListView();
check = 0;
arg0.finish();
}
});
break;
}
return true;
} else {
Toast.makeText(
getApplicationContext(),
"Cannot delete alarm(s). Make sure no alarm is currently ringing.",
Toast.LENGTH_SHORT).show();
adapter.clearSelection();
check = 0;
arg0.finish();
return true;
}
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
// TODO Auto-generated method stub
td = results.get(position).getDays();
if (checked) {
check++;
adapter.setNewSelection(position, checked);
weGotTheTime.add(results.get(position).getTime());
weGotTheType.add(results.get(position).getType());
weGotTheDays.add(results.get(position).getDays());
weGotTheIDs.add(results.get(position).getID());
weGotTheRings.add(results.get(position).getTitle());
} else {
check--;
adapter.removeSelection(position);
weGotTheTime.remove(results.get(position).getTime());
weGotTheType.remove(results.get(position).getType());
weGotTheDays.remove(results.get(position).getDays());
weGotTheIDs.remove(results.get(position).getID());
weGotTheRings.remove(results.get(position).getTitle());
}
mode.setTitle(check + " selected");
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
listView.setItemChecked(arg2, !adapter.isPositionChecked(arg2));
vibrator.vibrate(50);
return false;
}
});
This works great, long clicking a listview item highlights it and it works fine. However, once I change the device orientation from portrait to landscape and vice versa, the highlighting is gone and the Contextual Action Bar is still showing however it doesn't show anything is selected. Any help? I've tried making selectors and drawables and manually doing it that way and still no luck. I've spent weeks on this one issue and I'm wondering if somebody out there knows how to solve it.
Thanks.
See if you can using this helps:
android:configChanges="orientation|keyboardHidden"
For more info on complete implementation refer this:
http://developer.android.com/guide/topics/resources/runtime-changes.html
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
I'm trying to make a SingleChoiceItems AlertDialog with an OK and Cancel button which gives the user the option on a onItemLongClick from a ListView to 1.view the user's profile 2.send the user a message and 3.delete the user from the friends list.
I haven't done option 1 and 2 yet but I'm trying to make option 3 right now in which I included the Database delete method and a toast that says "friend removed" but when I select Option 3 and hit ok that row does not get deleted or I see the Toast saying the user was deleted.Here is my code for the Activity I'm using the Dialog.
public class PlayAFriend extends ListActivity {
DBAdapter DBAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_items);
final DBAdapter db = new DBAdapter(this);
DBAdapter = db.open();
ListView FriendLV = (ListView) findViewById(android.R.id.list);
final Cursor friendslist = db.GetAllFriends();
String[] from = new String[] { "FRIENDS" }; // your column/columns here
int[] to = new int[] { R.id.textview_friends };
#SuppressWarnings("deprecation")
ListAdapter cursorAdapter = new SimpleCursorAdapter(this,
R.layout.list_items, friendslist, from, to, 0);
FriendLV.setAdapter(cursorAdapter);
FriendLV.setLongClickable(true);
FriendLV.setOnItemLongClickListener(new OnItemLongClickListener() {
class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c, int flags) {
super(context, friendslist, flags);
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(context);
}
LayoutInflater inflater;
#Override
public void bindView(View view, Context context,
Cursor friendslist) {
// TODO Auto-generated method stub
int row_id = ((com.fullfrontalgames.numberfighter.DBAdapter) friendslist)
.get("_id");
}
#Override
public View newView(Context context, Cursor friendslist,
ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list_items, parent,
false);
bindView(v, context, friendslist);
return v;
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
showDialog(arg2);
return false;
}
});
}
public void OnButtonClick(View view) {
startActivity(new Intent(
"com.fullfrontalgames.numberfighter.Fightattacker"));
}
String[] items = { "View Profile", "Send Message", "Remove Friend" };
#Override
public Dialog onCreateDialog(final int id) {
final DBAdapter db = new DBAdapter(this);
db.open();
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select an Option")
.setSingleChoiceItems(items, id,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
// TODO Auto-generated method stub
}
}
)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
// TODO Auto-generated method stub
if (choice == 0) {
Toast.makeText(getBaseContext(),
"Test", Toast.LENGTH_SHORT)
.show();
} else if (choice == 1) {
Toast.makeText(getBaseContext(),
"Test2", Toast.LENGTH_SHORT)
.show();
} else if (choice == 2) {
Toast.makeText(getBaseContext(),
"Friend Removed",
Toast.LENGTH_SHORT).show();
final TextView friends = (TextView) findViewById(R.id.textview_friends);
String deletedfriend = friends
.getText().toString();
db.DeleteFriends(deletedfriend);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
}
})
.create();
}
return null;
}
#Override
protected void onDestroy() {
super.onDestroy();
// Clear the database
DBAdapter.close();
}
}
You have to save the choice when select a radio button, the other int parameter in the button does not represent the choice.
Make int mChoice; a class member
public class PlayAFriend extends ListActivity {
DBAdapter DBAdapter;
int mChoice;
......
......
#Override
public Dialog onCreateDialog(final int id) {
final DBAdapter db = new DBAdapter(this);
db.open();
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select an Option")
.setSingleChoiceItems(items, id,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
mChoice = choice; // save the choice
}
}
)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
// TODO Auto-generated method stub
if (mChoice == 0) {
Toast.makeText(getBaseContext(),
"Test", Toast.LENGTH_SHORT)
.show();
} else if (mChoice == 1) {
Toast.makeText(getBaseContext(),
"Test2", Toast.LENGTH_SHORT)
.show();
} else if (mChoice == 2) {
Toast.makeText(getBaseContext(),
"Friend Removed",
Toast.LENGTH_SHORT).show();
final TextView friends = (TextView) findViewById(R.id.textview_friends);
String deletedfriend = friends
.getText().toString();
db.DeleteFriends(deletedfriend);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int choice) {
}
})
.create();
}
return null;
}
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 :)