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();
}
}
Related
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 ;)
I am having trouble with LoaderCallbacks in my project. I have implements LoaderManager in android studio. I am trying to restart the loader whenever search button is press by user.
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>>
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check connection status
checkConnection(cm);
if (isConnected) {
updateQueryUrl(mSearchViewField.getQuery().toString());
restartLoader();
Log.i(LOG_TAG, "Search value: " + mSearchViewField.getQuery().toString());
}else{
// Clear the adapter of previous book data
mAdapter.clear();
// Set mEmptyStateTextView visible
mEmptyStateTextView.setVisibility(View.VISIBLE);
// ...and display message: "No internet connection."
mEmptyStateTextView.setText("No Internet Connection");
}
}
});
But, under restartLoader(), when I try to call getLoaderManager() to restart the loader, it's saying that callback argument is wrong, 3rd argument type. I am not sure what should i use for the callback.
public void restartLoader() {
mEmptyStateTextView.setVisibility(GONE);
progressBar.setVisibility(View.VISIBLE);
getLoaderManager().restartLoader(BOOK_LOADER_ID,null, MainActivity.this);
}
getLoaderManager is deprecated and uses the deprecated framework Loaders.
You should use LoaderManager.getInstance(MainActivity.this) instead, which uses the correct Support Library/AndroidX Loaders, which is probably the LoaderManager.LoaderCallbacks you've imported.
LoaderManager.getInstance(MainActivity.this)
.restartLoader(BOOK_LOADER_ID, null, MainActivity.this);
I've been reading answers, questions, forums and blogs for 2 days now but can't fix my issue.
I've an AngularJS webApp working in a Native (SDK) Android App with a WebView.
Everything seems to work but when my application calls services that responds with the "Set-Cookie" header those cookies are not setted in the webview and, of course are neither sent in the next calls, so my app explodes.
The app works flawlessly in browser and cordova and "document.cookie" returns an empty string, so i know this is where it fails.
My webview is initialized like this:
public class Main extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new mWebViewClient());
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setSavePassword(true);
webview.getSettings().setAllowFileAccessFromFileURLs(true);
webview.getSettings().setAllowContentAccess(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUserAgentString(...);
webview.loadUrl("file:///android_asset/www/index.html");
javascriptAPI = new JavascriptAPI(this);
webview.addJavascriptInterface(javascriptAPI, "jsAPI");
...
}
...
}
I've tried also with chunks of code from here and there like:
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().run();
CookieManager.getInstance().setAcceptCookie(true);
But it doesn't work neither.
My app is calling to some services that use redirect, so fetching the cookies from JS and setting them is not an option, i need the webview to work like a browser would.
This is my first SDK Android App and i'm not sure at all what info could be relevant to answer the question (manifest, jsAPI, etc) so don't hessitate to say and i'll post whatever else is needed
SOLVED
Thank you #Mark, this fixed my code:
(inside Activity onCreate)
...
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.createInstance(this);
}
^^^^^^^
THIS
WebView webview = (WebView) findViewById(R.id.webview);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().run();
CookieManager.getInstance().setAcceptCookie(true);
CookieManager.getInstance().setAcceptFileSchemeCookies(true); <- THIS
CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true); <- THIS
webview.setWebViewClient(new mWebViewClient());
webview.getSettings().setAppCacheEnabled(true);
...
There are three acceptCookie methods you need to worry about, and different behavior across several versions of Android to take into consideration.
1) I noticed your initial url is a file:// url. You may need to call CookieManager.getInstance().setAcceptFileSchemeCookies(true);.
2) In Android Lollipop and greater, you may need to call CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
3) For Android versions < Lollipop, if you want cookies to be persisted (e.g., survive rotation), you have to take some steps to manually manage syncing.
First, to ensure that CookieSyncManager is initialized during application startup by adding it your appplication class' onCreate(), or extend this one.
public class CookieApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.createInstance(this);
}
}
}
Second, you need to setup syncing for pre-lollipop devices, and finally to enable cookies. Here's an example activity that you could extend that sets up all the syncing for pre-Lollipop devices, and provides an enablesCookies(webView) that should turn on all cookie types regardless of Android version (be advised there are security considerations to be made when calling these methods!). Note that all of the CookieManager.getInstance().set*Cookie*() methods must be called after the webView is initialized.
public class AppCompatCookieActivity extends AppCompatActivity {
#Override
public void onResume() {
super.onResume();
// start cookie syncing for pre-lollipop devices
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.getInstance().startSync();
}
}
#Override
public void onPause() {
// stop cookie syncing for pre-lollipop devices
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.getInstance().sync();
}
super.onPause();
}
public final void enableCookies(WebView webView) {
// enable javascript (has security implications!)
webView.getSettings().setJavaScriptEnabled(true);
// enable cookies.
CookieManager.getInstance().setAcceptCookie(true);
// enable fileScheme cookies (has security implications!)
// it is recommended to comment this out should you find it not necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
CookieManager.getInstance().setAcceptFileSchemeCookies(true);
}
// enable third party cookies
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
}
}
}
I know there are lots of quetions regarden onSaveInstanceState but I wasn't able to find an answer to my problem.
I have an activity that extends AppCompatActivity; this activity uses 3 fragments and it has a variable 'int currentStep' to track which fragment is being displayed. In the onSavedInstanceState method I store the currentStep variable in the bundle, and then in onCreate method I restore it.
public class MainActivity extends AppCompatActivity {
private final String CURRENT_STEP_TAG = "current_step";
private int currentStep;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pedido);
if(savedInstanceState == null) {
loadFirstFragment();
} else {
currentStep = savedInstanceState.getInt(CURRENT_STEP_TAG);
if(currentStep == 2){
//Do some stuff...
}
}
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
Log.d("deubg", "--------onsaveinstancestate--------");
outState.putInt(CURRENT_STEP_TAG, currentStep);
super.onSaveInstanceState(outState, outPersistentState);
}
...
}
The thing is that onSavedInstanceState won't get called when screen orentation changes, and according to google documentation, it should. The message "--------onsaveinstancestate--------" doesn't show in the console.
However the Bundle savedInstanceState in the method onCreate is non null after screen rotation, but it doesn't have the int 'currentStep'.
I've tried many things: changed AppCompatActivity for ActionBarActivity, moved the call for super.onSavedInstanceState to different locations, tried to store other variables; but no matter what I do the method doesn't execute.
Also I DO NOT have android:configChanges in my manifest.
My application is being compiled against sdk version 22, buildToolsVersion 22.0.1
Unless your app is running on Lollipop (API21) version of Android or newer, your
public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState);
will NOT be called as it simply does not exist on earlier versions of the platform than 21. To support pre API 21 devices you must, instead of the above, override the following method:
public void onSaveInstanceState (Bundle outState);
This will work on API 21+ as well, so you do not need to override both methods, of course (unless you know you need to deal with PersistableBundle the new one offers).
See docs.
I'm a beginner with Java and Android Studio.
I try to implemet a OnEditorActionListener that listens for when the user presses the Done button in a softkeyboard.
There are many code fragments available, but I dont know where to put the code (onCreate ? Own class...)
While testing some of those code fragments I get an error "Cannot resolve symbol override", see screenshot.
I've found some articles about "cannot resolve symbol xy", but nothing about "override"
So my question is:
Why do I get "Cannot resolve symbol override" here ?
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.frm_main_layout);
//txtMeineZahl.setOnEditorActionListener(new classDoneOnEditorActionListener()); //doesnt work so far..OK for now
EditText txtMeineZahl = (EditText) findViewById(R.id.txtMeineZahl);
txtMeineZahl.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#override ---- ERROR here
public boolean onEditorAction(TextView view, int action,KeyEvent arg2event)
{
if (action == EditorInfo.IME_ACTION_DONE)
{
//view.setFocusable(false);
Toast.makeText(getApplicationContext(),"test",Toast.LENGTH_LONG);
}
return false;
}
});
}
It should be #Override not #override. O must be capital in #Override.