Android query network error -101 - android

I'm developing Android application, where tries to obtain remote JSON file using aquery. Target Version is Android 4.3 (api ver. 18). Before I was trying to get JSON using tumblr API, but I thought that maybe I'm constructing url wrong way, so I decided to try with easier JSON url, which you can see in code below. What I'm getting all over is Network Error with code -101.
I will be grateful for any tip.
public class WeHaveTheMunchiesActivity extends Activity {
private AQuery mAQ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_viewer);
mAQ=new AQuery(this);
String url="http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";
mAQ.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject json, AjaxStatus status){
Toast.makeText(getApplicationContext(), status.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

I know its too late, but if someone have same problem (status -101) and internet permission are present, but you still got -101 try this
add line in your application tag of your manifest.xml
<uses-library android:name="org.apache.http.legacy" android:required="false"/>

Add this permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.INTERNET"/>

Related

Blazor MAUI - Camera and Microphone Android permissions

I am trying to show live stream from camera & microphone in <video> html element.
In blazor file (sample.razor) I invoke method to request and show video:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("requestMediaAndShow");
}
}
In javascript file (sample.js) I request stream and assign to video html element.
// Create request options
let options = {
audio: true,
video: true
};
// Request user media
navigator.mediaDevices
.getUserMedia(options)
.then(gotLocalStream)
.catch(logError);
But when I am requesting i catch an error like "NotAllowedError: Permission denied".
AndroidManifest.xml contains:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
MainActivity.cs contains:
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.Camera, Manifest.Permission.RecordAudio, Manifest.Permission.ModifyAudioSettings }, 0);
}
}
Any ideas how to request audio and video stream by javascript in BlazorWebView natively on android?
PS. On both on website and natively on Windows platform works great and no extra permissions are required.
Although the Android permissions seem to be granted OK, I suspected the website permissions were not. Not sure if the author of this question is the same person, but an issue was opened on the .NET MAUI repo as well about this.
While we are looking into making this work out of the box, another helpful user has posted this workaround for now.
Implement your own handler like so
public class MauiWebChromeClient : WebChromeClient
{
public override void OnPermissionRequest(PermissionRequest request)
{
request.Grant(request.GetResources());
}
}
public class MauiBlazorWebViewHandler : BlazorWebViewHandler
{
protected override WebChromeClient GetWebChromeClient()
{
return new MauiWebChromeClient();
}
}
And register this handler in your MauiProgram.cs:
builder.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler<IBlazorWebView, MauiBlazorWebViewHandler>();
});
This will automatically grant all the requested permissions from the web side of things.
I think you are missing some parts of the permission checks. You should read this section about runtime permissions that were introduced in Android 6.0. For example, I cannot see any override of OnRequestPermissionsResult in MainActivity.
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/permissions?tabs=macos#runtime-permission-checks-in-android-60

Image not loading through URL in ImageView using Picasso android

I am using the Picasso library to set the image from URL. This URL is working in other programming language but not in Android.
Picasso.with(context).load(product_modal.getImage()).placeholder(R.drawable.ic_no_image).into(holder.iv_thumbnail_filled);
Finally, I found the actual problem that you have faced. Replace https to http in your URL. Because your site does not have SSL.
Just created a method for loading image
private void loadImage(final ImageView imageView, final String imageUrl){
Picasso.get()
.load(imageUrl)
.placeholder(R.drawable.image_white)
.into(imageView , new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
String updatedImageUrl;
if (imageUrl.contains("https")){
updatedImageUrl = imageUrl.replace("https", "http");
}else{
updatedImageUrl = imageUrl.replace("http", "https");
}
loadImage(imageView, updatedImageUrl);
}
});
}
You just need to provide an imageView and the image URL. For the first time if image not loaded then its try to replace https to http and then try load the image.
Using the method by using this:
loadImage(holder.iv_thumbnail_filled, product_modal.getImage());
And make sure you have Internet Access Permission on AndroidMenifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Hope this will solve your problem.
According to Picasso library, they've changed the way of loading images
Please use the below to load image
Picasso.get().load(product_modal.getImage()).placeholder(R.drawable.ic_no_image).into(holder.iv_thumbnail_filled);
You can check this question for more info.
If you have HTTP 504 error, have a try:
Uninstalling the app and installing it again!
Info from here.

Google Tag Manager throws "invalid macro" message

I've been trying out Google Tag Manager for mobile devices, specifically Android but I keep getting a message saying "invalid macro" when trying getString(myKeyValue) on a Container.
Here's a part of my code in my MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtHello = (TextView)findViewById(R.id.txtHello);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String hello = mContainer.getString("hello");
long l = mContainer.getLong("long");
txtHello.setText(hello + l);
}
});
tagManager = TagManager.getInstance(this);
ContainerOpener.openContainer(tagManager, CONTAINER_ID, OpenType.PREFER_NON_DEFAULT, null, new ContainerOpener.Notifier() {
#Override
public void containerAvailable(Container container) {
mContainer = container;
}
});
}
I've added these permissions in the manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
I have the right Container_id because it shows the right version after refreshing it programmatically.
And this is my assets/tagmanager/CONTAINER_ID.json file (of course with the right filename):
{
'hello': 'hola',
'long' : '12345679'
}
So after my container is initialized, I press a button that runs the code above, trying to get the values. But I get the error: "Invalid macro: hello" and "Invalid macro: long", also
"Failed to convert '' to a number"
This is a new service for mobile devices but can anybody help me with this?
I've found a problem for my case. I just downloaded a version from the web browser manager.
The important thing is to add a rule that allows GTM to use this macro. Always comes in handy here.
Don't forget to publish the version of your container
For people not getting what dumazy referring to
you'll also need to enable it with Always or any other appropriate rules
In your json you are using '123456' quotas to define long, you should not:
{
'string': 'hola',
'long': 123456,
'double': 123.123
}
If you have further problems look on: Android TagManager not getting default values

Android Asynchronous Http Client never seems to call back

I am trying to write an Android app that uses com.loopj.android.http.AsyncHttpClient. Although I wrote an Android app some years ago, I am very rusty, so please be gentle with me!
In my app, I do a get, and none of the callback virtual methods are called. To simplify, and make sure it wasn't something about my app, I made a new project based on the SupportAppNavigation project that comes with the SDK. I modified the onCreate code as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("com.trumphurst", "Creating AsyncHttpClient");
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(5000);
Log.i("com.trumphurst", "Getting www.google.com");
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.i("com.trumphurst", "Success");
}
#Override
public void onFailure(Throwable error, String content) {
Log.i("com.trumphurst", "Failure");
}
});
setListAdapter(new SampleAdapter(querySampleActivities()));
}
(Note that this is the only code change I have made to the example application that comes with the SDK.)
I started the app under the debugger, and monitored the logcat output. I saw "Creating AsyncHttpClient" and "Getting www.google.com", then nothing.
I have added some permissions to the manifest - it now starts:
<manifest android:versionCode="1"
android:versionName="1"
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.support.appnavigation">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application android:label="#string/app_name">
<activity android:name=".app.AppNavHomeActivity"
android:label="#string/app_nav_home_label">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Clearly I must be doing something wrong - can anyone put me right?
I think you forget add permission in your AndroidManifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Read more about Manifest file here.
UPDATED:
Here is an example of manifes file from loopj github
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loopj.android.http"
android:versionName="1.4.3"
android:versionCode="1">
<application
android:name="android_async_http">
</application>
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
You can see INTERNET permission here.
Change AsyncHttpResponseHandler()
to TextHttpResponseHandler()
then your Overrides should be:
myClient.get(url, new TextHttpResponseHandler() {
#Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
}
#Override
public void onSuccess(int ii, Header[] headers, String s) {
}
}
Try to also add the onStart and onComplete methods to the callback.
The problem with the AsyncHttpClient is that it wont throw an error if your JSON returned is correctly encoded or not
e.g. I had the same problem as you but noticed that both the onSuccess and onComplete methods were being called but not success or failure. Found it to be the way my server was returning JSON. I was trying to return an associated string array that I created my self and missed the [] infont of the arrayname
Problem: $result = array('result'=>'OK');
Solution: $result[] = array('result'=>'OK');
Not saying yours would be the same syntax problem but it wouldn't hurt to look over what is being returned

Write data to a Text file on URL in Android

I am writing an Android Application in Eclipse in which i need to write some text to a Text file on my webserver. In the onCreate() I am writing something like this..
try{
String data = "hello";
URL u1 = new URL("http://url.com/script.txt");
URLConnection uc1 = u1.openConnection();
uc1.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(uc1.getOutputStream());
out.write(data);
out.flush();
}
catch( Exception e ) {
e.printStackTrace();
}
But its not working. I just need to write a simple text onto an existing Text file on my Web Server. I know its a simple task but I have tried several ways and spent sometime on google trying to do this but not working..Some times I receive errors in yellow:
05-16 16:22:24.853: W/System.err(29095): android.os.NetworkOnMainThreadException
05-16 16:22:25.563: W/System.err(29095): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1108)
...
...
...
I tried writing in Async also:
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
//code comes here.....
}
}
But nothing is working.. i have android.permission.ACCESS_NETWORK_STATE and android.permission.INTERNET enabled in manifest. My folders in server hav write permissions.
Any help is appreciated... Thanks
You cannot access file served by some server like they resources on your file system.
Use HTTP POST with data and have the file writing done by some script engine like PHP.
The use of AsyncTask is required as well.
This is an issue with implementation on your webserver, not Android. One does not simply write over HTTP. You need something like a REST API or a specialized protocol.
Write permissions on the server only mean that the current user on the server has permissions to write to those folders. Outside clients still can only read unless you have something like a PHP script that accepts a POST variable with the text you want to write.

Categories

Resources