-2
私はマップ上にJSONを使用してマップ上にいくつかのマーカーを表示しようとしました。マップ上に位置を表示するためのJSON配列の呼び出しに失敗しました
route_activity.java
import java.util.ArrayList;
import org.json.JSONObject;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
public class route_activity extends FragmentActivity {
private GoogleMap map;
private JSONHelper json;
private ProgressDialog pDialog;
private ArrayList<route_list> listHalte;
private final String URL_API = "http://nfcworld.web.id/wibisono/retrieve.php";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map_route);
json = new JSONHelper();
new AsynTaskMain().execute();
setupMapIfNeeded();
}
@Override
public void onPause(){
super.onPause();
if(pDialog != null)
pDialog.dismiss();
}
private void setupMapIfNeeded()
{
if (map == null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map);
map = supportMapFragment.getMap();
if (map != null)
{
setupMap();
}
}
}
private void setupMap()
{
map.setMyLocationEnabled(true);
moveToMyLocation();
}
private void moveToMyLocation()
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 17));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.support_map, menu);
return true;
}
@Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();
//line 102
int resCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resCode != ConnectionResult.SUCCESS)
{
GooglePlayServicesUtil.getErrorDialog(resCode, this, 1);
}
}
private class AsynTaskMain extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
pDialog.dismiss();
runOnUiThread(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
for (int i = 0; i < listHalte.size(); i++)
{
map.addMarker(new MarkerOptions()
.position(new LatLng(listHalte.get(i).getLat(), listHalte.get(i).getLng()))
.title(listHalte.get(i).getNama()));
}
}
});
super.onPostExecute(result);
}
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(route_activity.this);
pDialog.setMessage("Loading....");
pDialog.setCancelable(true);
pDialog.show();
} //line 147
@Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
JSONObject jObject = json.getJSONFromURL(URL_API);
listHalte = json.gethalteAll(jObject);
return null;
}
}
}
JSONHelper.java
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
/**
* Created by wibisono on 10/19/2016.
*/
public class JSONHelper {
private InputStream is = null;
private JSONObject jsonObject = null;
private String json = "";
private final String TAG_HALTE = "halte";
private final String TAG_ID = "id";
private final String TAG_NAMA = "nama";
private final String TAG_LAT = "lat";
private final String TAG_LNG = "lng";
public JSONObject getJSONFromURL(String url)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.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)
{
// TODO: handle exception
}
try
{
jsonObject = new JSONObject(json);
} catch (JSONException e)
{
// TODO: handle exception
}
return jsonObject;
}
public ArrayList<route_list> gethalteAll(JSONObject jobj)
{
ArrayList<route_list> listhalte = new ArrayList<route_list>();
try
{
JSONArray arrayhalte = jobj.getJSONArray(TAG_HALTE); //line 99
for (int i = 0; i < arrayhalte.length(); i++)
{
JSONObject jobject = arrayhalte.getJSONObject(i);
Log.d("log", "muter ke " + i);
listhalte.add(new route_list(jobject.getInt(TAG_ID), jobject.getString(TAG_NAMA), jobject
.getDouble(TAG_LAT), jobject.getDouble(TAG_LNG)));
}
} catch (JSONException e)
{
e.printStackTrace();
}
return listhalte;
}
}
route_list.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by wibisono on 10/8/2016.
*/
public class route_list {
private int id;
private String nama;
private double lat;
private double lng;
public route_list()
{
// TODO Auto-generated constructor stub
}
public route_list(int id, String nama, double lat, double lng)
{
super();
this.id = id;
this.nama = nama;
this.lat = lat;
this.lng = lng;
}
public String getNama()
{
return nama;
}
public void setNama(String nama)
{
this.nama = nama;
}
public double getLat()
{
return lat;
}
public void setLat(double lat)
{
this.lat = lat;
}
public double getLng()
{
return lng;
}
public void setLng(double lng)
{
this.lng = lng;
}
}
LogCat
11-22 23:30:57.355 15576-15767/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.wibisono.tryhard_1, PID: 15576
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.example.wibisono.tryhard_1.JSONHelper.gethalteAll(JSONHelper.java:99)
at com.example.wibisono.tryhard_1.route_activity$AsynTaskMain.doInBackground(route_activity.java:147)
at com.example.wibisono.tryhard_1.route_activity$AsynTaskMain.doInBackground(route_activity.java:102)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
map_route.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".route_activity" >
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
retrieve.php
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
define('HOST','localhost');
define('USER','my_username');
define('PASS','my_password');
define('DB','my_database');
$konek = mysqli_connect(HOST,USER,PASS,DB);
$query = "SELECT * FROM halte";
$sql = mysqli_query($konek,$query);
$response = array();
while($row = mysqli_fetch_array($sql)){
array_push($response,array(
"id" => $row['id'];
"nama" => $row['nama'];
"lat" => $row['lat'];
"lng" => $row['lng'];
));
}
echo json_encode(array('halte'=>$response));
mysqli_close($konek);
}
?>
[NullPointerExceptionとは何か、それを修正する方法は?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how -do-i-fix-it) – Selvin
原因:java.lang.NullPointerException:nullオブジェクトリファレンスで仮想メソッド 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)'を呼び出そうとしています 何が間違っているかを判断するためにブレークポイントを使用しますが、doInBackgroundでjsonオブジェクトを呼び出すときにjsonオブジェクトが初期化されていないように見えます。 初期化する必要があります:private JSONHelper json; 次のようなものがあります:private JSONHelper json = new JSONHelper(); – Nyranith
@Nyranith私はまだ試したが、同じエラー、他の可能性がありますか? –