2017-02-16 7 views
0

私は自分のサーバーからAPI RESTを介して緯度と経度を受け取っているアプリを開発しましたので、その座標を表示する前にAPIコールを解決する必要があります地図。私にこれを行う方法を教えてください。Maps上に表示する前にAPIリクエストから座標を取得

私はすでに解決策を実装していますが、うまくいかないようです。私はこのメッセージを持っているスタックトレースから

E/AndroidRuntime: FATAL EXCEPTION: main 
       Process: pro.rane.myapplication, PID: 1590 
       java.lang.NullPointerException: Attempt to get length of null array 
        at pro.rane.myapplication.MapsActivity.onMapReady(MapsActivity.java:160) 
        at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source) 
        at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source) 
        at android.os.Binder.transact(Binder.java:392) 
        at com.google.android.gms.maps.internal.bw.a(:com.google.android.gms.DynamiteModulesB:82) 
        at com.google.maps.api.android.lib6.impl.bf.run(:com.google.android.gms.DynamiteModulesB:1805) 
        at android.os.Handler.handleCallback(Handler.java:815) 
        at android.os.Handler.dispatchMessage(Handler.java:104) 
        at android.os.Looper.loop(Looper.java:207) 
        at android.app.ActivityThread.main(ActivityThread.java:5728) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 

私は、このエラーは、関数getCoordinates()が正常に動作しないことに起因していることを意識しています。私は過去にもVolleyライブラリを使用しようとしましたが、それは同じように動作しませんでした。私のAPIリクエストを動作させるにはどうすればいいですか?

URLが機能していることに注意してください。自分のサーバーで自分のリクエストを取得すると、ブラウザに正しい結果が表示されます。ここで

は私のコードです:

パブリッククラスMapsActivityはFragmentActivityがOnMapReadyCallback {

private static final String LATITUDE = "latitude"; 
private static final String LONGITUDE = "longitude"; 

private GoogleMap mMap; 
private String info; 
/** 
* ATTENTION: This was auto-generated to implement the App Indexing API. 
* See https://g.co/AppIndexing/AndroidStudio for more information. 
*/ 
private GoogleApiClient client; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
    Bundle b = getIntent().getExtras(); 
    if (b != null) 
     info = b.getString("qrCodeInformation"); 
    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
} 

/*connection to obtain the array of positions*/ 


private static String[][] getCoordinates(String tran_id) throws JSONException { 

    String dummy_tran_id = "1"; 

    String richiesta = "http://myurl/getArticleTravel?tran_id=" + dummy_tran_id; 

    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
    HttpGet request = new HttpGet(richiesta); 

    request.setHeader("Content-type", "application/json"); 

    InputStream inputStream = null; 
    String result = ""; 
    try { 
     HttpResponse response = httpclient.execute(request); 
     HttpEntity entity = response.getEntity(); 

     inputStream = entity.getContent(); 
     // json is UTF-8 by default 
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
     StringBuilder sb = new StringBuilder(); 

     String line; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     result = sb.toString(); 
    } catch (Exception e) { 
     Log.i("Errore http request",""+e.getMessage()); 
    } finally { 
     try { 
      if (inputStream != null) inputStream.close(); 
     } catch (Exception squish) { 
      Log.i(squish.getMessage(), squish.getMessage()); 
     } 
    } 

    JSONArray jObject; 
    String[][] coordinates; 

    jObject = new JSONArray(result); 
    String[] latitude = new String[jObject.length()]; 
    String[] longitude = new String[jObject.length()]; 

    for (int i = 0; i < jObject.length(); i++) { 

     latitude[i] = jObject.getJSONObject(i).getString(LATITUDE); 
     longitude[i] = jObject.getJSONObject(i).getString(LONGITUDE); 
    } 

    coordinates = new String[latitude.length][longitude.length]; 

     for(int i =0; i < latitude.length;i++){ 
      coordinates[i][0] = latitude[i]; 
      coordinates[i][1] = longitude[i]; 
     } 


    //String[][] dummy_coordinates = {{"45.465454", "9.186515999999983"}, {"41.9027835", "12.496365500000024"}}; 

    return coordinates; 
    //return dummy_coordinates; 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 

    String[][] coordinates = {{"45.465454", "9.186515999999983"}, {"41.9027835", "12.496365500000024"},{"40.9027835", "15.496365500000024"}}; //= null; 
    try { 
     coordinates = getCoordinates(info); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    Integer a; 
    mMap = googleMap; 
    View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null); 
    TextView numTxt = (TextView) marker.findViewById(R.id.num_txt); 

    for (a = 0; a < coordinates.length; a++) { 

     if(a==0){ 
      numTxt.setText("Go"); 
      mMap.addMarker(new MarkerOptions() 
        .position(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1]))) 
        .title("GO") 
        .snippet("Start point "+ a.toString()) 
        .icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker))) 
      ); 
     }else { 
      numTxt.setText(a.toString()); 
      mMap.addMarker(new MarkerOptions() 
        .position(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1]))) 
        .title(a.toString()) 
        .snippet("Arrival point " + a.toString()) 
        .icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker))) 
      ); 
     } 
     googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])),5)); 
    } 



} 
// Convert a view to bitmap 
public static Bitmap createDrawableFromView(Context context, View view) { 
    DisplayMetrics displayMetrics = new DisplayMetrics(); 
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); 
    view.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, ViewPager.LayoutParams.WRAP_CONTENT)); 
    view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels); 
    view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels); 
    view.buildDrawingCache(); 
    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); 

    Canvas canvas = new Canvas(bitmap); 
    view.draw(canvas); 

    return bitmap; 
} 

@Override 
public void onStart() { 
    super.onStart(); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    client.connect(); 
} 

@Override 
public void onStop() { 
    super.onStop(); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    client.disconnect(); 
} 
} 
+0

あなたはonPostExecute'は、インターフェイスメソッドを介して 'Activity'に値を返すか、マップ参照に渡された上でアクションを実行するのいずれか'で、その後、 'AsyncTask'で' getCoordinates'を置く必要があります。 –

+0

これらの機能の例とリンクを投稿してください。 – Thecave3

答えて

0

がAsyncTaskクラスを拡張し、バックグラウンドスレッドでgetCoordinatesから仕事を処理するためにdoInBackgroundを使用して実装して拡張します。あなたは、座標値を、あなたのAsyncTaskを実行し、リスナーインタフェースを設定取得したいあなたのActivity

public class YourAsyncTask extends AsyncTask<Void, Void, YourReturnType> { 

    public interface OnFinishListener{ 
     void onFinish(YourReturnType result); 
    } 

    private OnFinishListener mListener; 

    public OnFinishListener setOnFinishListener(@Nullable OnFinishListener l){ 
     mListener = l; 
    } 

    @Override 
    protected YourReturnType doInBackground(Void... params) { 
     // Replace all "YourReturnType" with the actual type/object you want to return 
     YourReturnType returnValue; 

     // Do your work here and build/create your returnValue 

     return returnValue; 
    } 

    // This will get called automatically after doInBackground finishes 
    @Override 
    protected void onPostExecute(YourReturnType result) { 
     // If listener is set 
     if(mListener != null){ 
      mListener.onFinish(result); // Return the returnValue 
     } 
    } 
} 

YourAsyncTask yourTask = new YourAsyncTask(); 
yourTask.execute(); 
yourTask.setOnFinishListener(new YourAsyncTask.OnFinishListener(){ 
    @Override 
    public void onFinish(YourReturnType result){ 
     // Retrieve your returned value from result 
     // And if mMap is ready, perform map actions 
    } 
}); 

AsyncTask documentation

+1

本当に分かりやすくて、ありがとうございました! – Thecave3

関連する問題