Fixing the NetworkOnMainThreadException without using async codes - java

I want to have an application use networking operation on its main thread without it throwing a NetworkOnMainThreadException. I don't want to use async codes to get around this. I heard that you can get around the NetworkOnMainThreadException without using async codes by using this code instead, from this answer link: "How to fix 'android.os.NetworkOnMainThreadException'?"
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
The answer stated that you can use this code in the class and it would ignore the NetworkOnMainThreadException and the code would execute without any problems, but when I tried it in my class I got the "identifier expected" error. What am I doing wrong?
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.EditText;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public class myClass {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
public void connect(View v) throws IOException {
Document doc = Jsoup.connect("http://www.google.com//").get();
}
}
}

Related

The monitor of Android Studio do not show Logs

the monitor of Android Studio do not show Logs.
I have the code:
package com.nv.threadpassdata;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.content.Context;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "START";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "Start");
}
}
And the monitor shows NOTHING:
In settings the Log ticks are ON.
I do not use emulator. Instead of emulator I connect my Phone (HUAWEI MYA-L41)
What is the problem? Can anybody find?
Thanks,
Nickolas
Try to do on of the following:
File>Invalidate Caches and Restart
Build>Clean Project then Build>Rebuild Project

How to fix RecognitionEngine error on android app using API.ai

I've been following some tutorials on how to make an app with API.ai integrated with it. But so far, unlike the tutorials, it gives me an error when I apply the Recognition Engine. This is the code on my Manifest.
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import ai.api.AIConfiguration;
import ai.api.AIListener;
import ai.api.android.AIService;
import ai.api.model.AIError;
import ai.api.model.AIResponse;
import ai.api.model.Result;
import ai.api.ui.AIButton;
public class MainActivity extends AppCompatActivity implements AIListener{
private AIService aiService;
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
AIService aiService;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=findViewById(R.id.textView);
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO);
if (permission != PackageManager.PERMISSION_GRANTED) {
makeRequest();
}
final AIConfiguration config = new AIConfiguration("CLIENT_ACCESS_TOKEN",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, (ai.api.android.AIConfiguration) config);
aiService.setListener(this);
}
This line of code: AIConfiguration.RecognitionEngine.System);
I have all the dependencies that API.ai requests to add to the app gradle.
It says "Cannot resolve the symbol". Does anyone know why this error occurs or how to fix it?
You need to add "import ai.api.android.AIConfiguration;"

Disable screenshots in React Native

I know that you can not 100% stop the user from taking a screenshot if he insists to. But I read that you can still stop manual screenshots by setting LayoutParams.FLAG_SECURE in Java.
I tried adding it to my MainApplication file but getWindow() kept on throwing errors no matter what I do. So I moved that line of code to the MainActivity file and it worked without any errors.
Problem is, I can still normally take screenshots.
MainApplication:
package com.testapp;
import android.app.Activity;
import com.reactnativenavigation.NavigationApplication;
import com.facebook.react.modules.i18nmanager.I18nUtil;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import android.support.annotation.Nullable;
/* custom modules */
import com.oblador.vectoricons.VectorIconsPackage;
import org.pgsqlite.SQLitePluginPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends NavigationApplication {
#Override
public boolean isDebug() {
return BuildConfig.DEBUG;
}
#Nullable
#Override
public List<ReactPackage> createAdditionalReactPackages() {
return Arrays.<ReactPackage>asList(
new SQLitePluginPackage(),
new VectorIconsPackage(),
new RNDeviceInfo()
);
}
#Override
public void onCreate() {
super.onCreate();
I18nUtil sharedI18nUtilInstance = I18nUtil.getInstance();
sharedI18nUtilInstance.allowRTL(getApplicationContext(), false);
}
}
MainActivity:
package com.testapp;
import android.widget.ImageView;
import com.reactnativenavigation.controllers.SplashActivity;
import android.os.Bundle;
import android.view.WindowManager.LayoutParams;
public class MainActivity extends SplashActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
}
}
I did simply the following and it is working properly:
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_main);
}
}

The application ship(process com.example.ship) has stopped unexpectedly. Please try again

I am new for the android apps developing, I have created an sample app with a html design included with it.
when i was trying to install the app it displays
"The application has stopped unexpectedly. Please try again" in the device.
Please help me. Thanks in Advance.
MainActivity.java:
package com.example.ship;
import android.net.ConnectivityManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;
import com.phonegap.*;
public class MainActivity extends DroidGap {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
super.init();
super.loadUrl("ship/assets/www/ship/task.html");
}
}
Try this,
super.loadUrl("file:///android_asset/www/ship/task.html");

Android: Internet works in emulator but not on my phone

I'm making an app which reads a certain part of a website and posts it to the screen. The app currently works in my android emulator but when I transfer it to my galaxy S2, it doesn't seem to access the website at all.
package com.example.beam;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
String current = null;
Button check;
TextView text;
TextView url;
String[] lines = new String[12];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check = (Button) findViewById(R.id.checkstatus);
text = (TextView) findViewById(R.id.textView1);
url = (TextView) findViewById(R.id.url);
String[] lines = new String[12];
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// Attempt to the read the source from a website.
String bodyHtml = "null";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.spring8.or.jp/ext/ja/status/text.html");
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
bodyHtml = httpClient.execute(httpGet, resHandler);
} catch (Exception e) {
e.printStackTrace();
}
double current = 0;
try{
String derp = bodyHtml.substring(bodyHtml.lastIndexOf("mA") - 5, bodyHtml.lastIndexOf("mA"));
current = Double.parseDouble(derp);
}
catch(Exception e){
}
url.setText(current + " mA");
}
});
}
}
Apologies if the coding is a bit poor and messy, I'm quite new to all this. How do I fix this issue? Thank you
Also, I'm pretty sure I've set the permission correctly in the manifest.
Try this....
Its a good practice to Keep the UI work on UI thread and Non-UI work on Non-UI thread, but that became a LAW from the release of HONEYCOMB Android version.... That may be causing the error.
So you can do the following....
Do the Http on a separate thread, and then place the value on the UI using Handler, Handler Keep the reference of the thread in which it was created.
You can use AsyncTask which is specially designed for android to make a sync between
UI and Non-UI thread.
Note:
Please check the Internet Permission in AndroidManifest, though i know you have done it, cause the app ran on the emulator.... but still..no harm in checking it again.

Categories