Android JSoup Connection Issues - android

Using the guide on JSoup's website I wrote the following code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
Document doc = Jsoup.connect("http://google.com").get();
Elements links = doc.getElementsByTag("a");
for(Element ele : links){
Log.i("Menu", ele.text());
}
} catch (IOException e) {
}
setContentView(R.layout.main);
}
I added the internet permission in my manifest file but it keeps throwing an IOException!

I tested your code and it should work fine... I would imagine your permission was put in the wrong spot. It goes BEFORE your application definition in your manifest:
here are the first few lines of my manifest that runs your code:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">

Related

Sonar Cocos Helper - Setting Up Google Play Game Services on Android Studio

Android Studio 2.3.3 (LATEST)
Cocos2d-x 3.15.1 (LATEST)
I tested on Debug.
It's my first experience with Cocos2d-x Game Engine, I developed an Android Game using Cocos2d-x, all it's fine but when I tried to show the achievements it shows me an error like this :
java.lang.NullPointerException
at sonar.systems.framework.SonarFrameworkFunctions.showAchievements(SonarFrameworkFunctions.java:432)
at org.cocos2dx.lib.Cocos2dxRenderer.nativeTouchesEnd(Native Method)
at org.cocos2dx.lib.Cocos2dxRenderer.handleActionUp(Cocos2dxRenderer.java:129)
at org.cocos2dx.lib.Cocos2dxGLSurfaceView$10.run(Cocos2dxGLSurfaceView.java:311)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1486)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1263)
My Code when I click to show the achievements :
SonarCocosHelper::GooglePlayServices::showAchievements();
When I want To sign In :
java.lang.NullPointerException
at sonar.systems.framework.SonarFrameworkFunctions.isSignedIn(SonarFrameworkFunctions.java:277)
at org.cocos2dx.lib.Cocos2dxRenderer.nativeRender(Native Method)
at org.cocos2dx.lib.Cocos2dxRenderer.onDrawFrame(Cocos2dxRenderer.java:105)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1557)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1263)
My Code for Sign In :
if(!SonarCocosHelper::GooglePlayServices::isSignedIn())
SonarCocosHelper::GooglePlayServices::signIn();
My Manifest File :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ilyo.test"
android:installLocation="auto">
<supports-screens android:anyDensity="true"
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"/>
<uses-feature android:glEsVersion="0x00020000" />
<!-- Basic permission for Internet and don't allow turn of the screen -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:label="#string/app_name"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher">
<!-- Tell Cocos2dxActivity the name of our .so -->
<meta-data android:name="android.app.lib_name"
android:value="MyGame" />
<!-- Required for Google Play Services -->
<meta-data android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name="org.cocos2dx.cpp.AppActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Build Gradle File :
Cocos Helper Frameworks Used :
My Google Play Achievement (I removed the ID from this photo):
I searched already for solutions in relationship with Android Studio but the results are very rare, I don't know what is the solution and what this the reason for this error.
Thank you,
I founded a solution but now I guess it's just a dirty fix, first the problem is in the GooglePlayServices.java and exactly in onStart method : Null pointer Exception because mHelper is Null.
#Override
public void onStart()
{
mHelper.onStart((Activity) ctx);
}
Let us a little further why it generates null, so :
1. SonarFrameworkFunctions.java
when we want to call GooglePlayServices constructor from SonarFrameworkFunctions.java :
//GOOGLE PLAY SERVICES
if (SonarFrameworkSettings.USE_GOOGLE_PLAY_GAME_SERVICES)
{
String packageName = "sonar.systems.frameworks.GooglePlayServices.GooglePlayServices";
googlePlayServices = (InstantiateFramework(packageName) != null) ? InstantiateFramework(packageName) : new Framework();
}
2. Method : InstantiateFramework in SonarFrameworkFunctions.java
public static Framework InstantiateFramework(String packageName)
{
Framework tmp = null;
try
{
tmp = (Framework) Class.forName(packageName).getConstructor().newInstance();
tmp.SetActivity(((SonarFrameworkActivity) app));
} catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
Log.e("Class not found", "class doesn't exist or bad package name " + packageName);
}
return tmp;
}
The constructor is empty so there is only a method called onCreate that instantiate and prepare the mHelper to access to all functionalities of Google Play Services.
Solution (Dirty Fix):
GooglePlayServices.java
public GooglePlayServices()
{
mHelper=getGameHelper();
mHelper.setup(this);
}

Permission issue on runnable android

I'm trying to make a service that will run every 10 seconds to check a queue and if there is some data in the queue upload the given uri (uri of a picture just taken from the app) to a certain url.
I have created something along these lines
public QueueProcessor(final Context context){
this.mContext = context.getApplicationContext();
}
/**
* Starts processing the items on a separate thread.
*/
public void process() {
Runnable running = new Runnable() {
#Override
public void run() {
try{
Log.i(RUN_QP_TAG, "Processing queue");
// more here
isRunning = true;
Queue theQ = Queue.getInstance();
if(theQ.getSize() > 0){
WorkQItem itm = theQ.pop();
if(itm.hasImage()){
pushImageUploadToProcess(itm);
}
}
} catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed(this, 10000);
}
}
};
new Thread(running).start();
}
The pushImageUploadToProcess takes the WorkQItem and tries to upload the image from the item (which is saved as String picUri) by opening the uri and writing the bytes. However I get a permissions denied exception when trying to open the picUri location.
MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image%3A531 from pid=795, uid=10327 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
How can I allow this Thread/Runnable to have access to the URI?
Note I have tried the upload directly from a button event and it does work.
I have the following permissions in the manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
You should implement runtime permission, for that use below code
PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
#Override
public void onGranted() {
// Proceed with initialization
}
#Override
public void onDenied(String permission) {
// Notify the user that you need all of the permissions
}
});
add below dependency in your app gradle
compile 'com.anthonycr.grant:permissions:1.0'
It looks like the actual permission error is not the real issue. The real issue was the way I was choosing and picking the image.
I ended up using https://gist.github.com/Mariovc/f06e70ebe8ca52fbbbe2 this picker and it seemed to work without any issues.
I tweaked this code a little bit to suit my needs as any image picked from the camera needed to be saved too so that if there are several images being done and each is needed for later use the relative uri initially will get overwritten therefore you need a fixed one (e.g: to be saved).

Android query network error -101

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"/>

Suddenly gets android.os.NetworkOnMainThreadException

I have a little app that I made that have worked for months, but suddenly I get a
android.os.NetworkOnMainThreadException
I havent changed any code, this is the line that crashes
try {
endPoint = InetAddress.getByName(target.getToIp());
port = target.getPort();
socket = new DatagramSocket();
}
catch(Exception e) {
}
Note that I'm not sending anything I'm just creating the instances, it breaks already on the InetAddress row.
It wored as late as last night, all I have done on the phone is run update on Google play, it updated to latest version of Google Maps, but that cant have anything todo with it?
It works in the emulator, only my HTC One X that breaks
Full code here
https://github.com/AndersMalmgren/FreePIE/tree/master/Lib/Android/FreePIE%20Android%20IMU
edit:
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.freepie.android.imu"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Tried to move the problem code to the thread instead, now it wont break, but the socket is set to null.
running = true;
worker = new Thread(new Runnable() {
public void run(){
try {
endPoint = InetAddress.getByName(target.getToIp());
port = target.getPort();
socket = new DatagramSocket();
}
catch(Exception e) {
Exception err = e;
}
while(running) {
try {
sync.await();
} catch(Exception e) {}
Send();
}
try {
socket.disconnect();
}
catch(Exception e) {}
}
});
worker.start();
update:
Solution was to add some failback if user types a DNS instead of a IP
https://github.com/AndersMalmgren/FreePIE/commit/e8017e02a7893d9df41e4ed67a037f016b6a7d39
You will get NetworkOnMainThreadException on Android 4.0+ by default if you attempt to do network I/O on the main application thread. getByName() does a DNS lookup if you provide a domain name (instead of dotted-IP notation), and that will trigger NetworkOnMainThreadException.
You must put your code in AsyncTask like this:
new AsyncTask<Void,Void,Void>(){
doInBackground(){
endPoint = InetAddress.getByName(target.getToIp());
port = target.getPort();
socket = new DatagramSocket();
}
}.execute();
Note this code is not a working one, please read more about AsyncTasks here
Use Network on main thread is not allowed from the Android 4.0. If you run the code at Android 2.3 or other, it will not throw any exception.

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

Categories

Resources