I am a very beginner at AndroidStudio. I opened a new empty project in java language and I just want to show a toast but every time it is showing many errors.
LIKE:
Cannot resolve method 'makeText(com.example.newapp.MainActivity, java.lang.String, int)'
Cannot resolve method 'getActivity' in 'MainActivity'
Cannot resolve method 'getApplicationContext' in 'MainActivity' ETC.
I looked on the internet and tried every method to make a toast in android studio but every time I get errors. I've tried 5 methods but I don't understand why I am getting errors.
Here is the code:
package com.example.newapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;**
public class MainActivity extends AppCompatActivity {
public void startApp(View view)
{
Toast toast1 = Toast.makeText(this, "message", Toast.LENGTH_SHORT);
Toast toast2 = Toast.makeText(MainActivity.this, "message", Toast.LENGTH_SHORT);
Toast.makeText(getActivity(), "message",
Toast.LENGTH_LONG).show();
Toast toast3 = Toast.makeText(getApplicationContext(),"message",Toast. LENGTH_SHORT);
Toast toast4 = Toast.makeText(getActivity().getApplicationContext(),"message",Toast. LENGTH_SHORT);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Replace getActivity() with this in your code.
first of all your code looks ok, but some notes :
first, you create a method but you don't call it anywhere in the
Activity lifecycle method.
Next, when you are in an Activity class that is one of the child of Context class , you don't need to use getActivity(), or any other methods , you can simply pass this or YourActivityClassName.this.
The last thing is that why you have view parameter in method signature when you don't need it?
Delete unused method parameters from method, then replace getActivity() with this or MainActivity.this, at the last call your method in onCreate method by writing your methodName with double parentheses.
Edit:
Don't forget to call the show() method on your Toast yo show it ;)
Related
I am trying to make a simple QR Code scanner and run well if the result shows in the MainActivity. But when I'm trying to generate new Activity as a result, it can't show. Would you like to help me with this problem? Thank you.
Here is the result of the scanner code in the scanner.java:
#Override
public void handleResult(Result rawResult) {
startActivity(new Intent(getApplicationContext(),ResultActivity.class));
ResultActivity.scanText2.setText(rawResult.getText());
onBackPressed();
}
And here is the code of my new Activity for showing the result:
public class ResultActivity extends AppCompatActivity {
public static TextView scanText2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient);
scanText2 = (TextView) findViewById(R.id.scanText2);
}
}
There are a lot of issues with this:
You are launching PatientActivity, not ResultActivity in handleResult()
You are trying to set the value of a TextView in another Activity with this code:
ResultActivity.scanText2.setText(rawResult.getText());
This is an absolute no-no. Pass the data to ResultActivity as an Intent extra when you launch it. You cannot access the views of another Activity like that.
You expect that ResultActivity.scanText2 will contain a reference to a TextView, but at this point it will only contain null. The reason is that it takes some time for ResultActivity to actually start and call its onCreate(). You have not accounted for this timing in your code. To solve this problem, just see (2) above.
Also, you should have gotten a bunch of crashes with useful messages in your logcat. In the future please look there to solve problems and/or post the messages with stacktrace in your Stackoverflow questions.
I'm fairly new to Android, and Javascript. But, I'm actively learning by watching tutorials, and asking questions. Now, I'm trying to code an app that changes certain system values. I know this can only be done by granting my app the WRITE_SECURE_SETTINGS permission. Through my research I've realized I cannot declare the permission in the manifest file itself. Obviously, the only respectable answer is to check if the permission has been granted by the user through ADB. I can't find anything related to this topic and I'm hoping you guys can help me come to a conclusion on how to properly do this. So far this is the code that I have.
package com.datastream.settingschanger;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String requiredPermission = "android.permission.WRITE_SECURE_SETTINGS";
int checkVal = getContext().checkCallingOrSelfPermission(requiredPermission);
if (checkVal == PackageManager.PERMISSION_GRANTED) {
}
Toast.makeText(getActivity(), "WRITE_SECURE_SETTINGS has been granted to the application. You may now continue!",
Toast.LENGTH_LONG).show();
if (checkVal == PackageManager.PERMISSION_DENIED) {
}
Toast.makeText(getActivity(), "WRITE_SECURE_SETTINGS has not been granted to the application. Please grant access to continue.",
Toast.LENGTH_LONG).show();
}
}
But, when ever I run this in Android Studio I get the following errors:
error: cannot find symbol method getContext()
error: cannot find symbol method getActivity()
error: cannot find symbol method getActivity()
Can anyone help me resolves these errors? I have no clue how to fix this. Thank you!
The getContext() and getActivity() method is used in Fragment to get Context
Remove getContext() and getActivity() And use this and MainActivity.this to get Context in your activity
Use this
int checkVal = checkCallingOrSelfPermission(requiredPermission);
instead of this
int checkVal = getContext().checkCallingOrSelfPermission(requiredPermission);
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String requiredPermission = "android.permission.WRITE_SECURE_SETTINGS";
int checkVal = checkCallingOrSelfPermission(requiredPermission);
if (checkVal == PackageManager.PERMISSION_GRANTED) {
}
Toast.makeText(this, "WRITE_SECURE_SETTINGS has been granted to the application. You may now continue!",
Toast.LENGTH_LONG).show();
if (checkVal == PackageManager.PERMISSION_DENIED) {
}
Toast.makeText(this, "WRITE_SECURE_SETTINGS has not been granted to the application. Please grant access to continue.",
Toast.LENGTH_LONG).show();
}
}
I was creating a simple calculator with android. I searched the google and found this fragment of code which worked perfectly for me. But I cannot understand this fragment of the code which was implemented on the onCreate() method. Can someone please explain me this part of code?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "Welcome :)", Toast.LENGTH_SHORT).show();
int[]Btn_Id={ R.id.Btn0, R.id.Btn1, R.id.Btn2, R.id.Btn3,R.id.Btn4, R.id.Btn5, R.id.Btn6, R.id.Btn7, R.id.Btn8, R.id.Btn9, R.id.BtnClear, R.id.BtnDecimal, R.id.BtnDivide, R.id.BtnMultiply, R.id.BtnSubtract, R.id.BtnAdd, R.id.BtnEqual };
for(int i: Btn_Id) {
((Button)findViewById(i)).setOnClickListener(this);
}
}
int[]Btn_Id
it is a array of button which contain id of buttons defined in layout resource file
The below code is used to set ClickListener to all Button in your Btn_Id array
for(int i: Btn_Id) {
((Button)findViewById(i)).setOnClickListener(this);
}
The method onCreate is called when activity starts, its the entry point for the activity.
And activity is empty window, the setContentView is used to fill the resource of id R.layout.activity_main
super.onCreate(savedInstanceState);, you tell the Dalvik VM to run your code in addition to the existing code in the onCreate() of the parent class. If you leave out this line, then only your code is run. The existing code is ignored completely.
R.id.Btn0.... means its defined in resource file and used to show 0 and other buttons. int[]Btn_Id variable holds the resource id of the used buttons.
The following line assigns listener for button click for all the buttons:
for(int i: Btn_Id) {
((Button)findViewById(i)).setOnClickListener(this);
}
Hear is the solution of your problem hope you understand code till
Toast.makeText(this, "Welcome :)", Toast.LENGTH_SHORT).show();
which will create toast message 'welcome' when activity launch.
int[]Btn_Id={ R.id.Btn0, R.id.Btn1, R.id.Btn2, R.id.Btn3,R.id.Btn4, R.id.Btn5, R.id.Btn6, R.id.Btn7, R.id.Btn8, R.id.Btn9, R.id.BtnClear, R.id.BtnDecimal, R.id.BtnDivide, R.id.BtnMultiply, R.id.BtnSubtract, R.id.BtnAdd, R.id.BtnEqual };
Above the Btn_Id is an integer array that will store ID of the all button from btn0 to btnEqual
for(int i: Btn_Id) {
((Button)findViewById(i)).setOnClickListener(this);
}
this function called for each loop. It work like for every int ID in array Btn_Id and assign to int i. and for every i set Button.setOnClickListner(this)\ this is a context.
if you try to find a source code of android calculator then you can get from hear free.
Download Source code:https://www.youtube.com/playlist?list=PLdMmtAIsH0KYiKrdpbzat6t96Nb1_k3_1
I am new to Android and Java. I have constructed an app using HTML/Javascript that is working great.
I now need to create an activity that launches the email client, fills in subject and body, and (the tough part) adds a file attachment. I have not been able to do this from within JavaScript, mailto: will not attach the file.
So I need to accomplish this through Java and execute it from JavaScript. I think this can be done by using addJavaScriptInterface but I cannot find any detailed documentation or examples to go off of.
How could I do this?
Here is what I have so far after reading the documentation:
2nd update to code:
MainActivity.java
public class MainActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty( "splashscreen", R.drawable.splash );
super.loadUrl("file:///android_asset/www/index.html", 1000);
WebView mWebView;
mWebView = (WebView)findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
}
}
JavaScriptInterface.java
public class JavaScriptInterface {
public void doEmail(){
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/html");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT,"test text");
sendIntent.putExtra(Intent.EXTRA_SUBJECT,"test subject");
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://test co.html"));
startActivity(Intent.createChooser(sendIntent, "Send email..."));
}
}
Then I would reference the intent through JavaScript by using Android.doEmail().
With the above code I am getting 2 errors in Eclipse
1. The method startActivity(Intent) is undefined for the type - JavaScriptInterface
2. webview cannot be resolved or is not a field - MainActivity
What am I doing wrong?
This documentation tells you exactly how to do it.
It looks like there are three main steps:
Create your 'interface' class in Android
Add an instance of this 'interface' to the WebView you are using.
Call the interface from your JavaScript.
public class MainActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty( "splashscreen", R.drawable.splash );
JavaScriptInterface jsi = new JavaScriptInterface(this, appView);
appView.addJavascriptInterface(jsi, "Android");
super.loadUrl("file:///android_asset/www/index.html", 1000);
}
}
and
public class JavaScriptInterface {
private WebView mAppView;
private DroidGap mGap
public JavaScriptInterface (DroidGap gap, WebView view)
{
mAppView = view;
mGap = gap;
}
public void doEmail(){
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/html");
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT,"test text");
sendIntent.putExtra(Intent.EXTRA_SUBJECT,"test subject");
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://test co.html"));
startActivity(Intent.createChooser(sendIntent, "Send email..."));
}
}
Using addJavaScriptInterface will extend the DOM inside the embedded browser, and allow JS to access a Java object, which is exactly what you want.
There are too many steps to outline here, that have already been documented. This link has a good overview.
I used WebIntents from Boris Smus (http://smus.com/android-phonegap-plugins) and it works like a charm. You can also peruse his code a little to understand better the approach he took with plugins.
NOTE: you do need to update the code provided as is a little (see comments) and the plugin architecture has changed a little.
How would I call a method from a different activity?
In my main activity, I have a button that shows a dialog to set the difficulty level of the game.
Then you click start game which starts a new activity containing a view with all the game information.
I need to send the difficulty level chosen to the other activity but cannot seem to figure out how to.
You could put it in the extras with the intent:
Intent StartGame = new Intent(this, StartGame.class);
StartGame.putExtra("difficulty", difficultyLevel);
startActivity(StartGame);
Then in your StartGame.class you can retrive it like this(assuming its a string):
Bundle extras = getIntent().getExtras();
if (extras != null) {
String difficulty= extras.getString("difficulty");
}
Well I don't know how sound my solution is but I created a myApplication class which sub classes the Application class .
This holds the reference to the activity I wanted to call
import android.app.Application;
public class myApplication extends Application {
public PostAndViewActivity pv;
}
When the PostAndViewActivity calls the oncreate is sets the pv to point to itself.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((myApplication) getApplication()).pv = this;
Then when I want to call the method I want I just use code like this:
((myApplication) getApplication()).pv.refreshYourself();
Perhaps a bit hacky but it works.....
I welcome some critisism for this ;-)