I saw many question related to this one but none solved my problem yet so I apologize if it was duplicated.
I'm creating a contact book. I've created a fragment to display all contacts.
Now what I want to do is to created an imageview (Call Button) to enable calling the contact when clicked.
I keep getting the error (No Activity found to handle Intent { act android.intent.action.CALL }and when I run on my device it crashed although I've added the intent to the manifest.
What am I doing wrong ?
Fragment Class:
public class DetailFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor> {
public interface DetailFragmentListener {
void onContactDeleted();
void onEditContact(Uri contactUri);
}
private static final int CONTACT_LOADER = 0;
private DetailFragmentListener listener; // MainActivity
private Uri contactUri;
private TextView nameTextView;
private TextView phoneTextView;
private TextView emailTextView;
private TextView streetTextView;
private TextView cityTextView;
private TextView stateTextView;
private TextView zipTextView;
private ImageButton callButton; //The image View for the calling
#Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (DetailFragmentListener) context;
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
// called when DetailFragmentListener's view needs to be created
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(true); // this fragment has menu items to display
// get Bundle of arguments then extract the contact's Uri
Bundle arguments = getArguments();
if (arguments != null)
contactUri = arguments.getParcelable(MainActivity.CONTACT_URI);
// inflate DetailFragment's layout
View view =
inflater.inflate(R.layout.fragment_detail, container, false);
// get the EditTexts
nameTextView = (TextView) view.findViewById(R.id.nameTextView);
phoneTextView = (TextView) view.findViewById(R.id.phoneTextView);
emailTextView = (TextView) view.findViewById(R.id.emailTextView);
streetTextView = (TextView) view.findViewById(R.id.streetTextView);
cityTextView = (TextView) view.findViewById(R.id.cityTextView);
stateTextView = (TextView) view.findViewById(R.id.stateTextView);
zipTextView = (TextView) view.findViewById(R.id.zipTextView);
callButton = (ImageButton) view.findViewById(R.id.callButton);/Get the image view
// load the contact
getLoaderManager().initLoader(CONTACT_LOADER, null, this);
addListenerOnButton(view);//Call the Listener
return view;
}
// display this fragment's menu items
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_details_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
listener.onEditContact(contactUri);
return true;
case R.id.action_delete:
deleteContact();
return true;
}
return super.onOptionsItemSelected(item);
}
private void deleteContact() {
confirmDelete.show(getFragmentManager(), "confirm delete");
}
private final DialogFragment confirmDelete =
new DialogFragment() {
#Override
public Dialog onCreateDialog(Bundle bundle) {
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.confirm_title);
builder.setMessage(R.string.confirm_message);
// provide an OK button that simply dismisses the dialog
builder.setPositiveButton(R.string.button_delete,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog, int button) {
getActivity().getContentResolver().delete(
contactUri, null, null);
listener.onContactDeleted(); // notify listener
}
}
);
builder.setNegativeButton(R.string.button_cancel, null);
return builder.create(); // return the AlertDialog
}
};
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader;
switch (id) {
case CONTACT_LOADER:
cursorLoader = new CursorLoader(getActivity(),
contactUri,
null,
null,
null,
null);
break;
default:
cursorLoader = null;
break;
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
// get the column index for each data item
int nameIndex = data.getColumnIndex(Contact.COLUMN_NAME);
int phoneIndex = data.getColumnIndex(Contact.COLUMN_PHONE);
int emailIndex = data.getColumnIndex(Contact.COLUMN_EMAIL);
int streetIndex = data.getColumnIndex(Contact.COLUMN_STREET);
int cityIndex = data.getColumnIndex(Contact.COLUMN_CITY);
int stateIndex = data.getColumnIndex(Contact.COLUMN_STATE);
int zipIndex = data.getColumnIndex(Contact.COLUMN_ZIP);
// fill TextViews with the retrieved data
nameTextView.setText(data.getString(nameIndex));
phoneTextView.setText(data.getString(phoneIndex));
emailTextView.setText(data.getString(emailIndex));
streetTextView.setText(data.getString(streetIndex));
cityTextView.setText(data.getString(cityIndex));
stateTextView.setText(data.getString(stateIndex));
zipTextView.setText(data.getString(zipIndex));
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
/////Add listener to the image view
public void addListenerOnButton(View v) {
callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String phone_number = phoneTextView.getText().toString();//nUHA
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(phone_number));
startActivity(callIntent);
}
});
}
}
This is specifically the part of the on click method
#Override
public void onClick(View arg0) {
String phone_number = phoneTextView.getText().toString();//nUHA
Intent callIntent =new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(phone_number));
startActivity(callIntent);
My main
public class MainActivity extends AppCompatActivity
implements ContactsFragment.ContactsFragmentListener,
DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
public static final String CONTACT_URI = "contact_uri";
private ContactsFragment contactsFragment; // displays contact list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null &&
findViewById(R.id.fragmentContainer) != null) {
// create ContactsFragment
contactsFragment = new ContactsFragment();
// add the fragment to the FrameLayout
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentContainer, contactsFragment);
transaction.commit(); // display ContactsFragment
}
else {
contactsFragment =
(ContactsFragment) getSupportFragmentManager().
findFragmentById(R.id.contactsFragment);
}
}
#Override
public void onContactSelected(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayContact(contactUri, R.id.fragmentContainer);
else { // tablet
getSupportFragmentManager().popBackStack();
displayContact(contactUri, R.id.rightPaneContainer);
}
}
#Override
public void onAddContact() {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, null);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, null);
}
private void displayContact(Uri contactUri, int viewID) {
DetailFragment detailFragment = new DetailFragment();
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
detailFragment.setArguments(arguments);
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, detailFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes DetailFragment to display
}
private void displayAddEditFragment(int viewID, Uri contactUri) {
AddEditFragment addEditFragment = new AddEditFragment();
if (contactUri != null) {
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
addEditFragment.setArguments(arguments);
}
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, addEditFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes AddEditFragment to display
}
#Override
public void onContactDeleted() {
// removes top of back stack
getSupportFragmentManager().popBackStack();
contactsFragment.updateContactList(); // refresh contacts
}
// display the AddEditFragment to edit an existing contact
#Override
public void onEditContact(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, contactUri);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, contactUri);
}
// update GUI after new contact or updated contact saved
#Override
public void onAddEditCompleted(Uri contactUri) {
// removes top of back stack
getSupportFragmentManager().popBackStack();
contactsFragment.updateContactList(); // refresh contacts
if (findViewById(R.id.fragmentContainer) == null) { // tablet
// removes top of back stack
getSupportFragmentManager().popBackStack();
// on tablet, display contact that was just added or edited
displayContact(contactUri, R.id.rightPaneContainer);
}
}
}
My Manifest
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CALL"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<provider
android:name=".data.AddressBookContentProvider"
android:authorities="com.deitel.addressbook.data"
android:enabled="true"
android:exported="false" >
</provider>
</application>
</manifest>
Use
Uri.parse("tel:" + phone_number)
instead of
Uri.parse(phone_number)
Related
I have an Android app with a navigation drawer with menu items.This menu contains entry to multiple fragments. One of the fragments has a listview in it with names of websites. My aim is that whenever a name of website is clicked from that list the link associated with the listview item saved in stringarray in strings.xml file is opened in new fragment with webview which opens the site.
So far I have implemented this code for the fragment with listview
class AtlasListFragment extends android.support.v4.app.ListFragment implements AdapterView.OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.atlas_list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tut_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}}
And the code which launches the fragment from navigation drawer is below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.Fragment fragment = null;
if (id == R.id.home) {
fragment = frag;
else if (id == R.id.settings) {
fragment=new Settings();
} else if (id == R.id.about_us) {
fragment=new AboutUc();
}
else if(id == R.id.atlas){
fragment = new AtlasListFragment();
}
else{
}
if (fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.fragmentview,fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
By this mehod you can open a webview in where you want use WebView layout and use this method in your activity
public void openWebView(String url){
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Hope it works for you
First of all you will need broadcast so you can send your clicked
URL from adapter to your fragment, and in your main fragment when you
receive the url you can use intent or webview
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.hossam";
private static final String UPDATE_LOCATION_METHOD = "updateLocation";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
String url_adapter = arg1.getStringExtra("url_adapter");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url_adapter));
startActivity(i);
break;
default:
break;
}
}
}
}
i hope this helped
Tried many ways, but none works perfectly. I want to get main activity from the fragments set up in a navigation view.
I tried
#Override
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
but it won't function properly. I want it like when I'm in a fragmented activity it returns back to main and while clicking back again it quits (I already did this), help me out with when back pressed get back to main activity
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1000 ;
private static final String TAG = "MainActivity";
private AdView mAdView;
ImageView imageView;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
List<Item> items;
CustomAdapter adapter;
private long backpressedtime;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case PERMISSION_REQUEST_CODE:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this,"Permission Denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str="Click on Wallpaper to set Wallpaper";
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
imageView=(ImageView)findViewById(R.id.imageView);
mDrawerLayout=(DrawerLayout) findViewById(R.id.dl);
mToggle=new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = (NavigationView) findViewById(R.id.Navigation_v);
setupDrawerContent(navigationView);
ActionBar actionBar = getSupportActionBar();
recyclerView =(RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
imageView=(ImageView)findViewById(R.id.imageView);
initItem();
//start service and play music
startService(new Intent(MainActivity.this, SoundService.class));
}
public void toast(View v) {
Toast.makeText(MainActivity.this, "Wallpaper Set", Toast.LENGTH_LONG).show();
}
private void initItem() {
items = new ArrayList<>();
items.add(new Item(0,"Wide","https://images8.alphacoders.com/532/thumb-1920-532407.jpg"));
items.add(new Item(1, "Wide","https://images5.alphacoders.com/394/thumb-1920-394511.jpg"));
items.add(new Item(1,"Wide","https://images5.alphacoders.com/408/thumb-1920-408539.jpg"));
adapter = new CustomAdapter(this,items);
recyclerView.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onDestroy() {
//stop service and stop music
stopService(new Intent(MainActivity.this, SoundService.class));
super.onDestroy();
}
public void selectItemDrawer(MenuItem menuItem){
Fragment myFragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.walkthrough:
fragmentClass = Walkthrough.class;
break;
case R.id.info:
fragmentClass = About.class;
break;
default:
fragmentClass = Walkthrough.class;
}
try {
myFragment = (Fragment) fragmentClass.newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
setTitle(menuItem.getTitle());
mDrawerLayout.closeDrawers();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return true;
}
});
}
#Override
public void onBackPressed() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure you want to exit?");
builder.setCancelable(true);
builder.setNegativeButton("No Stay ;-)", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.setPositiveButton("Yes :'-(", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
Walkthrough.java
public class Walkthrough extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Walkthrough() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Walkthrough.
*/
// TODO: Rename and change types and number of parameters
public static Walkthrough newInstance(String param1, String param2) {
Walkthrough fragment = new Walkthrough();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_walkthrough, container, false);
WebView webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true); //enable javascript
webView.setWebViewClient(new WebViewClient()); //important to open url in your app
webView.loadUrl("http://ign.com/wikis/the-last-of-us/Prologue");
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
If you want to go back to the MainActivity onBack click of WalkthroughFragment then while commit your fragment add it to BackStack using this method:
FragmentTransaction addToBackStack (String name)
This method will do the below operation:
Will Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.
You can use it like that
FragmentTransaction ftx = getFragmentManager().beginTransaction();
ftx.replace(R.id.my_container_frame, fragment);
ftx.addToBackStack(null);
ftx.commit();
Alternatively you include all the function invocations on a single line
getSupportFragmentManager().beginTransaction().replace('Your Fragment Container ID', new 'Fragment Class Name').addToBackStack(null).commit();
Cheers!
I 've added a button to the menu which is suppose to take me from the fragment to the main activity but I don't now how to implement it?
I put a switch statement inside onOptionsItemSelected.
Fragment wehre I will call main activity:
public class DetailFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor> {
//Fragment detailFragment= new Fragment(this);
// callback methods implemented by MainActivity
public interface DetailFragmentListener {
void onContactDeleted(); // called when a contact is deleted
// pass Uri of contact to edit to the DetailFragmentListener
void onEditContact(Uri contactUri);
}
private static final int CONTACT_LOADER = 0; // identifies the Loader
private DetailFragmentListener listener; // MainActivity
private Uri contactUri; // Uri of selected contact
private TextView nameTextView; // displays contact's name
private TextView phoneTextView; // displays contact's phone
private TextView emailTextView; // displays contact's email
private TextView specialtyTextView; // displays contact's
private TextView cityTextView; // displays contact's city
private TextView chargeTextView; // displays contact's state
private TextView noteTextView; // displays contact's zip
private Button callButton; //Nuha
private Button emailButton;
private Button smsButton;
// set DetailFragmentListener when fragment attached
#Override
public void onAttach(Context context) {
super.onAttach(context);
listener = (DetailFragmentListener) context;
}
// remove DetailFragmentListener when fragment detached
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
// called when DetailFragmentListener's view needs to be created
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(true); // this fragment has menu items to display
// get Bundle of arguments then extract the contact's Uri
Bundle arguments = getArguments();
if (arguments != null)
contactUri = arguments.getParcelable(MainActivity.CONTACT_URI);
// inflate DetailFragment's layout
View view =
inflater.inflate(R.layout.fragment_detail, container, false);
// get the EditTexts
nameTextView = (TextView) view.findViewById(R.id.nameTextView);
phoneTextView = (TextView) view.findViewById(R.id.phoneTextView);
emailTextView = (TextView) view.findViewById(R.id.emailTextView);
specialtyTextView = (TextView) view.findViewById(R.id.specialtyTextView);
cityTextView = (TextView) view.findViewById(R.id.cityTextView);
chargeTextView = (TextView) view.findViewById(R.id.chargeTextView);
noteTextView = (TextView) view.findViewById(R.id.noteTextView);
callButton = (Button) view.findViewById(R.id.callbutton);//nuha
emailButton=(Button) view.findViewById(R.id.sendEmailbutton);
smsButton=(Button)view.findViewById(R.id.smsbutton);
// load the contact
getLoaderManager().initLoader(CONTACT_LOADER, null, this);
addListenerOnButton(view);//Nuha buttons
Animation animation = AnimationUtils.loadAnimation(getContext(),R.anim.pop_enter);//Animate details Nuha
nameTextView.startAnimation(animation);
phoneTextView.startAnimation(animation);
emailTextView.startAnimation(animation);
emailButton.startAnimation(animation);
specialtyTextView.startAnimation(animation);
cityTextView.startAnimation(animation);
chargeTextView.startAnimation(animation);
noteTextView.startAnimation(animation);
callButton.startAnimation(animation);
emailButton.startAnimation(animation);//till here
return view;
}
// display this fragment's menu items
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_details_menu, menu);
}
// handle menu item selections
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
listener.onEditContact(contactUri); // pass Uri to listener
return true;
case R.id.action_home:////home button
//What should I put here ??
return true;
case R.id.action_delete:
deleteContact();
return true;
}
return super.onOptionsItemSelected(item);
}
My mainactivity :
public class MainActivity extends AppCompatActivity
implements ContactsFragment.ContactsFragmentListener,
DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
// key for storing a contact's Uri in a Bundle passed to a fragment
public static final String CONTACT_URI = "contact_uri";
private ContactsFragment contactsFragment; // displays contact list
// display ContactsFragment when MainActivity first loads
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// if layout contains fragmentContainer, the phone layout is in use;
// create and display a ContactsFragment
if (savedInstanceState == null &&
findViewById(R.id.fragmentContainer) != null) {
// create ContactsFragment
//Nuha animation
// add the fragment to the FrameLayout
///Nuha try animation
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
contactsFragment = new ContactsFragment();
transaction.replace(R.id.fragmentContainer, contactsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
else {
contactsFragment =
(ContactsFragment) getSupportFragmentManager().
findFragmentById(R.id.contactsFragment);
}
}
// display DetailFragment for selected contact
#Override
public void onContactSelected(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayContact(contactUri, R.id.fragmentContainer);
else { // tablet
// removes top of back stack
getSupportFragmentManager().popBackStack();
displayContact(contactUri, R.id.rightPaneContainer);
}
}
// display AddEditFragment to add a new contact
#Override
public void onAddContact() {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, null);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, null);
}
// display a contact
private void displayContact(Uri contactUri, int viewID) {
DetailFragment detailFragment = new DetailFragment();
// specify contact's Uri as an argument to the DetailFragment
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
detailFragment.setArguments(arguments);
// use a FragmentTransaction to display the DetailFragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, detailFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes DetailFragment to display
}
// display fragment for adding a new or editing an existing contact
private void displayAddEditFragment(int viewID, Uri contactUri) {
AddEditFragment addEditFragment = new AddEditFragment();
// if editing existing contact, provide contactUri as an argument
if (contactUri != null) {
Bundle arguments = new Bundle();
arguments.putParcelable(CONTACT_URI, contactUri);
addEditFragment.setArguments(arguments);
}
// use a FragmentTransaction to display the AddEditFragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, addEditFragment);
transaction.addToBackStack(null);
transaction.commit(); // causes AddEditFragment to display
}
// return to contact list when displayed contact deleted
#Override
public void onContactDeleted() {
// removes top of back stack
getSupportFragmentManager().popBackStack();
contactsFragment.updateContactList(); // refresh contacts
}
// display the AddEditFragment to edit an existing contact
#Override
public void onEditContact(Uri contactUri) {
if (findViewById(R.id.fragmentContainer) != null) // phone
displayAddEditFragment(R.id.fragmentContainer, contactUri);
else // tablet
displayAddEditFragment(R.id.rightPaneContainer, contactUri);
}
// update GUI after new contact or updated contact saved
#Override
public void onAddEditCompleted(Uri contactUri) {
// removes top of back stack
getSupportFragmentManager().popBackStack();
contactsFragment.updateContactList(); // refresh contacts
if (findViewById(R.id.fragmentContainer) == null) { // tablet
// removes top of back stack
getSupportFragmentManager().popBackStack();
// on tablet, display contact that was just added or edited
displayContact(contactUri, R.id.rightPaneContainer);
}
}
//
}
Can you please help ?
Edit: This fragment is associated with the main activity.. I want to return to the main activity with the original fragment.
If I get your question correctly, this is what you need to put in your switch statement,
Intent mainActivityIntent = new Intent(getActivity(),MainActivity.class);
startActivity(mainActivityIntent);
brief explanation of the constructor of Intent
getActivity() returns the activity associated with the fragment.
The activity is a context (since Activity extends Context).
MainActivity.class is the activity you want to return to.
Hope this helps! :)
-After you updated the question-
I think this is what you are looking for How to get a Fragment to remove itself?
Try this.(inside fragment)
Intent intent = new Intent (getApplicationContext(),MainActivity.class);
startActivity(intent);
you have to use this in your itenselected option
Intent intent = new Intent(context, ActivityName.class);
startActivity(intent);
where context is the fragment that you are using , and the next is the activity that you want to go .
I have tried every post in StackOverflow and have not been successful, i have a FragmentTabHost activity with tabs A B C D E
When i go to tab A and then go to tab B everything is ok, but if i return to tab A is blank, then return to tab B is also blank!!
A -> B -> A = Blank -> B = blank
I followed this post to get it working Dynamically changing the fragments inside a fragment tab host?, but the transition between tabs is not working.
I have tried changing my BaseContainerFragment to use getSupportFragmentManager instead of getChildFragmentManager but was unsuccessful, also removing addToBackStack(null) at this point im out of ideas, any help here will be appreciated, thanks.
This is the mainActivity that contain code for creating tabs using fragment.
public class ActivityMain extends FragmentActivity {
public static final String TAB_1_TAG = "tab_1";
public static final String TAB_2_TAG = "tab_2";
public static final String TAB_3_TAG = "tab_3";
public static final String TAB_4_TAG = "tab_4";
public static final String TAB_5_TAG = "tab_5";
private FragmentTabHost mTabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.getTabWidget().setDividerDrawable(null);
mTabHost.getTabWidget().setStripEnabled(false);
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("", getResources().getDrawable(R.drawable.tab_account)), FragmentAccountContainer.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("", getResources().getDrawable(R.drawable.tab_discounts)), FragmentPromotionsContainer.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("", getResources().getDrawable(R.drawable.tab_payment)), FragmentAccountContainer.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("", getResources().getDrawable(R.drawable.tab_gas)), FragmentAccountContainer.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("", getResources().getDrawable(R.drawable.tab_rest)), FragmentAccountContainer.class, null);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
Log.e("ActivityMain", "currentTabTag: " + currentTabTag);
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_3_TAG)) {
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_4_TAG)) {
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_5_TAG)) {
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
}
Log.e("ActivityMain", "isPopFragment: " + isPopFragment);
if (!isPopFragment) {
finish();
}
}
}
This is my BaseContainerFragment that allows backtracking and replacment of fragments
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
This is container for the first Tab (this tab holds 2 activities, one is main, and another is called on listview Click)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPrefs = this.getActivity().getSharedPreferences("getLogin", Context.MODE_PRIVATE);
idUser = myPrefs.getInt("idUser", 0);
d(TAG, "idUser: " + idUser);
/*
Map<String,?> keys = myPrefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Log.d("map values",entry.getKey() + ": " +
entry.getValue().toString());
}
*/
context = getActivity();
pDialog = new SweetAlertDialog(context, PROGRESS_TYPE);
// Check if Internet present
if (!isOnline(context)) {
// Internet Connection is not present
makeText(context, "Error en la conexion de Internet",
LENGTH_LONG).show();
// stop executing code by return
return;
}
new asyncGetFeedClass(context).execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_cardholder, container, false);
toolbar = (Toolbar) v.findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(toolbar_title);
mTitle.setText("TARJETAS");
list = (ListView) v.findViewById(R.id.list);
// Click event for single list row
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
FragmentAccount fragment = new FragmentAccount();
// if U need to pass some data
Bundle bundle = new Bundle();
if (listBalance.get(position).get(TAG_ACCOUNT_BANKACCOUNTS_ID) != null) {
bundle.putString("idBankAccount", listBalance.get(position).get(TAG_ACCOUNT_BANKACCOUNTS_ID));
bundle.putString("idGiftCard", "0");
} else if (listBalance.get(position).get(TAG_ACCOUNT_GIFTCARDS_ID) != null) {
bundle.putString("idGiftCard", listBalance.get(position).get(TAG_ACCOUNT_GIFTCARDS_ID));
bundle.putString("idBankAccount", "0");
} else {
bundle.putString("idBankAccount", "0");
bundle.putString("idGiftCard", "0");
}
fragment.setArguments(bundle);
((BaseContainerFragment) getParentFragment()).replaceFragment(fragment, false);
}
});
return v;
}
The main class for Tab #1
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPrefs = this.getActivity().getSharedPreferences("getLogin", Context.MODE_PRIVATE);
idUser = myPrefs.getInt("idUser", 0);
d(TAG, "idUser: " + idUser);
/*
Map<String,?> keys = myPrefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Log.d("map values",entry.getKey() + ": " +
entry.getValue().toString());
}
*/
context = getActivity();
pDialog = new SweetAlertDialog(context, PROGRESS_TYPE);
// Check if Internet present
if (!isOnline(context)) {
// Internet Connection is not present
makeText(context, "Error en la conexion de Internet",
LENGTH_LONG).show();
// stop executing code by return
return;
}
Bundle bundle = this.getArguments();
idBankAccount = Integer.parseInt(bundle.getString(FragmentCardHolder.TAG_ACCOUNT_BANKACCOUNTS_ID, "0"));
idGiftCard = Integer.parseInt(bundle.getString(FragmentCardHolder.TAG_ACCOUNT_GIFTCARDS_ID, "0"));
if(idBankAccount > 0){
new asyncGetBankTransactions(context).execute();
} else if(idGiftCard > 0) {
new asyncGetGiftCardTransactions(context).execute();
} else {
new asyncGetX111Transactions(context).execute();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_account, container, false);
toolbar = (Toolbar) v.findViewById(id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(toolbar_title);
mTitle.setText("MI CUENTA");
toolbar.setNavigationIcon(R.drawable.icon_user);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToCards();
}
});
layoutAccount = (LinearLayout) v.findViewById(id.layoutAccount);
layoutGetCredit = (LinearLayout) v.findViewById(id.layoutGetCredit);
layoutTransactions = (LinearLayout) v.findViewById(id.layoutTransactions);
btnAccount = (Button) v.findViewById(id.btnMyBalance);
btnGetCredit = (Button) v.findViewById(id.btnGetCredit);
btnSendCredit = (Button) v.findViewById(id.btnSendCredit);
btnTransactions = (Button) v.findViewById(id.btnTransactions);
list = (ListView) v.findViewById(id.list);
btnTransactions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layoutAccount.setVisibility(View.GONE);
layoutGetCredit.setVisibility(View.GONE);
layoutTransactions.setVisibility(View.VISIBLE);
}
});
btnGetCredit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layoutAccount.setVisibility(View.GONE);
layoutGetCredit.setVisibility(View.VISIBLE);
layoutTransactions.setVisibility(View.GONE);
}
});
btnAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layoutAccount.setVisibility(View.VISIBLE);
layoutGetCredit.setVisibility(View.GONE);
layoutTransactions.setVisibility(View.GONE);
}
});
return v;
}
private void goToCards() {
FragmentCardHolder fragment = new FragmentCardHolder();
((BaseContainerFragment) getParentFragment()).replaceFragment(fragment, true);
}
I think the problem is in hidden part of code where you add first fragment to container (FragmentAccountContainer and FragmentPromotionsContainer classes). I suggest you to create abstract method in BaseContainerFragment.class with signature by example
protected abstract Fragment getFirstFragment();
So concrete container class will override this method and return new instance of a first fragment to super class and then in parent class add it to fragment container with using add transaction.
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
addFragment(getFirstFragment(), false);
}
}
Note you should check if savedInstanceState is null before adding fragment to avoid dublicates in case activity recreation by system.
In nested fragments you could use replace like you did it ((BaseContainerFragment) getParentFragment()).replaceFragment(___, true);
Also i have a few suggestions for you code. You couldn't just avoid overriding onBackPressed in activity like #NecipAllef suggests, because of known bug with default back logic and child fragment manager , but you could simplify call to popFragment like
#Override
public void onBackPressed() {
String currentTabTag = mTabHost.getCurrentTabTag();
boolean isPopFragment = ((BaseContainerFragment) getSupportFragmentManager().findFragmentByTag(currentTabTag)).popFragment();
if (!isPopFragment) {
super.onBackPressed();
}
}
And for setting bundles to fragment i suggest use fabric method pattern, like
public class TestFragment extends Fragment {
public static Fragment newInstance(String text){
Fragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putString("text", text);
fragment.setArguments(args);
return fragment;
}
}
Ps: i created for you a simple project with described logic
Why are you keeping track of Fragments and popping them by yourself? You don't need to do that, and you shouldn't override onBackPressed(). Let FragmentManager handle the fragment transactions.
If you have fragments inside an activity, use
FragmentManager fManager = getFragmentManager();
or if you want to support devices prior to Android 3.0, use
FragmentManager fManager = getSupportFragmentManager();
if fragments are inside another fragment, then use
FragmentManager fManager = getChildFragmentManager();
After you have fManager, to show a fragment, use
fManager.beginTransaction().add(R.id.fragment_parent, new FirstTabFragment()).commit();
where fragment_parent is the parent view which you want to place your fragments.
When you want to switch to next fragment, use
fManager.beginTransaction().replace(R.id.fragment_parent, new SecondTabFragment())
.addToBackStack(null)
.commit();
Since you add it to back stack, you will see your first fragment when you press back. That's it.
Moreover, as you can easily realize this will cause your fragments to be created from scratch every time, you can prevent this by initializing them once and reuse them.
HTH
I have a listview in one of my fragments and it empties when I leave that fragment.
Why is it happening?
That fragment:
public class ListActivity extends ListFragment {
public void ToastLoadShout(String msg) {
Toast.makeText(getActivity(), msg.toString(), Toast.LENGTH_LONG).show();
}
private static View View;
HttpClient client;
HttpPost httppost;
HttpGet httpget;
JSONObject json;
List<List<String>> items;
List<item> markers = new ArrayList<item>();
MobileArrayAdapter adapter;
ListView list;
ProgressBar listload;
Button relist;
Preferences pref;
String datadata = "";
String savedlat="0.0";
String savedlon="0.0";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_list, container, false);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
try {
pref = new Preferences(getActivity());
list = (ListView) getView().findViewById(android.R.id.list);
listload = (ProgressBar) getView().findViewById(R.id.listload);
HashMap<String, String> loc = pref.getData();
ToastLoadShout(loc.get(Preferences.LAT) + ","
+ loc.get(Preferences.LON));
if (loc.get(Preferences.LAT) != "0.0" && loc.get(Preferences.LAT) != null)
{
//adapter.deleteList();
//list.destroyDrawingCache();
if (loc.get(Preferences.LAT) != savedlat && loc.get(Preferences.LON)!=savedlon){
new Load().execute();
savedlat=loc.get(Preferences.LAT);
savedlon=loc.get(Preferences.LON);
}
}
else
ToastLoadShout("Get Location First.");
relist = (Button) getView().findViewById(R.id.relist);
relist.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listload.setVisibility(View.INVISIBLE);
HashMap<String, String> loc = pref.getData();
ToastLoadShout(loc.get(Preferences.LAT) + ","
+ loc.get(Preferences.LON));
if (loc.get(Preferences.LAT) != "0.0" && loc.get(Preferences.LAT) != null){
adapter.deleteList();
list.destroyDrawingCache();
new Load().execute();}
else
ToastLoadShout("Get Location First.");
}});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// get selected items
//String selectedValue = (String) getListAdapter().getItem(position);
String selectedValue = markers.get(position).getTitle();
Toast.makeText(getActivity(), selectedValue, Toast.LENGTH_SHORT).show();
}
}
And the MainActivity which holds the fragments:
public class Fragments extends FragmentActivity {
Fragment newFragment;
Button Add;
public void ToastLoadShout(String msg) {
Toast.makeText(this, msg.toString(), Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragments);
//Set Custom actionBar<
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.titlebar);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
//Set Custom actionBar>
ListActivity fragment = new ListActivity();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_place, fragment,"Nearby");
transaction.commit();
turnGPSOn();
Add = (Button)findViewById(R.id.add);
Add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent Intent = new Intent(Fragments.this,Add.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(),
R.anim.animation,R.anim.animation2).toBundle();
startActivity(Intent, bndlanimation);
}
});
/* For putting commas in attractin's checkIns
String number = "1345";
int amount = Integer.parseInt(number);
DecimalFormat formatter = new DecimalFormat("#,###");
ToastLoadShout(formatter.format(amount));*/
}
public void onSelectFragment(View view) {
String fragTag="";
boolean needNew=false;
if (view == findViewById(R.id.map))
{
Fragment f = getSupportFragmentManager().findFragmentByTag("Map");
if (f==null){
newFragment = new MainActivity();
needNew=true;
fragTag="Map";
}
else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_place, f, "Map"); //or whatever other string you want to use
transaction.addToBackStack(null);
transaction.commit();
}
}
else if (view == findViewById(R.id.nearby))
{
Fragment f = getSupportFragmentManager().findFragmentByTag("Nearby");
if (f==null){
newFragment = new ListActivity();
needNew=true;
fragTag="Nearby";
}
else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_place, f, "Nearby"); //or whatever other string you want to use
transaction.addToBackStack(null);
transaction.commit();
}
}
if (needNew) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_place, newFragment, fragTag);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
Already tried loading the list on OnCreate. Doesn't work at all.
Thanks for your assistance.
EDIT:
Load.Class:
class Load extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
listload.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... params) {
try {
items = DownloadList();
if (items != null)
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
#Override
protected void onPostExecute(Boolean res) {
// TODO Auto-generated method stub
if (res) {
ArrangePutMarkers();
adapter=new MobileArrayAdapter(getActivity(), markers);
list.setAdapter(adapter);
} else {
ToastLoadShout("Error");
ToastLoadShout(datadata);
}
listload.setVisibility(View.INVISIBLE);
}
}
As i can see you recreate the loc object every time the fragment is displayed.
It obviously makes you fragment to reload the data.
Keep your adapter in activity as a field. Destroying everything in your fragment when you leave it is a normal thing. setRetainInstance() works only on configuration changes, such as screen rotating. Recreate your list every time you came back in your fragment (in onActivityCreated(), for example, like you do know) and supply it with your stored adapter with saved data in it. You can gain access to your activity inside a fragment, for example, by casting (MainActivity)getActivity(), as an Activity which is passed to this fragment in this case is actually your activity.