0

i am working on a network communication project in android, but my app dose not work ! after some debugging, i find out that every network request has a null response from system.

i tried so many ways such as : 1) hard restart my phone 2) adding all network permissions to the manifest file

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

3) using local network ( my phone as a server ) 4) letting all applications to connect to the network : setting > networked apps > ...

but ! nothing happened...

this is my similar problem link, but there is no answer in this topic: can't connect to internet in ONLY in my android app. Each method to connect internet returns null

network is working on my phone because some apps like telegram and chrome are working well !

and there is a funny thing here, when i copy and past this code to the simple java project not android project, it works well !

because i wanted to find out where is the problem, i just copy 3 simple lines of codes to the simple android project, but still nothing happened!

manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dltests"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

layout file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

source file

package com.example.dltests;

import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView mTextView = (TextView) findViewById(R.id.hello);

        try 
        {
            URL mUrl = new URL("http://192.168.1.53:8080/some.zip");
            HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
            mTextView.setText(mHttpURLConnection.getContentLength());

        } 
        catch (Exception e) 
        {
            mTextView.setText("ERROR: " + e.getMessage());
        }

    }
}

and the result is : ERROR: null

Community
  • 1
  • 1
Mohammad
  • 75
  • 1
  • 11

1 Answers1

0

Android bars you from networking in the UI thread. What you need to do it spawn a separate thread to do the networking for you. Then you need either a receiver or handler to post/update the UI with the data.

1 - Create a new class:

import android.os.Handler;
import android.os.Message;

public class GetData extends Thread
{

    // Holds url that data is stored on
    private URL url

    // Sets the url value
    public GetData(URL newUrl)
    {
         url = newUrl;
    }

    // Runs when the thread is launched
    public void run()
    {
        // Opens connection
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        // Sends back to UI using a Message
        Message msg = MainActivity.MainActivityInterface.obtainMessage(MainActivity.getAndUpdate);
        msg.obj = con.getContentLength(); // Adds the data
        HomeScreen.homeScreenInterface.sendMessage(msg); 
    }
}

2 - Create handler in activity so UI can be updated as well as launch worker thread

import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import android.os.Handler;
import android.os.Message;

public class MainActivity extends Activity {

    // Holds activity instance
    public static MainActivity currentInstance;

    // Variable that allows us to separate messages for handler
    public static final getAndUpdate = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        currentInstance = this;
        TextView mTextView = (TextView) findViewById(R.id.hello);

        try 
        {
            URL mUrl = new URL("http://192.168.1.53:8080/some.zip");

            // Spawns worker thread
            GetData gd = new GetData(mUrl);
            gd.start();
        } 
        catch (Exception e) 
        {
            mTextView.setText("ERROR: " + e.getMessage());
        }
    }

    // Deals with service responses
    public static Handler MainActivityInterface = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch(msg.what)
            {
                case getAndUpdate:
                    currentInstance.mTextView.setText((String) msg.obj); // Gets message object and updates UI
                break;
            }
        }
    }
}

I hope this helps. Note that I have not tested it as I am very far away from my coding computer!