2013-07-24 7 views
0
내가 GoogleAPIs에 코드를 넣고 사용

에뮬레이터 그것을 잘 작동,하지만 난 갤럭시 넥서스 에뮬레이터은 충돌과 같은 일에 실행 코드를 사용하는 경우 내 전화기에 왜? 이 코드가 작동하려면 어떻게해야합니까? 제발 나를 안내 해줘. 클래스 :응용 프로그램 충돌

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; 
} 

} 

참고 : GoogleAPIs 에뮬레이터에 잘 작동 getLocationInfo() 방법.

레이아웃 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> 

manifest.xml 파일 :

<?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> 

메신저 새로운 안드로이드합니다. 도와주세요.

답변

2

사용자의 기능 getLocationInfo(...)은 UI 스레드에서 http 통신을 수행하고 있습니다. Android는 UI 스레드에서 네트워크 통신을 허용하지 않습니다. 안드로이드는 그러한 상호 작용을 목적으로하는 AsyncTask (문서 : http://developer.android.com/reference/android/os/AsyncTask.html 참조) 클래스를 제공합니다.

How to fix android.os.NetworkOnMainThreadException?

또는 당신은 또한 스레드를 확장하거나 UI 스레드에 게시물 사용하는 것이 Runnable를 구현하는 사용자 정의 클래스를 만들 수 있습니다 (당신이 원하는 이것은 아마도) 솔루션이 세부 사항에 대한 링크를 하나의 옵션을 참조하십시오 a 핸들러

+0

또는'HandlerThread' 또는'java.util.concurrent' 패키지의 것. –

+0

@Scott 감사합니다. 이 코드에는 API 키가 필요합니까?. 가입 위치? 왜 GoogleAPIs 에뮬레이터를 사용할 때 응용 프로그램이 잘 작동합니까 ?? – Yousif

+0

@Yousif 당신이 앱에서 http 통신에 필요한 유일한 것은 이미 완료 한 mainifest.xml 파일에 인터넷 권한을 설정하는 것입니다. 나는 이것이 에뮬레이터에서 왜 당신에게 효과가 있을지에 대해 당혹 스럽지만, 에뮬레이터에 대한 많은 경험이 없다. 이 모든 것은 셀룰라 기기에서 앱을 실행할 때 모든 네트워킹을 차단해야한다는 것을 확신합니다. – Scott