0

when i used the code bellow on GoogleAPIs emulator it works fine, but when i used the code to run on Galaxy Nexus emulator it crashes and the same thing on my phone, why? and what i need to get this code works? please guide me. The class:

import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Get_Location_Name extends Activity implements OnClickListener {

private EditText ET1;
private EditText ET2;
private TextView TV1;
private Button B1;
static String result ="";

 double lat=0;
  double lng=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.location_name);
    ET1=(EditText)this.findViewById(R.id.ET1_location_name);
    ET2=(EditText)this.findViewById(R.id.ET2_location_name);
    TV1=(TextView)this.findViewById(R.id.TV1_Location_name);
    B1=(Button)this.findViewById(R.id.B1_Location_name);
    B1.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {

    if(!ET1.getText().toString().isEmpty() && !ET2.getText().toString().isEmpty())
    {

        lng=Double.parseDouble(ET1.getText().toString());
        lat=Double.parseDouble(ET2.getText().toString());
            if(this.isOnline())
            {

                JSONObject ret = getLocationInfo(); 
                JSONObject location;
                String location_string="";
                try {
                    location = ret.getJSONArray("results").getJSONObject(0);
                    location_string = location.getString("formatted_address");
                    Log.d("test", "formattted address:" + location_string);
                } catch (JSONException e1) {
                    e1.printStackTrace();

                }
                TV1.setText(" "+location_string);
            }
            else
                TV1.setText("no internet connection");

    }
    else
        TV1.setText("Enter the Lat. and Lon.");



}

public boolean isOnline() {
    // this method works fine(no problems)
        }


public JSONObject getLocationInfo() {

    HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject;
 }

}

NOTE: the method getLocationInfo() works fine on GoogleAPIs emulator.

The layout location_name.xml:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TableRow
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Longitude"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/ET1_location_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
         >

        <requestFocus />
    </EditText>

</TableRow>



    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="  Latitude"
        android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/ET2_location_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
             />

    </TableRow>

     <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        >

        <Button
            android:id="@+id/B1_Location_name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Get Location Name" />

    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/TV1_Location_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Location Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    </TableRow>



</LinearLayout>

The manifest.xml file:

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

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="14" />

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



<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

             <activity
        android:name="com.example.hellp1_package.MainActivity"
       android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

</manifest>

im new to android. please help me.

1 Answer 1

2

your function getLocationInfo(...) is doing http communication on the UI thread. Android does not allow network communication to be done on the UI thread. Android provides a class called AsyncTask (see documentaion: http://developer.android.com/reference/android/os/AsyncTask.html) that is intended for such interactions. See this link for details and one option for a solution (This is probably what you want):

How to fix android.os.NetworkOnMainThreadException?

or you can also create a custom class that extends Thread or implements Runnable that posts to the UI thread using a Handler

Sign up to request clarification or add additional context in comments.

5 Comments

Or HandlerThread, or something from java.util.concurrent package.
@Scott thank you. Do i need api key for this code?. Where to signup? and why when i used GoogleAPIs emulator the app works fine??
@Yousif the only thing necessary for http communication in you app is to set the internet permission in you mainifest.xml file, which you have already done. I am a bit puzzled as to why this would work for you on the emulator, but I don't have much experience with the emulator. All this being said, I am certain that you must thread off all networking when running an app on an cellular device.
@Scott thank you, now the app workes fine on my phone. i used thread(Runnabe) and post in anther, is that reliable?.if i want to add mapView ill need to signup in google to get api key. where to signup(Link)??? thanx again
for the google maps api key follow the instructions on this link: developers.google.com/maps/documentation/android... A thread and handler implementation is fine for your purposes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.