I have a MainActivity which loads a Fragment in it's oncreate Method and a Dialog to check for User's Input. This Fragment loads a WebView and a ProgressDialog in it's onPageStarted Method. The Problem is, now Those 2 Dialogs are overlapping each other on App start, So the user has to wait for the ProgressDialog (WebView) to finish, before he can access the InputDialog.
Can I access the ProgressDialog from my MainActivity or can I display the Input Dialog after finishing (dismissing) the ProgressDialog from my MainActivity in any way?
MainActivity oncreate:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBar actionBar;
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment FirstFragment = new FirstFragment();
Fragment SecondFragment = new SecondFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String firstrun = preferences.getString("firstrun", null);
String helpread = preferences.getString("helpread", null);
//check for users first time to open the app
//opens the FirstRunActivity if so
if (firstrun == null) {
Intent FirstRunActivity = new Intent(this, FirstRunActivity.class);
startActivity(FirstRunActivity);
}
//check for users first time to open the app
//opens the HelpActivity if so
if (helpread == null) {
new MaterialDialog.Builder(this)
.title("Hilfe Sektion lesen!")
.content("Bitte lies die Hilfe Sektion der App um alle Informationen über die App zu erhalten und Fehler zu vermeiden.")
.positiveText("OK")
.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onPositive(MaterialDialog dialog) {
Intent HelpActivity = new Intent(MainActivity.this, HelpActivity.class);
startActivity(HelpActivity);
}
})
.show();
}
//Replaces/adds the name and the grade of the users preferences to the header of the NavigationDrawer
String name = preferences.getString("name_preference", "");
String grade = preferences.getString("grade_preference", "");
TextView header_username = (TextView) findViewById(R.id.header_username);
TextView header_grade = (TextView) findViewById(R.id.header_grade);
header_username.setText("Name: " + name);
header_grade.setText("Klasse: " + grade);
//initiate the Toolbar/Actionbar and adds the white menu Icon to it
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
//initiates the NavigationDrawer
drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
if (navigationView != null) {
setupNavigationDrawerContent(navigationView);
}
setupNavigationDrawerContent(navigationView);
//initiates the FirstFragment if there is no Saved Instance of the App
if (savedInstanceState == null) {
fragmentTransaction.replace(R.id.main_fragment, FirstFragment);
fragmentTransaction.commit();
}
}
FirstFragment oncreateview:
public class FirstFragment extends Fragment {
private ProgressBar ProgressBar;
private WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Initiate the Fragments Menu
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.first_fragment, container, false);
//Initiates the FloatingActionButton and it's onClickListener
FloatingActionButton button = (FloatingActionButton) view.findViewById(R.id.fab);
button.setOnClickListener(new View.OnClickListener() {
//Reloads the WebView if the User clicks on the FloatingActionButton
#Override
public void onClick(View v) {
webView.reload();
}
});
webView = (WebView) view.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(false);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.setWebViewClient(new WebViewClient() {
ProgressDialog prDialog;
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
new MaterialDialog.Builder(getActivity())
.title("Es ist etwas schief gelaufen :(")
.content("Es gibt ein Problem mit deiner Internetverbindung.\nBitte lade die Seite Neu oder besuche sie zu einem späteren Zeitpunkt nochmal.")
.positiveText("Ok")
.show();
}
//ProgressBar is Visible on a loading Page
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
prDialog = ProgressDialog.show(getActivity(), null, "Wird geladen, bitte warten...");
}
//PrgressBar is not visible on a finished Page and SnackBar with Hint
#Override
public void onPageFinished(WebView view, String url) {
if (prDialog.isShowing()) {
prDialog.dismiss();
}
Snackbar.make(view, "Hinweiß: 'oops...404 Error' bedeuted: \nEs sind aktuell keine Vertretungen für dich vorhanden.", Snackbar.LENGTH_LONG).show();
}
});
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String item = preferences.getString("grade_preference", "");
webView.loadUrl("http://www.kantschule-falkensee.de/uploads/dmiadgspahw/vertretung/Druck_Kla_" + item + ".htm");
return view;
}
Yes,you can define a interface like this:
public interface ProgressDialogDismissListener {
void onProgressDialogDisMiss();
}
You can init a interface,and do what you want in the method "onProgressDialogDisMiss",such as start a input dialog.then transmit the reference of that interface to your fragment
Try making your ProgressDialog globally accessible by making it public static in your MainActivity.
Then you can access your ProgressDialog outside your MainAcitivity by just doing MainActivity.myProgressDialog
Related
Basic info
I am using the Settings Activity and navigation menu : and i have button to display the data (which is the number) from the settings to a textview. It's a sms app
Problem
I have the textview in context_main (The first screen when you start the app) But i would really like to have the textview in my fragment and when i press the button "the onlick" will display the value from settings.
The Button is in the fragment. and when i click the button it works^^ for the context_main se below code.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = prefs.getString("example_text", "");
radertst.setText(restoredText);
}
But when i press a button to send a sms and i linked it with the textfield for where the number is but then i get this.
09-16 20:47:03.501 5389-5389/c.timno.smsgsm20 E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.timno.smsgsm20, PID: 5389
java.lang.NullPointerException
at c.timno.smsgsm20.FirstFragment$1$override.onClick(FirstFragment.java:102)
at c.timno.smsgsm20.FirstFragment$1$override.access$dispatch(FirstFragment.java)
at c.timno.smsgsm20.FirstFragment$1.onClick(FirstFragment.java:0)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18475)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
This my
MainActivity java class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TextView tstnr;
TextView radertst;
EditText nantxt;
Button sendSMSaon;
EditText aonTxt;
TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
nantxt =(EditText) findViewById(R.id.nummer);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The fragment java file
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText numTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
TextView ifirt;
TextView tstnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
numTxt = (EditText)view.findViewById(R.id.nummer);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
tstnr = (TextView) view.findViewById(R.id.numretladd);
msgTxt.setVisibility(View.INVISIBLE);
aonTxt.setVisibility(View.INVISIBLE);
aoffTxt.setVisibility(View.INVISIBLE);
rela1txt.setVisibility(View.INVISIBLE);
rela2txt.setVisibility(View.INVISIBLE);
//testnedan
LayoutInflater lf = getActivity().getLayoutInflater();
view = lf.inflate(R.layout.first_layout, container, false);
//ovantest
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumber = nyanumtxt.getText().toString();
sendMsg(theNumber, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgrela2);
}
}
);
return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
if you look at
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
The numTxt is where i want the value to be loaded and it's in the first layout xml not context_main. So for some reason it wont be loaded there. Imgur image
If I'm understanding you correctly, R.id.raderanumtxt is in the MainActivity's layout file and not FirstFragment's.
That means that it won't be found in the onCreateView() method of FirstFragment the way you're accessing it. The view object there is the layout you just loaded:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt); // <- this assignment won't work
...
}
You're also inflating R.layout.first_layout twice, which is unnecessary.
To get access to a View in the Activity, you can do something like this:
View view = getActivity().findViewById(R.id.viewid);
EDIT:
Without seeing your layouts, I can't be sure, but try and replace:
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt);
... with:
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
That way you're looking for R.id.raderanumtxt in the entire Activity layout. This will only work if the Activity is available and the layout has already been added, so to be safer I'd move this assignment to onViewCreated() instead of onCreateView().
I have this code within onCreate:
webView.setWebViewClient(new WebViewClient() {
final ProgressDialog progress = new ProgressDialog(MainActivity.this);
.
.
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl("file:///android_asset/www/error.html");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.openDrawer(GravityCompat.START);
progress.dismiss();
// onBackPressed(); // this doesn't open the drawer either
}
});
When there is no internet connection it successfully detects the error and loads error.html. However, it refuses to open the drawer. Also, it closes the progress dialog whether I comment out that line or not. And, when I try calling onBackPressed(), it also fails to open the drawer.
The drawer opens and closes fine when the back button is pressed:
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
Why will the drawer not open inside onReceivedError?
Instead of getting the drawer layout reference (drawer) inside onReceivedError, try by declaring the drawer as instance variable and get the reference at onCreate itself.
I tried and able to open & close the drawer, below is the sample.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout)
findViewById(R.id.drawer_layout);
Fragment fragment = new PlanetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,
fragment).commit();
}
public class PlanetFragment extends Fragment {
private WebView webView;
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
this.webView = (WebView)rootView.findViewById(R.id.webview);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl("file:///android_asset/www/error.html");
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
webView.loadUrl("http://www.google.com");
return rootView;
}
}
}
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'm new to programming .
I make an app that contains 3 Tabs with viewpager. 1st tab is a list of Button with their respective link. 2nd Tab is a WebView that will load url passed from the 1st tab when the users clicked on the link. 3rd tab is my Download Manager.
This is my MainActivity:
public class MainActivity extends SherlockFragmentActivity{
ActionBar mActionBar;
Button button;
ViewPager mPager;
Tab tab;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActionBar = getSupportActionBar();
// Hide Actionbar Icon
mActionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
mActionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//For ViewPager
mPager = (ViewPager) findViewById(R.id.pager);
//Activate FragmentManger
FragmentManager fm= getSupportFragmentManager();
ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position){
super.onPageSelected(position);
mActionBar.setSelectedNavigationItem(position);//find the viewPager Potision
}
};
mPager.setOnPageChangeListener(ViewPagerListener);
// Locate the adapter class called ViewPagerAdapter.java
ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fm);
// Set the View Pager Adapter into ViewPager
mPager.setAdapter(viewpageradapter);
// Capture tab button clicks
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Pass the position on tab click to ViewPager
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// Create first Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_home).setTabListener(tabListener);
mActionBar.addTab(tab);
// Create second Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_browse).setTabListener(tabListener);
mActionBar.addTab(tab);
// Create third Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_downloads).setTabListener(tabListener);
mActionBar.addTab(tab);
}
}
My FragmentTab1:
public class FragmentTab1 extends SherlockFragment implements OnClickListener{
FragmentTab2 fTab2;
ViewPager viewPager;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home, container, false);
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
webview = (WebView) view.findViewById(R.id.webView1);
view.findViewById(R.id.Button01).setOnClickListener(this);
view.findViewById(R.id.Button02).setOnClickListener(this);
view.findViewById(R.id.Button03).setOnClickListener(this);
view.findViewById(R.id.Button04).setOnClickListener(this);
view.findViewById(R.id.Button05).setOnClickListener(this);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.Button01:
String urlToBeSend = " http://google.com";
String TabOfFragmentB = ((MainActivity)getActivity()).getTabFragmentB();
FragmentTab2 fragmentB = (FragmentTab2)getActivity().getSupportFragmentManager().findFragmentByTag(TabOfFragmentB);
fragmentB.b_updateText(urlToBeSend);
Toast.makeText(getSherlockActivity(), "url to be send = " +urlToBeSend, Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(1);
break;
case R.id.Button02:
String urlToBeSend2 = " http://facebook.com";
String TabOfFragmentB2 = ((MainActivity)getActivity()).getTabFragmentB();
FragmentTab2 fragmentB2 = (FragmentTab2)getActivity().getSupportFragmentManager().findFragmentByTag(TabOfFragmentB2);
fragmentB2.b_updateText(urlToBeSend2);
Toast.makeText(getSherlockActivity(), "url to be send = " +urlToBeSend2, Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(1);
break;
case R.id.Button03:
viewPager.setCurrentItem(1);
break;
case R.id.Button04:
viewPager.setCurrentItem(1);
break;
case R.id.Button05:
viewPager.setCurrentItem(1);
break;
default:
break;
}
}
}
For My FragmentTab2:
public class FragmentTab2 extends SherlockFragment {
private static WebView webview;
private ProgressBar progress;
String homeUrl="http://new3gpmovies.com/";
private int urlIndex=0;
String a_url;
TextView b_received;
ViewPager viewpager;
public void b_updateText(String t){
b_received.setText(t);
a_url = t;
}
public FragmentTab2(){
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
b_received = (TextView) view.findViewById(R.id.textView1);
ImageView backward = (ImageView) view.findViewById(R.id.backward);
ImageView forward = (ImageView) view.findViewById(R.id.forward);
backward.setOnClickListener(new OnClickListener(){
public void onClick(View view){
if (webview.canGoBack()){
webview.goBack();
}
}
});
forward.setOnClickListener(new OnClickListener(){
public void onClick(View view){
if (webview.canGoForward()){
webview.goForward();
}
}
});
webview = (WebView) view.findViewById(R.id.webView1);
webview.setWebChromeClient(new MyWebChromeClient());
webview.setWebViewClient(new MyWebViewClient());
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
progress = (ProgressBar) view.findViewById(R.id.progressBar1);
progress.setMax(100);
if (a_url != null){
webview.loadUrl(a_url);
}else if (a_url == null){
webview.loadUrl(homeUrl);
}
if (progress.getProgress() == 100){
FragmentTab2.this.progress.setProgress(0);
}
return view;
}
private class MyWebViewClient extends WebViewClient{
#SuppressLint({ "InlinedApi", "NewApi" })
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
boolean value = true;
if (url.endsWith(".3gp") || url.endsWith(".mp4")){
Intent downloadIntent = new Intent("com.nanoidea.download.services.IDownloadService");
downloadIntent.putExtra(MyIntents.TYPE, MyIntents.Types.ADD);
downloadIntent.putExtra(MyIntents.URL, Utils.url[urlIndex]);
getActivity().startService(downloadIntent);
urlIndex++;
if (urlIndex >= Utils.url.length) {
urlIndex = 0;
}
value=false;
}
if(value){
view.loadUrl(url);
}
return value;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
webview.loadUrl("file:///android_asset/failedPage.html");
}
}
public String getFileName(String url) {
String filenameWithoutExtension = "";
if (url.endsWith("3gp")){
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".3gp");
}else if (url.endsWith(".mp4")){
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".mp4");
}
return filenameWithoutExtension;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
private class MyWebChromeClient extends WebChromeClient{
#Override
public void onProgressChanged(WebView view, int newProgress){
FragmentTab2.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress){
this.progress.setProgress(progress);
}
public static boolean canGoBack(){
return webview.canGoBack();
}
public static void goBack(){
webview.goBack();
}
}
Question:
Why when i click on the link from the 1st tab the second tab doesn't change? even if the 2nd tab received the string url from the 1st tab? any idea? Please guide me.
I have an EditText view in my MainActivity that the user can input a url. This MainActivity also contains a fragment which will hold a WebView.
I have it set up so that when the fragment is displayed the url will load in the WebView. However I don't know how I can pass the String to the Fragment?
Below is the Main Activity code:
public class MainActivity extends FragmentActivity {
Button goBtn;
EditText urlInput;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
goBtn = (Button)findViewById(R.id.button1);
urlInput = (EditText)findViewById(R.id.editText1);
goBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
url = "http://"+urlInput.getText().toString(); //THIS TO FRAGMENT!
Toast.makeText(v.getContext(), "Search:" + url, Toast.LENGTH_SHORT).show();
}
});
and this is the fragment code:
WebView webDisplay;
String url;
AsyncHttpClient client;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag1_layout, container, false);
urlDisplay = (TextView)v.findViewById(R.id.textView1);
webDisplay = (WebView)v.findViewById(R.id.webView1);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//url = "http://"+this.getActivity() ???
client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
Toast.makeText(getActivity(), "Success!", Toast.LENGTH_SHORT).show();
webDisplay.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}});
webDisplay.loadUrl(url);
}
});
The value I am concerned about it the String URL variable in MainActivity.java.
The transaction of the fragments is controlled by a class TabFragment.
public class TabFragment extends Fragment {
private static final int TAB1_STATE = 0x1;
private static final int TAB2_STATE = 0x2;
private int mTabState;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab, container, false);
//References to buttons in layout file
Button tabBtn1 = (Button)v.findViewById(R.id.tabBtn1);
Button tabBtn2 = (Button)v.findViewById(R.id.tabBtn2);
//add listener to buttons
tabBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Action to perform when Tab 1 clicked...
goToTab1View();
}
});
tabBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Action to perform when Tab 2 clicked...
goToTab2View();
}
});
return v;
}
//Tab action functions.
protected void goToTab1View() {
if(mTabState != TAB1_STATE){
mTabState = TAB1_STATE;
FragmentManager fm = getFragmentManager();
if(fm!= null){
//Perform fragment transaction
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, new FragTab1());
ft.commit();
}
}
}
protected void goToTab2View() {
if(mTabState != TAB2_STATE){
mTabState = TAB2_STATE;
FragmentManager fm = getFragmentManager();
if(fm!= null){
//Perform fragment transaction
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, new FragTab2());
ft.commit();
}
}
}
Or create Bundle and set it using method fragment.setArguments(myBundle);
This answer is in case the fragment already exists
You can define a public method in your fragment. Something like:
public void setString(final String str) { //... }
After that make your activity to implement OnClickListener interfave. And when the button is pressed just type something like that:
public void onClick(View view) {
// Form url...
((YourWebViewFragment) getFragmentManager().findFragmentById(fragments_id)).setString(url);
}