2

我正在导入一个应用程序来捕获塔(移动网络信号名称)。当我运行我的应用程序时,我收到错误,因为不幸的是 Towercapture 已停止。我的java文件

package com.tower;

import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;

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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.widget.TextView;
import android.widget.Toast;

public class Towercap2Activity extends Activity {

double myLatitude, myLongitude;
String rs;
double currentLatitude;
double currentLongitude;
StringBuilder result = new StringBuilder();
Address address ;
String adress;
InputStream is=null;
JSONObject jobj;

JSONArray map_address = null;
String json;
/** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  TextView textGsmCellLocation = (TextView)findViewById(R.id.gsmcelllocation);
  TextView textCID = (TextView)findViewById(R.id.cid);
  TextView textLAC = (TextView)findViewById(R.id.lac);
  TextView textGeo = (TextView)findViewById(R.id.geo);


  TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();

  int cid = cellLocation.getCid();
  int lac = cellLocation.getLac();
  textCID.setText("gsm cell id: " + String.valueOf(cid));
  textLAC.setText("gsm location area_code"+String.valueOf(lac));


  if(RqsLocation(cid, lac)){
          currentLatitude = myLatitude/1000000;
          currentLatitude+=00.002170;
          currentLongitude =myLongitude/1000000;
          currentLongitude+=00.013348;
          String url ="http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address="+currentLatitude+"+"+currentLongitude;

          try
        {
             HttpClient httpclient = new DefaultHttpClient();
               HttpPost httppost = new HttpPost(url);
               HttpResponse response = httpclient.execute(httppost);
               HttpEntity entity = response.getEntity();
                is = entity.getContent();
        } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
        } catch (ClientProtocolException e) {
             e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) 
            {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();

        } catch (Exception e) {
        Toast.makeText(getBaseContext(), "Buffer Error"+"Error converting result"+e.toString(), Toast.LENGTH_LONG).show();
        }


        try {
            jobj = new JSONObject(json);
            map_address = jobj.getJSONArray("results");
            for(int i = 0; i < map_address.length(); i++)
                {
                   JSONObject c = map_address.getJSONObject(i);
                    adress = c.getString("formatted_address");
                }

        } catch (JSONException e)
            {
            Toast.makeText(getBaseContext(), "JSON Parser"+"Error parsing data"+e.toString(), Toast.LENGTH_LONG).show();
            }
           textGeo.setText(adress);





  }else{
   textGeo.setText("Can't find Location!");
  }

  }

  private Boolean RqsLocation(int cid, int lac){

   Boolean result = false;

   String urlmmap = "http://www.google.com/glm/mmap";

  try {
      URL url = new URL(urlmmap);
      URLConnection conn = url.openConnection();
      HttpURLConnection httpConn = (HttpURLConnection) conn;      
      httpConn.setRequestMethod("POST");
      httpConn.setDoOutput(true);
      httpConn.setDoInput(true);
      httpConn.connect();

     OutputStream outputStream = httpConn.getOutputStream();
     WriteData(outputStream, cid, lac);

     InputStream inputStream = httpConn.getInputStream();
     DataInputStream dataInputStream = new DataInputStream(inputStream);

    dataInputStream.readShort();
    dataInputStream.readByte();
    int code = dataInputStream.readInt();
    if (code == 0) {
     myLatitude = dataInputStream.readInt();
     myLongitude = dataInputStream.readInt();

        result = true;

    }
 } catch (IOException e) {

  e.printStackTrace();
 }

 return result;

  }

  private void WriteData(OutputStream out, int cid, int lac)
throws IOException
  {    
  DataOutputStream dataOutputStream = new DataOutputStream(out);
  dataOutputStream.writeShort(21);
  dataOutputStream.writeLong(0);
  dataOutputStream.writeUTF("en");
  dataOutputStream.writeUTF("Android");
  dataOutputStream.writeUTF("1.0");
  dataOutputStream.writeUTF("Web");
  dataOutputStream.writeByte(27);
  dataOutputStream.writeInt(0);
  dataOutputStream.writeInt(0);
  dataOutputStream.writeInt(3);
  dataOutputStream.writeUTF("");

  dataOutputStream.writeInt(cid);
  dataOutputStream.writeInt(lac);   

  dataOutputStream.writeInt(0);
  dataOutputStream.writeInt(0);
  dataOutputStream.writeInt(0);
  dataOutputStream.writeInt(0);
  dataOutputStream.flush();    
}

}

主要.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/gsmcelllocation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
 />
<TextView
android:id="@+id/cid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
 />
<TextView
android:id="@+id/lac"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/geo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

清单文件:

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

<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".Towercap2Activity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

logcat 显示错误如下:

01-07 08:59:32.056: W/Trace(801): Unexpected value from nativeGetEnabledTags: 0
01-07 08:59:32.056: W/Trace(801): Unexpected value from nativeGetEnabledTags: 0
01-07 08:59:32.056: W/Trace(801): Unexpected value from nativeGetEnabledTags: 0
01-07 08:59:32.356: W/Trace(801): Unexpected value from nativeGetEnabledTags: 0
01-07 08:59:32.377: W/Trace(801): Unexpected value from nativeGetEnabledTags: 0
01-07 08:59:32.886: D/AndroidRuntime(801): Shutting down VM
01-07 08:59:32.896: W/dalvikvm(801): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
01-07 08:59:32.976: E/AndroidRuntime(801): FATAL EXCEPTION: main
01-07 08:59:32.976: E/AndroidRuntime(801): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tower/com.tower.Towercap2Activity}: java.lang.NullPointerException
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.os.Looper.loop(Looper.java:137)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.app.ActivityThread.main(ActivityThread.java:5039)
01-07 08:59:32.976: E/AndroidRuntime(801):  at java.lang.reflect.Method.invokeNative(Native Method)
01-07 08:59:32.976: E/AndroidRuntime(801):  at java.lang.reflect.Method.invoke(Method.java:511)
01-07 08:59:32.976: E/AndroidRuntime(801):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-07 08:59:32.976: E/AndroidRuntime(801):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-07 08:59:32.976: E/AndroidRuntime(801):  at dalvik.system.NativeStart.main(Native Method)
01-07 08:59:32.976: E/AndroidRuntime(801): Caused by: java.lang.NullPointerException
01-07 08:59:32.976: E/AndroidRuntime(801):  at com.tower.Towercap2Activity.onCreate(Towercap2Activity.java:68)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.app.Activity.performCreate(Activity.java:5104)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-07 08:59:32.976: E/AndroidRuntime(801):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-07 08:59:32.976: E/AndroidRuntime(801):  ... 11 more

请告诉问题是什么以及如何避免这种情况。提前致谢

4

2 回答 2

0

cellLocation一片空白!

getCellLocation()如果当前位置不可用,则返回 null。

你必须考虑到这种情况。


解释:

以这种方式考虑:您不能保证从中获得位置getCellLocation()(由于多种可能的原因,其中之一可能是连接不良)。因此,此函数可能会返回 null 而不是真正的CellLocation. 当它返回 null 并且您尝试getCid()在此 null 值上使用时,NullPointerException会抛出 a 并且您的应用程序崩溃。


解决方案:

int cid = 0;
int lac = 0;
if(cellLocation !=null) {

    cid = cellLocation.getCid();
    lac = cellLocation.getLac();

}
于 2013-01-07T09:18:37.570 回答
0

只需检查这样的空值GsmCellLocation

if(cellLocation !=null) <---Add this null check.
 {
   int cid = cellLocation.getCid();
   int lac = cellLocation.getLac();
   textCID.setText("gsm cell id: " + String.valueOf(cid));
   textLAC.setText("gsm location area_code"+String.valueOf(lac));
              .....................................
      ...................................
 }
于 2013-01-07T09:24:15.093 回答