I have a problem with viewpager. I created 2 fragment inside viewpager, but when I call again then I get view == null.
paper_adater.java
public class Paper_adapter extends FragmentStatePagerAdapter {
Context context;
public Paper_adapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new Web_fragment();
case 1:
return new Table_fragment();
default:
return null;
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
#Override
public float getPageWidth(int position) {
// TODO Auto-generated method stub
return 0.95f;
}
detail_fragment.java
public class DetailFragment extends Fragment implements OnPageChangeListener {
public static final String TAG = "Detail fragment";
WebView webView;
ViewPager viewPaper;
Paper_adapter paper_adapter;
public static int currentPage;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e(TAG, "on create view");
View view = inflater.inflate(R.layout.detail_fragment, null);
viewPaper = (ViewPager) view.findViewById(R.id.pager);
paper_adapter = new Paper_adapter(getChildFragmentManager());
viewPaper.setAdapter(paper_adapter);
viewPaper.setOnPageChangeListener(this);
return view;
}
public void Draw(String data, int position) {
FragmentManager fm = getFragmentManager();
Fragment fr = paper_adapter.getItem(position);
if (fr instanceof Web_fragment && fr != null) {
((Web_fragment) fr).draw(getActivity(),data);
} else if (fr instanceof Table_fragment && fr != null) {
}
}
}
Web_fragment.java
public class Web_fragment extends Fragment {
public static final String URL = "file:///android_asset/chart/index.html";
private final String TAG = "WEB fragment";
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.webview_fragment, null);
this.webView = (WebView) view.findViewById(R.id.webview);
// webView.clearHistory();
// webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.loadUrl(URL);
return view;
}
public void setValue(Context context) {
// webView = (WebView)getView().findViewById(R.id.webview);
// webView.loadUrl("javascript:setValue()");
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
}
public Boolean draw(Context context, String data) {
if (webView == null) {
// webView.loadUrl("javascript:setValue()");
Toast.makeText(context, "webview null", Toast.LENGTH_SHORT)
.show();
} else {
if (data == null) {
webView = (WebView) getView().findViewById(R.id.webview);
webView.loadUrl("javascript:setValue()");
return false;
} else {
Toast.makeText(context, "data web :" + data, Toast.LENGTH_SHORT)
.show();
webView.loadUrl("javascript:setValue()");
return true;
}
}
return false;
}
When I call Draw() from detail_fragment then I get Web_fragment == null
Related
I want to add an image from device to the app.
I will use solution of David Manpearl at this openImageIntent.
My code looks fine but when I run the app and select the image in the app, but the problem is the onActivityResult when I finish selecting the image. Please see my code and advise me on what I'm doing wrong. Thank for any suggestion.
Update Info: This Fragment is parent of another Fragment it's name "EventFragment" because I have use FragmentTabHost in EventFragment to display EventAdd class fragment and I have MainActivity it's a ActionBarActivity this is a main of activity when application started. When I click EventFragment menu from MainActivity it will go to EventFragment and EventAdd it's here in FragmentTabHost . Let's see the code:
MainActivity:
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
public static String Username;
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent myIntent = getIntent();
Username = myIntent.getStringExtra("username");
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_sectionMain);
break;
case 2:
mTitle = getString(R.string.title_section1);
break;
case 3:
mTitle = getString(R.string.title_section2);
break;
case 4:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static Fragment newInstance(int sectionNumber) {
Fragment fragment = null;
switch(sectionNumber) {
default:
case 1:
fragment = new PlaceholderFragment();
break;
case 2:
fragment = new EventFragment();
break;
case 3:
//Fragment fragment = new MyFragment2();
break;
case 4:
//Fragment fragment = new MyFragment2();
break;
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
}
}
EventFragment:
public class EventFragment extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
mTabHost = null;
}
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment_event);
mTabHost.addTab(mTabHost.newTabSpec("Tab1").setIndicator("รายการแจ้งเหตุ"),
EventListView.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Tab2").setIndicator("แจ้งเรื่องร้องเรียน"),EventAdd.class,null);
return mTabHost;
}
public EventFragment() {
// TODO Auto-generated constructor stub
}
}
EventAdd Class Fragment:
public class EventAdd extends Fragment {
private ArrayList<HashMap<String, String>> EventTypeList = null;
private Spinner spinnerET;
private List<String> spinnerETArray;
private static final int SELECT_PICTURE_REQUEST_CODE = 0;
private ImageView imageView;
private Bitmap photo;
private Uri outputFileUri;
private Button clearbtn;
private Button AEbtn;
private EditText name;
private EditText detail;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_event_add, container, false);
SetGet sl = new SetGet();
EventTypeList = sl.getArrayListET();
spinnerET=(Spinner) rootView.findViewById(R.id.spinnerType);
name = (EditText) rootView.findViewById(R.id.EditTextName);
detail = (EditText) rootView.findViewById(R.id.editTextdetail);
spinnerETArray = new ArrayList<String>();
imageView = (ImageView)rootView.findViewById(R.id.imageView1);
Button photoButton = (Button) rootView.findViewById(R.id.cam_btn);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImageIntent();
}
});
spinnerETArray.add("==เลือกประเภท==");
for (HashMap<String, String> map : EventTypeList){
for (Entry<String, String> mapEntry : map.entrySet())
{
if(mapEntry.getKey() == "event_type_name"){
spinnerETArray.add(mapEntry.getValue());
}
}
}
Log.d("spinnerETArray:",spinnerETArray.toString());
ArrayAdapter<String> adapter =new ArrayAdapter<String>(this.getContext(),android.R.layout.simple_spinner_item, spinnerETArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerET.setAdapter(adapter);
clearbtn = (Button) rootView.findViewById(R.id.Clearbtn);
clearbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clearInput();
}
});
AEbtn = (Button) rootView.findViewById(R.id.AEbtn);
AEbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Mapint = new Intent(getActivity(), MapMarkPointActivity.class);
Mapint.putExtra("name", name.getText().toString());
Mapint.putExtra("detail", detail.getText().toString());
Mapint.putExtra("photo", photo);
String text = spinnerET.getSelectedItem().toString();
Integer typeId = null;
String CurrentText = "";
for (HashMap<String, String> map : EventTypeList){
for (Entry<String, String> mapEntry : map.entrySet())
{
if(mapEntry.getKey() == "event_type_name"){
CurrentText = mapEntry.getValue();
}else if(mapEntry.getKey() == "event_type_id" && CurrentText == text){
String id = mapEntry.getValue();
typeId = Integer.parseInt(id);
}
}
}
Mapint.putExtra("typeId", typeId);
startActivity(Mapint);
}
});
return rootView;
}
protected void clearInput() {
name.setText("");
detail.setText("");
spinnerET.setSelection(0);
photo = null;
imageView.setImageResource(R.drawable.ic_launcher);
}
private void openImageIntent(){
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getContext().getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
try{
Log.d("startActivityForResult:","startActivityForResult");
getParentFragment().startActivityForResult(chooserIntent, SELECT_PICTURE_REQUEST_CODE);
}catch(Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
Log.d("onActivityResult:","onActivityResult");
if (resultCode == Activity.RESULT_OK) {
Log.d("OK:","ok");
if (requestCode == SELECT_PICTURE_REQUEST_CODE) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
Log.d("รูป:",selectedImageUri.toString());
try {
photo = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
Log.d("รูป:",photo.toString());
imageView.setImageBitmap(photo);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
Log.d("Error:",data.toString());
}
}
public EventAdd() {
super();
// TODO Auto-generated constructor stub
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
In your host activity (MainActivity.java) you need to do:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
}
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?
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 stuck with the project trying to make Page Slider between two activities.
All I know that each activity independently works, but when I try to set up PageAdapter for sliding putting:
Also, I write activity in Manifest, initialize all variables from XML in Java, but the problem starts exactly at the moment when I set up onClickListener for my buttons.
LayoutInflater inflater = LayoutInflater.from(this);
List pages = new ArrayList();
View page = inflater.inflate(R.layout.photo, null);
pages.add(page);
page = inflater.inflate(R.layout.cameragrid, null);
pages.add(page);
CameraPagerAdapter pagerAdapter = new CameraPagerAdapter(pages);
ViewPager viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0); //view being shown firstly
setContentView(viewPager);
instead of *setContentView(R.layout.photo);* it's doesn't launch.
What did I missed? Thanks for advance.
First Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
makeAdditionalPageSlide(); //>>> problems started here
initialize();
InputStream is = getResources().openRawResource(R.drawable.dinam);
bmp = BitmapFactory.decodeStream(is);
}
public void makeAdditionalPageSlide(){
LayoutInflater inflater = LayoutInflater.from(this);
List<View> pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.photo, null);
pages.add(page);
page = inflater.inflate(R.layout.cameragrid, null);
pages.add(page);
CameraPagerAdapter pagerAdapter = new CameraPagerAdapter(pages);
ViewPager viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0); //view being shown firstly
setContentView(viewPager);
}
private void initialize() {
// TODO Auto-generated method stub
iv = (ImageView) findViewById (R.id.ivReturnedPic);
ib = (ImageButton) findViewById (R.id.ibTakePic);
b = (Button) findViewById(R.id.bSetWall);
b.setOnClickListener(this);
ib.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.ibTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
PageAdapter:
public class CameraPagerAdapter extends PagerAdapter {
List<View> pages = null;
public CameraPagerAdapter(List<View> pages){
this.pages = pages;
}
#Override
public Object instantiateItem(View collection, int position){
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((View) view);
}
#Override
public int getCount(){
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object){
return view.equals(object);
}
#Override
public void finishUpdate(View arg0){
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1){
}
#Override
public Parcelable saveState(){
return null;
}
#Override
public void startUpdate(View arg0){
}
}
the second Activity:
public class CameraGrid extends Activity implements OnItemClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cameragrid);
GridView gv = (GridView) findViewById(R.id.cameragrid);
CameraImageAdapter ia = new CameraImageAdapter(getApplicationContext());
gv.setAdapter(ia);
//gridview.setOnItemClickListener(this);
gv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0, View iv, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(),CameraImageDetails.class);
i.putExtra("id", position);
startActivity(i);
}
}
My recommendation is to make mainActivity.xml layout with placeholder for ViewPager and setContentView(R.layout.mainActivity)
Things related to content of page view u setup in PageViewAdapter.
Maybe I didn't quite understand logic u tried to do it, but it seems a bit confusing.. :S