I am a novice developer. Can someone help me how can I set the image I have the url as the wallpaper title when I click a button? (Kotlin)
You could go through this official documentation for android developers.
Load and display images from the Internet
You need to use WallpaperManager to set the wallpaper, and there's a handy setStream function that takes an InputStream. So instead of having to download the image, you can just open a stream to it, and pass that to WallpaperManager:
button.setOnClickListener {
lifecycleScope.launch(Dispatchers.IO) {
val inputStream = URL("https://cdn2.thecatapi.com/images/oe.jpg").openStream()
WallpaperManager.getInstance(requireContext()).setStream(inputStream)
}
}
Or if you don't want to use coroutines (you should, it's safer since they get cancelled automatically) you could run it in a worker thread
thread(start = true) {
val inputStream = URL("https://cdn2.thecatapi.com/images/oe.jpg").openStream()
WallpaperManager.getInstance(requireContext()).setStream(inputStream)
}
But you need to do one of those things, because you can't do network stuff on the main thread.
You also need the SET_WALLPAPER and INTERNET permissions in your AndroidManifest.xml:
// inside the main <manifest> block
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.INTERNET" />
Related
I am trying to create an application that allows sending any website as data, but when I write the address it does not load in the second activity.
Note: in the manifest I already put this code <uses-permission android: name = "android.permission.INTERNET" />
This is my code
MainActivity
bt_ir.setOnClickListener {
val sitio = pt_sitio.text.toString()
val inten = Intent (this, MainActivity2_Webview::class.java)
inten.putExtra("Clave", sitio)
startActivity(inten)
}
Second Activity
val intent = intent
val name = intent.getStringExtra("Clave")
wv_sitio.loadUrl("http//:${name}")
bt_atras.setOnClickListener {
finish()
}
You have a typo in your URL string after http, it should be :// instead of //:
As well as that, if you're using http instead of https, you might need to set usesCleartextTraffic in the manifest to true - this was the default before API 28, if you target 28+ it defaults to false and you have to explicitly enable it.
There's also a more complex system with a Network security configuration if you want more fine control over which sites are allowed through.
Depending on what's going on in your WebView, you might need use setMixedContentMode to ALWAYS_ALLOW or something - this is a security problem, so using https would be better, but that's up to you!
My main purpose is getting data from soap webservice on my android phone. Actually i implemented webservice references correctly. But i want to try some data from soap webservice on my android phone , i am getting time out exception like this ;
System.Net.WebException: The operation has timed out.
Here is my source code ;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
var service = new LifeService.LifeService();
var result = service.LifeService_getPersons("xxx#gmail.com","12345");
}
After adding some email and number to the LifeService_getPersons method it should return PersonList to me . Nevertheless it return an exception what i mentioned above. I run this service at windows form application and xamarin.android by using an emulator. Service works fine . It returns data correctly. However when i try to use it on my self phone , it is not working. Then i thought it might be some permission problem and added permissions to the Manifest.xml file such as ;
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Unfortunately it doesn't change anything.Please help . thanks.
I want to make a request in my android app when the button is clicked. In Python I could do this like that:
import requests
params = {
'param1':some_string,
'param2':some_int,
'param3':another_string
}
requests.post("https://some.api.com/method/some.method", params=params)
I'd like to do the same in Kotlin when I push the button. I tried tp do this with Fuel and khhtp but didn't succeed much -- app crashed as soon as I pushed the button, responsible for sending request.
UPD: What I used:
AndroidManifest.xml
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
...
build.gradle
dependencies {
...
compile 'com.github.jkcclemens:khttp:0.1.0'
...
}
MainActivity.kt
fun request(){
var message = "message"
var uid = "123456" //I wanted to use it as int, but mapOf didn't allow me
var token = "token"
val payload = mapOf("token" to token, "user_id" to uid, "message" to message)
get("https://some.api.com/method/some.method", params=payload)
val popup = Toast.makeText(this,"Message sent!",Toast.LENGTH_LONG)
popup.show()
}
activity_main.xml
<Button
...
android:onClick="request" />
This is the example with khhtp, the one with Fuel is gone.
UPD2. Part of Logcat output:
You just need to look at the stack trace to find the issue. The code is throwing a NetworkOnMainThreadException. This happens when you try to access the network from within Android's main (often called UI) thread. This question have some good answers about this issue, however instead of trying to use AsyncTask make sure to read the documentation of your chosen network library and see how to make the call on a different thread.
I'm not sure if this is the root of your problem but your request method signature should be:
fun request(view: View)
{
}
As other members answered your code is calling network operation on main thread that's why it is crashing . You can avoid this either by using Kotlin Coroutines or by using methods of Anko Library (Which is officially supported by kotlin to simplify things in android). Here i just give a reference for how to do Async call in Anko.
doAsync {
// Call all operation related to network or other ui blocking operations here.
uiThread {
// perform all ui related operation here
}
}
To do it as Kotlin Coroutines, you can refer this answer:-
Kotlin Coroutines the right way in Android
I found the answer, basically what's happening is that you are not able to run internet connections at main thread, To override, add the following to the class where the user is performing network operations:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Reference (https://www.educative.io/edpresso/how-to-fix-androidosnetworkonmainthreadexception-error)
I'm trying to figure a way to test if <uses-permission android:name="android.permission.INTERNET" /> is set in AndroidManifest.xml, but I can't. Is it possible to do that? Right now I'm using ActivityInstrumentationTestCase2.
I'm trying to learn testing in Android Studio, and I think that testing that certain uses-permission permissions are set is a good idea at the start of testing the application.
This is how I ended up doing it:
Context testContext = getActivity().getContext();
PackageManager pm = testContext.getPackageManager();
expected = PackageManager.PERMISSION_GRANTED;
actual = pm.checkPermission(Manifest.permission.<PERMISSION_YOU_ARE_LOOKING_FOR>, testContext.getPackageName());
assertEquals(expected, actual);
I have a widget which I am trying to use to display information from my app's local database inside of a listview.
I'm using the RemoteViewsService.RemoteViewsFactory interface to load my list's contents. If I run the block of code which reloads the list in the onDataSetChanged method. the app crashes with the following message:
11-01 16:40:39.540: E/ACRA(27175): DataDisplay fatal error : Permission Denial: reading com.datadisplay.content.ContentProviderAdapter uri content://com.datadisplay.provider.internalDB/events from pid=573, uid=10029 requires the provider be exported, or grantUriPermission()
However, this same code run in the class's constructor works just fine. Of course, I need to have this also work in the onDataSetChanged method for updating and stuff.
Here is my provider's entry in the manifest:
<provider android:name="com.datadisplay.content.ContentProviderAdapter"
android:authorities="com.datadisplay.provider.internalDB"
android:exported="true"
android:enabled="true"
android:grantUriPermissions="true">
<grant-uri-permission android:pathPattern="/events/"/>
</provider>
I am both exporting it AND granting Uri permissions like the error message requests, but it still fails. I found this question, where the guy had an issue but eventually removes his custom permissions and it worked. I don't have any custom permissions like that, but still no luck:
Widget with content provider; impossible to use ReadPermission?
If anyone has insight I'd be really grateful, this is getting incredibly frustrating, haha.
This is happening because RemoteViewsFactory is being called from a remote process, and that context is being used for permission enforcement. (The remote caller doesn't have permission to use your provider, so it throws a SecurityException.)
To solve this, you can clear the identity of the remote process, so that permission enforcement is checked against your app instead of against the remote caller. Here's a common pattern you'll find across the platform:
final long token = Binder.clearCallingIdentity();
try {
[perform your query, etc]
} finally {
Binder.restoreCallingIdentity(token);
}
Put this in your onDataSetChanged() method:
Thread thread = new Thread() {
public void run() {
query();
}
};
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
}
Fetch data from the database inside query() method. I do not know why fetching data in a separate thread helps get around this problem, but it works! I got this from one of the Android examples.
If this only happens for 4.2 and not the rest, you need to set the android:exported="true", because the default is changed:
http://developer.android.com/about/versions/android-4.2.html
Content providers are no longer exported by default. That is, the default value for the android:exported attribute is now “false". If it’s important that other apps be able to access your content provider, you must now explicitly set android:exported="true".