2014-01-24 73 views
0

我正在开发一个应用程序,此时显示一个地图,你的gps邮件和这个邮件上的一个标记。下一步是从XML文件接收数据。我试图使用的XML是http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4解析XML到谷歌地图程序

但启动应用程序后(在真实的设备上,最新版本)很差,应用程序终止并不显示任何内容。 logcat的说,致命的异常:主要 了java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.xmlparser/com.example.xmlparser.MainActivitz}:显示java.lang.NullPointerException

MainActivity.java

package com.example.xmlparser; 

import android.app.Activity; 
import android.content.Context; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 
import java.io.IOException; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.ParseException; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 
import com.google.android.gms.maps.CameraUpdate; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 


public class MainActivity extends Activity implements LocationListener { 
private TextView latituteField; 
private TextView longitudeField; 
private LocationManager locationManager; 
private String provider; 
public String url = "http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4"; 
public EditText feldname, id; 
public HandleXml obj; 

/** Called when the activity is first created. */ 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    latituteField = (TextView) findViewById(R.id.TextView02); 
    longitudeField = (TextView) findViewById(R.id.TextView04); 
    feldname = (EditText)findViewById(R.id.editText1); 
    id = (EditText)findViewById(R.id.editText2); 


    // Get the location manager 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    // Define the criteria how to select the location provider -> use 
    // default 
    Criteria criteria = new Criteria(); 
    provider = locationManager.getBestProvider(criteria, false); 
    Location location = locationManager.getLastKnownLocation(provider); 

    // Initialize the location fields 
    if (location != null) 
    { 
     System.out.println("Provider " + provider + " has been selected."); 
     onLocationChanged(location); 
    } 
    else 
    { 
     latituteField.setText("Location not available"); 
     longitudeField.setText("Location not available"); 
    } 

    float lat1 = (float) (location.getLatitude());  //Getting the position 
    float lng1 = (float) (location.getLongitude()); 
    GoogleMap mMap; 
    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment1)).getMap(); 
    mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(lat1, lng1)) 
      .title("Your Position")); 


    LatLng bounds = new LatLng(lat1, lng1); 


    CameraUpdate cu = CameraUpdateFactory.newLatLng(bounds); 

    mMap.moveCamera(cu); 
} 





//Request updates at startup */ 
@Override 
protected void onResume() { 
    super.onResume(); 
    locationManager.requestLocationUpdates(provider, 400, 1, this); 
} 

/* Remove the locationlistener updates when Activity is paused */ 
@Override 
protected void onPause() { 
    super.onPause(); 
    locationManager.removeUpdates(this); 
} 

@Override 
public void onLocationChanged(Location location) { 
    float lat = (float) (location.getLatitude());  //Getting the ' '' 
    float lng = (float) (location.getLongitude()); 
    latituteField.setText(String.valueOf(lat)); 
    longitudeField.setText(String.valueOf(lng)); 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 


} 

@Override 
public void onProviderEnabled(String provider) { 
    Toast.makeText(this, "Enabled new provider " + provider, 
      Toast.LENGTH_SHORT).show(); 

} 

@Override 
public void onProviderDisabled(String provider) { 
    Toast.makeText(this, "Disabled provider " + provider, 
      Toast.LENGTH_SHORT).show(); 
} 

公共无效开放(查看视图) { feldname.setText(URL); obj = new HandleXml(url); obj.fetchXML(); while(obj.parsingComplete); feldname.setText(obj.getFeldName()); id.setText(obj.getId()); }}

HandleXml.java

package com.example.xmlparser; 

import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 
import org.xmlpull.v1.XmlPullParser; 
import org.xmlpull.v1.XmlPullParserException; 
import org.xmlpull.v1.XmlPullParserFactory; 

import android.util.Log; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.Toast; 


public class HandleXml { 

    private String feldname = "name"; 
    private String id = "id"; 
    private String urlString = null; 
     private XmlPullParserFactory xmlFactoryObject; 
     public volatile boolean parsingComplete = true; 

     public HandleXml(String url) 
     { 
      this.urlString = url; 
     } 
     public String getFeldName() 
     { 
       return feldname; 
     } 
     public String getId() 
     { 
      return id; 
     } 
     public void parseXMLAndStoreIt(XmlPullParser myParser) 
     { 
       int event; 
       String text=null; 
       try 
       { 
       event = myParser.getEventType(); 
       while (event != XmlPullParser.END_DOCUMENT) 
       { 
        String name=myParser.getName(); 
        switch (event) 
        { 
         case XmlPullParser.START_TAG: 
         break; 
         case XmlPullParser.TEXT: 
         text = myParser.getText(); 
         break; 

         case XmlPullParser.END_TAG: 
          if(name.equals("name_kana")) 
          { 
           feldname = text; 
          } 
          else if(name.equals("id")) 
          {  
           id =text;// myParser.getAttributeValue(null,"value"); 
          } 

          else 
          {} 
          break; 
          }  
          event = myParser.next(); 

         } 
         parsingComplete = false; 
       } catch (Exception e) { 
       e.printStackTrace(); 
       } 

      } 
     public void fetchXML() 
     { 
       Thread thread = new Thread(new Runnable() 
       { 
       @Override 
       public void run() 
       { 
        try 
        { 
         URL url = new URL(urlString); 
         HttpURLConnection conn = (HttpURLConnection) 
         url.openConnection();           
          conn.setReadTimeout(10000 /* milliseconds */); 
          conn.setConnectTimeout(15000 /* milliseconds */); 
          conn.setRequestMethod("GET"); 
          conn.setDoInput(true); 
          conn.connect(); 
        InputStream stream = conn.getInputStream(); 

        xmlFactoryObject = XmlPullParserFactory.newInstance(); 
        XmlPullParser myparser = xmlFactoryObject.newPullParser(); 

        myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES 
        , false); 
        myparser.setInput(stream, null); 
        parseXMLAndStoreIt(myparser); 
        stream.close(); 
        } catch (Exception e) 
        { 
         e.printStackTrace(); 
        } 
       } 
      }); 

      thread.start(); 


      } 

     } 

AndroidManifest.xml中

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


<permission 
android:name="com.example.map.permission.MAPS_RECEIVE" 
android:protectionLevel="signature" /> 
<uses-sdk 
    android:minSdkVersion="12" 
    android:targetSdkVersion="18" /> 
<uses-feature 
android:glEsVersion="0x00020000" 
android:required="true" /> 

<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" android:debuggable="true"> 
    <uses-library android:name="com.google.android.maps" /> 
    <activity 
     android:name="com.example.xmlparser.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> 

    <meta-data 
    android:name="com.google.android.maps.v2.API_KEY" 
    android:value="AIzaSyC3DipaFNo1EC44rZ8N1AJKVAiUCNOtqZw"/> 
<meta-data 
android:name="com.google.android.gms.version" 
android:value="@integer/google_play_services_version" /> 
</application> 

</manifest> 

我真的希望你可以告诉我,什么是错,此代码,因为它是工作只有自己的地图和解析器作为自己的程序完全没问题。

+0

你的代码是一个完整的混乱,尝试一步一步地做事;) –

+0

@ Yume117你是如何推荐,新的代码,新的问题,也许你冒险看看 – user3196789

+0

什么行给你空指针异常? –

回答

0

这里是一个类,把位置逻辑的护理:

public class GPSManager extends Service implements android.location.LocationListener { 

// LOG 
protected static final String TAG        = GPSManager.class.getSimpleName(); 
// DATA 
protected Context    mContext; 
protected static GPSManager  mInstance; 
// DISTANCE BEFORE UPDATE 
protected static final long  MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;        // meters 
// TIME BEFORE UPDATE IN MILLISECONDE 
protected static final long  MIN_TIME_BW_UPDATES    = 1000 * 30 * 1;     // minute 
// LOCATION MANAGER 
protected LocationManager  mLocationManager; 
boolean       mIsGPSEnabled     = false; 
boolean       mIsNetworkEnabled    = false; 
boolean       mCanGetLocation     = false; 
public Location     mLocation; 
double       mLatitude; 
double       mLongitude; 

public GPSManager() { 
    mContext = null; 
} 

public static GPSManager getInstance() { 
    if (mInstance == null) { 
     mInstance = new GPSManager(); 
    } 
    return mInstance; 
} 

public void set_mContext(Context context) { 
    this.mContext = context; 
} 

public Location get_mLocation(Context context) { 
    mContext = context; 
    try { 
     mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 
     mIsGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     mIsNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     if (!mIsGPSEnabled && !mIsNetworkEnabled) { 
      // NO NETWORK PROVIDER ENABLED 
     } 
     else { 
      this.mCanGetLocation = true; 
      if (mIsNetworkEnabled) { 
       mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (mLocationManager != null) { 
        mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (mLocation != null) { 
         mLatitude = mLocation.getLatitude(); 
         mLongitude = mLocation.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (mIsGPSEnabled) { 
       if (mLocation == null) { 
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "GPS Enabled"); 
        if (mLocationManager != null) { 
         mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (mLocation != null) { 
          mLatitude = mLocation.getLatitude(); 
          mLongitude = mLocation.getLongitude(); 
         } 
        } 
       } 
      } 
     } 
    } 
    catch (Exception e) { 
     // DO NOTHING 
    } 
    return mLocation; 
} 

public void stopUsingGPS() { 
    if (mLocationManager != null) { 
     mLocationManager.removeUpdates(GPSManager.this); 
    } 
} 

public double get_mLatitude() { 
    if (mLocation != null) { 
     mLatitude = mLocation.getLatitude(); 
    } 
    return mLatitude; 
} 

public double get_mLongitude() { 
    if (mLocation != null) { 
     mLongitude = mLocation.getLongitude(); 
    } 
    return mLongitude; 
} 

public boolean canGetLocation() { 
    return this.mCanGetLocation; 
} 

/** 
* Function to show settings alert dialog On pressing Settings button will lauch Settings Options 
*/ 
public void showSettingsAlert(String title, String msg) { 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 
    alertDialog.setTitle(title); 
    alertDialog.setMessage(msg); 
    // SETTING BUTTON 
    alertDialog.setPositiveButton("Paramètres", new DialogInterface.OnClickListener() { 

     public void onClick(DialogInterface dialog, int which) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      mContext.startActivity(intent); 
     } 
    }); 
    // cancel button 
    alertDialog.setNegativeButton("Annuler", new DialogInterface.OnClickListener() { 

     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
     } 
    }); 
    // show 
    alertDialog.show(); 
} 

@Override 
public void onLocationChanged(Location location) { 
} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
} 

@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 
} 

现在如何在活动中使用它:

protected LatLng  mLocation; 
    protected GPSManager mGpsManager; 
    private GoogleMap  mGoogleMap; 

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_map); 
     // get location 
     mGpsManager = GPSManager.getInstance(); 
     mGpsManager.set_mContext(this); 
     Location location = mGpsManager.get_mLocation(this); 
     mLocation = new LatLng(location.getLatitude(), location.getLongitude()); 
     // setup map 
     mGoogleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); 
     mGoogleMap.setIndoorEnabled(true); 
     mGoogleMap.setMyLocationEnabled(true); 
     mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLocation.latitude, mLocation.longitude), 8.0f)); 
    } 


    @Override 
    protected void onDestroy() { 
     clearMap(mGoogleMap); 
     super.onDestroy(); 
    } 

    private void clearMap(GoogleMap googleMap) { 
     googleMap.clear(); 
    } 

我没有摆正位置更新,但你肯定会找到方法;)

+0

非常感谢,我可以使用它:) 现在我有一个新问题,但这是一个新的问题。 – user3196789