This is for study and I just want to make sure my answers are 100% right. The question gives me skeleton code and I'm required to fill it in. Here is the code.
public class WebFragment extends WebViewFragment {
private WebView mWebView;
#Override
public void onActivityCreated(Bundle.savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Fill in here
}
public void refreshPage(View view) {
// Fill in here
}
}
Now I am asked three questions. I have put my answers below each question.
a. Instantiate the WebView property in the class
b. When the activity has started, make the WebView component load the url "http://www.google.com/"
#Override
public void onActivityCreated(Bundle.savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mWebView = (WebView) findViewById(R.id.webview); // question a
mWebView.getSettings().setJavaScriptEnabled(true); // question a
mWebView.loadUrl("http://www.google.com"); // question b
}
c. Assuming a button is available in the activity layout and runs refreshPage when pressed, make the function reload the WebView page and show a Toast with the message "Page has been refreshed!"
public void refreshPage(View view) {
mWebView.reload();
Toast toast = Toast.makeText(getApplicationContext(), "Page has been refreshed!"), Toast.LENGTH_SHORT().show();
}
Any feedback is appreciated.
answer a seems ok, for the toast you don't need the variable, unless you don't want to do something other than showing the toast
mWebView.reload();
Toast.makeText(getApllicationContext(),"foo",Toast.LENGTH_SHORT).show();
or pass a custom time in milliseconds
Toast.makeText(getApllicationContext(),"foo",2000).show();
you can also initialize a Toast variable and than call show on it, it works, it's just a useless variable if you're not going to do anything with it but it's not wrong
Toast toast = Toast.makeText(getApplicationContext(),"foo",1000);
toast.show();
oh, I don't know if it's required, but like this refreshPage method is not callable by anybody, maybe you want to set an OnClickListener to the button (that we assume is in the layout) so that refreshPage can be called
((Button)findViewById(R.id.buttonId)).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
refreshPage(v);
}
});
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 2 years ago.
I am a novice Android Developer.
I have created a package-private class which extends Application, and contains the required code for specific functions. I basically want to display if the user-selected button is the correct choice or not, via a toast. Since I have to call this code for many activities, I just created a package-private class for it. However, on clicking the button, the app crashes. Please see the code given below for reference.
I cannot change the onClick method to non-static because if I do that, Android Studio shows an error, and if I change it to static, I am unable to use the method getApplicationContext(), because it is not accessible inside static blocks.
I think that using view.getContext() is causing the crash.
Is there any workaround, or a solution?
Your help would be greatly appreciated. Thanks :)
Here is the code for your reference.
activity.java:
public class activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(functions.select);
functions.makeLayout(expression, buttons);
}
}
Here is the code which crashes the app.
functions.java:
class functions extends Application {
private static int idx;
public static View.OnClickListener select=new View.OnClickListener() {
#Override
public void onClick(View view) {
int selected_index=(int) view.getTag();
if(selected_index==idx)
{
Toast.makeText(view.getContext(), "Correct.", Toast.LENGTH_LONG).show();
((Button) view).setTextColor(Color.GREEN);
}
else
{
Toast.makeText(view.getContext(), "Wrong.", Toast.LENGTH_LONG).show();
((Button) view).setTextColor(Color.RED);
}
}
};
Okay, I figured out that it was not view.getContext() but the line int selected_index=(int) view.getTag(); which was causing the crash. I solved it first making it into a string and then int by using the following code:
String selected_index=view.getTag.toString();
int sidx=Integer.parseInt(selected_index);
I have successfully implemented a custom Dialog box that appears when the user tries to leave an activity via a back button or by using onBackPressed(). They can simply cancel the dialog box or continue, and leave the activity. This function has been implemented in multiple activities, however its making my code a lot longer than it needs to be. I wanted to know how to create a util that can be referenced in different activities, without the need for the chunk of code to copy pasted multiple times. Please note that I am retrieving the dialog title and description from string.xml
This is my code:
Dialog customDialog;
Button button_one, button_two;
TextView dialog_title, dialog_description;
customDialog = new Dialog(this);
//Back button will close app
#Override
public void onBackPressed() {
customDialog.setContentView(R.layout.custom_dialog_box);
dialog_title = customDialog.findViewById(R.id.dialog_title);
dialog_title.setText(getString(R.string.leaving_activity_warning_title));
dialog_description = customDialog.findViewById(R.id.dialog_description); dialog_description.setText(getString(R.string.leaving_activity_warning_description));
button_one = customDialog.findViewById(R.id.button_one);
button_one.setText(getString(R.string.cancel));
button_two = customDialog.findViewById(R.id.button_two);
button_two.setText(getString(R.string.leave_anyway));
button_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
button_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.show();
}
UPDATE
Created a Java file called "DialogBoxMessage"
DialogBoxMessage Code:
class DialogBoxMessage {
private Dialog customDialog;
private TextView dialog_title, dialog_description;
private Button button_one, button_two;
//Custom Dialog Box Initialization
DialogBoxMessage(Button myButtonOne, TextView myDialogTitle, TextView myDialogDescription, Dialog myCustomDialog) {
customDialog = myCustomDialog;
button_one = myButtonOne;
button_two = myButtonOne;
dialog_title = myDialogTitle;
dialog_description = myDialogDescription;
}
void leaveActivity() {
customDialog.setContentView(R.layout.custom_dialog_box);
dialog_title = customDialog.findViewById(R.id.dialog_title);
dialog_title.setText(Resources.getSystem().getString(R.string.leaving_activity_warning_title));
dialog_description = customDialog.findViewById(R.id.dialog_description);
dialog_description.setText(Resources.getSystem().getString(R.string.leaving_activity_warning_description));
button_one = customDialog.findViewById(R.id.button_one);
button_one.setText(Resources.getSystem().getString(R.string.cancel));
button_two = customDialog.findViewById(R.id.button_two);
button_two.setText(Resources.getSystem().getString(R.string.leave_anyway));
button_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
button_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.show();
}
}
I input the following code in another activity
Other activity code:
//Reusable exit dialog message
DialogBoxMessage dialogBoxMessage;
//Back button will close app
#Override
public void onBackPressed() {
dialogBoxMessage.leaveActivity();
finish();
}
But it doesn't seem to work, I think there are a lot of issues... please help :(
I assume customDialog is a seperate class you wrote - therefore i would suggest you put main information like contentview, title, message or type in the constructor when you initialize ur Dialog.
For your onClick Method I suggest you create an Interface to handle Button Clicks in your
customDialog class.
This could be implemented as a static method in a utilities class. The method would require 'this' as a parameter, which contains the activity context. The method should return the result of the button press. The activity can use this response to determine if finish() should be called or not.
UPDATE
I had suggested a simple static method, but you've gone down the object-oriented route. That's fine.
However, your constructor requires passing in several views, which wouldn't appear to achieve the code efficiency you are after.
Your constructor should just require the Activity context; everything else is encapsulated in your new class.
In each Activity's onBackPressed method you will need to create the object with
dialogBoxMessage = new DialogBoxMessage(this);
before you can call any of that object's methods.
my problem is this:
I make a toast "welcome" in the Activity Main for the first time that you open the home, and it's ok,but when another page to return to the home via the back button, how can I make the toast "welcome" does not appear anymore?
the code of main activity is:
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
MyActivity actvi1;
int cont=0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnabout=(Button)findViewById(R.id.about);
//click
btnabout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// definisco l'intenzione di aprire l'Activity "aboutme.java"
Intent aboutmejava= new Intent(MyActivity.this,aboutme.class);
startActivity(aboutmejava);
}
}
);
//toast
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
code of aboutme.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutme);
Button btnback=(Button)findViewById(R.id.scritta);
btnback.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent main = new Intent(aboutme.this,MyActivity.class);
startActivity(main);
If you want it to only show the very first time the application runs, put a boolean flag in SharedPreferences and check here. There are tons of examples but here is one
If you want it to show *every time the Activity is first run when the app starts, simply replace your onClick() code with onBackPressed(). This way it won't start a new instance of your MyActivity and since the Toast code is in onCreate() and not onResume(), it won't run when you go back by clicking the back button.
SharedPreferences
This works.
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
int show = sp.getInt("firstlaunch", 0);
if(show == 0) {
Toast.makeText(getApplicationContext(), "WELCOME", Toast.LENGTH_LONG).show();
sp.edit().putInt("firstlaunch", 1).apply();
}
Place it in your home activities onCreate method.'
A shared preference is a "setting" of sort. It's a xml file that is loaded which contains all of your settings. When we first run "sp.getInt" you can see that i have a 0 after the "key - fistlaunch". The 0 is specifying what to give our Int SHOW if it can't find any shared preference with that key. Next if the int show is equal to 0 we run our Toast and then change the shared preference value to 1 so next time you run it doesn't show...
boolean b = false;
if(!b) {
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
b = true
}
kind of like that?
Are you another instance of MainActivity?
In order to return to your Main activity you should send an Intent with the flag FLAG_ACTIVITY_CLEAR_TOP (or set android:launchMode="singleTop" in launchMode in AndroidManifest.xml)
Intent main = new Intent(aboutme.this,MyActivity.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
By doing so, your main activity will be restored, instead of creating a new instance of MainActivity
I have searched high and low and found so many examples of this, but unable to get it to work, my setup currently is:
Notifier.java
public class Notifier{
Context mContext;
Notifier(Context c) {
mContext = c;
}
#JavascriptInterface
public void showText()
{
Toast.makeText(mContext, "Some text!", Toast.LENGTH_LONG).show();
}
}
SearchLicenseActivity.java
public class SearchLicenseActivity extends Activity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_license);
LoadSearch();
}
public void LoadSearch(){
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Notifier(this), "Android");
webView.loadUrl("javascript:Android.showText();");
}
}
So I am expecting a Toast to show. It may be worth noting that this SearchActivity gets created when a button on a previous Activity is clicked; so I want it to execute LoadSearch straight away and get the Toast from the JavaScript.
I hope one of you out there can cure my woes over this!
Edit: I am also not getting any errors in LogCat.
OK, it turns out webView must have a webpage loaded.
Even if the url is "about:blank" this seems to work. So...
webView.loadUrl("about:blank");
webView.loadUrl("javascript:Android.showText();");
...works.
In my app i have to use same dialog box on all the activities but then on to the click of button on dialog box i need to perform different operations for different activities, i have kept a common code for dialog but then how to call different functions, here is my code:
final Dialog dialog = new Dialog(mContext,R.style.Theme_Levels);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_alert);
TextView title = (TextView)dialog.findViewById(R.id.title);
title.setText("Network Error");
TextView msg = (TextView)dialog.findViewById(R.id.msg_txt);
msg.setText("The system is down, please check after some time ");
ImageView cancel = (ImageView)dialog.findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView continue_btn = (TextView)dialog.findViewById(R.id.continue_btn);
continue_btn.setBackgroundResource(R.drawable.feedback_button_purple);
continue_btn.setText("Retry");
continue_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//TODO perform different operation depending upon from where this function has been called
dialog.dismiss();
}
});
dialog.show();
Create an interface, say DialogActivity, with one method "handlePositiveButton". Let all your Activities implement this interface. From the Dialog.onClick you do this:
DialogActivity activity = (DialogActivity) getActivity();
activity.handlePositiveButton();
Put the code you have specified in a function of a Utils file.
Then pass the positive button onclick listener in that function.
Refer the below code.
public static void showAlertDialog(OnClickListener listener) {
// enter your code here
continue_btn.setOnClickListener(listener);
// more code here
}