我想解析一个json,我已经设法在onCreate中解析它,但应用程序显示一个空白的屏幕大约5-6秒,所以我以为我会#l?ll做一些doInBackground并显示进度条,直到解析完成..但应用程序继续崩溃与OutOfBoundsExeption ......
这是我的代码:
公共类MainActivity扩展了Activity {
private ArrayList<LatLng> markers = new ArrayList<LatLng>();
private LocationManager locationManager;
TextView text, distance, metric, warningTxt, speedTxt, kmh;
public double lat, lon;
private Location nearest;
private ArrayList<Location> cameras;
String answerstr;
public EditText editt;
public ImageView sign;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
text = (TextView) findViewById(R.id.text);
new DownloadJSON().execute();
cameras = new ArrayList<Location>();
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, mlocListener);
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(MainActivity.this);
progressBar.setTitle("Çek 1.5 JSON");
progressBar.setMessage("Jsondan veriler çekiliyor...");
progressBar.setIndeterminate(false);
progressBar.show();
}
@Override
protected Void doInBackground(Void... params) {
jsonarray = JSONParser
.getJSONfromURL("https://dl.dropboxusercontent.com/s/84el6b3mpgat7uj/aggie.json");
try {
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject row;
row = jsonarray.getJSONObject(i);
Location currentLoc;
String camera;
double lat, lon;
camera = row.getString("name");
lat = row.getDouble("latitude");
lon = row.getDouble("longitude");
currentLoc = new Location(camera);
currentLoc.setLatitude(lat);
currentLoc.setLongitude(lon);
cameras.add(currentLoc);
}
} catch (NullPointerException ex) {
ex.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
progressBar.dismiss();
}
}
public void sortByLocation(Location mycurrentlocation) {
boolean swapped = true;
while (swapped) {
swapped = false;
for (int i = 1; i < cameras.size(); i++) {
if (cameras.get(i - 1).distanceTo(mycurrentlocation) > cameras
.get(i).distanceTo(mycurrentlocation)) {
Location tmp = cameras.get(i);
cameras.set(i, cameras.get(i - 1));
cameras.set(i - 1, tmp);
swapped = true;
}
}
}
}
public Location getNearest() {
nearest = cameras.get(0);
return nearest;
}
// handles the menu.
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
lat = loc.getLatitude();
lon = loc.getLongitude();
Location currentLocation = new Location("Current");
currentLocation.setLatitude(lat);
currentLocation.setLongitude(lon);
LatLng tmp = new LatLng(loc.getLatitude(), loc.getLongitude());
sortByLocation(currentLocation);
text.setText(getNearest().getProvider());
if (currentLocation.distanceTo(getNearest()) < 1000) {
text.setTextColor(Color.RED);
}
else {
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
这是我的logcat:
08-20 21:51:06.256: E/AndroidRuntime(26236): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
08-20 21:51:06.256: E/AndroidRuntime(26236): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
08-20 21:51:06.256: E/AndroidRuntime(26236): at java.util.ArrayList.get(ArrayList.java:308)
08-20 21:51:06.256: E/AndroidRuntime(26236): at com.finlaysmith.MotorcycleParking.MainActivity.getNearest(MainActivity.java:190)
08-20 21:51:06.256: E/AndroidRuntime(26236): at com.finlaysmith.MotorcycleParking.MainActivity$MyLocationListener.onLocationChanged(MainActivity.java:217)
08-20 21:51:06.256: E/AndroidRuntime(26236): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:279)
08-20 21:51:06.256: E/AndroidRuntime(26236): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:208)
08-20 21:51:06.256: E/AndroidRuntime(26236): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:224)
08-20 21:51:06.256: E/AndroidRuntime(26236): at android.os.Handler.dispatchMessage(Handler.java:102)
08-20 21:51:06.256: E/AndroidRuntime(26236): at android.os.Looper.loop(Looper.java:136)
08-20 21:51:06.256: E/AndroidRuntime(26236): at android.app.ActivityThread.main(ActivityThread.java:5001)
08-20 21:51:06.256: E/AndroidRuntime(26236): at java.lang.reflect.Method.invokeNative(Native Method)
08-20 21:51:06.256: E/AndroidRuntime(26236): at java.lang.reflect.Method.invoke(Method.java:515)
08-20 21:51:06.256: E/AndroidRuntime(26236): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
08-20 21:51:06.256: E/AndroidRuntime(26236): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
答案 0 :(得分:0)
Line -> JSONArray jArray=new JSONArray(result); giving nullpointer exception
在转换为JSONArray之前将结果转换为JSONObject
请注意,您的JSON结构不好:
&#34; anykey&#34;:[//此密钥丢失,因此您无法直接转换为JSON对象 { &#34;经度&#34;:4.424652, &#34;纬度&#34;:49.534077, &#34;名称&#34;:&#34;区域危险130 kmh&#34;, &#34; free_bikes&#34;:&#34; 1&#34;, &#34; empty_slots&#34;:&#34; 130&#34;, &#34; id&#34;:&#34;&#34; }, { &#34;经度&#34;:5.387198, &#34;纬度&#34;:45.173737, &#34;名称&#34;:&#34;区域危险130 kmh&#34;, &#34; free_bikes&#34;:&#34; 1&#34;, &#34; empty_slots&#34;:&#34; 130&#34;, &#34; id&#34;:&#34;&#34; },....
使用它转换为JsonObject然后转换为Json Array
httpclient = new DefaultHttpClient();
httppost = new HttpPost("https://dl.dropboxusercontent.com/s/84el6b3mpgat7uj/aggie.json");
response = httpclient.execute(httppost); // Execute HTTP Post Request
inputStream = response.getEntity().getContent();
String result=null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line=null;
while((line=reader.readLine())!= null){
sb.append(line+"\n");
}
inputStream.close();
result=sb.toString();
jObject = new JSONObject(result.trim());
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
if( jObject.get(key) instanceof JSONObject ){
}
}
请在使用之前初始化ArrayList
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
text = (TextView) findViewById(R.id.text);
cameras = new ArrayList<Location>();// before you start asynctask
new DownloadJSON().execute();
我注意到的另一件事:请使用getter / setter从AsyncTask类内部访问私有变量摄像头。
答案 1 :(得分:0)
试试这个,
JSONArray jsonObject = new JSONArray("https://dl.dropboxusercontent.com/s/84el6b3mpgat7uj/aggie.json");
JSONArray jArray= jsonObject.getJSONArray(0);
for (int i = 0; i <jArray.length(); i++){ ... }
答案 2 :(得分:-1)
试试这个: 你的问题是由这一行引起的:
08-20 21:51:06.256: E/AndroidRuntime(26236): at com.finlaysmith.MotorcycleParking.MainActivity$MyLocationListener.onLocationChanged(MainActivity.java:217)
(MainActivity.java:217)
所以我认为你必须在确定数组已经填满后设置监听器
@Override
protected void onPostExecute(Void args) {
progressBar.dismiss();
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, mlocListener);
}