我正在尝试从android studio中的JSONParser列表中获取单个数据。编译时没有错误,但它在设备上保持强制关闭。这是我的JSONParser代码:
public class JSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jCountries = null;
try {
// Retrieves all the elements in the 'countries' array
jCountries = jObject.getJSONArray("konten");
} catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;
// Taking each country, parses and adds to list object
for(int i=0; i<countryCount;i++){
try {
// Call getCountry with country JSON object to parse the country
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
// Parsing the Country JSON object
private HashMap<String, Object> getCountry(JSONObject jCountry){
HashMap<String, Object> country = new HashMap<String, Object>();
String idkos = "";
String namakos = "";
String alamat = "";
String cp = "";
String koordinat1 = "";
String koordinat2 = "";
String fasilitas = "";
String harga = "";
String jenis = "";
String foto1 = "";
String foto2 = "";
String foto3 = "";
/*String countryName = "";
String flag="";
String language = "";
String capital = "";
String currencyCode = "";
String currencyName = "";*/
try {
idkos = jCountry.getString("id_kos");
namakos = jCountry.getString("nama_kos");
alamat = jCountry.getString("alamat");
cp = jCountry.getString("cp");
koordinat1 = jCountry.getString("koordinat1");
koordinat2 = jCountry.getString("koordinat2");
fasilitas = jCountry.getString("fasilitas");
harga = jCountry.getString("harga");
jenis = jCountry.getString("jenis");
foto1 = jCountry.getString("foto1");
foto2 = jCountry.getString("foto2");
foto3 = jCountry.getString("foto3");
country.put("id_kos", idkos);
country.put("nama_kos", namakos);
country.put("alamat", alamat);
country.put("cp", cp);
country.put("koordinat1", koordinat1);
country.put("koordinat2", koordinat2);
country.put("fasilitas", fasilitas);
country.put("harga", harga);
country.put("jenis", jenis);
country.put("foto1", R.drawable.blank);
country.put("foto2", foto2);
country.put("foto3", foto3);
country.put("id_kos", idkos);
country.put("flag_path", foto1);
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
}
这是我的活动代码:
public class DisplayPeta extends FragmentActivity {
private static final String TAG_SENTKAT = "exKategori";
private static final String TAG_SENTMIN = "exMin";
private static final String TAG_SENTMAX = "exMax";
ListView mListView;
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_peta);
Intent in = getIntent();
String exMin = in.getStringExtra(TAG_SENTMIN);
String exMax = in.getStringExtra(TAG_SENTMAX);
String exKat = in.getStringExtra(TAG_SENTKAT);
// URL to the JSON data
String strUrl = "http://smartkos.zz.mu/android/kos.php?min=" +exMin+ "&max=" +exMax+ "&jenis=" +exKat;
//String strUrl = "http://wptrafficanalyzer.in/p/demo1/first.php/countries";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_kos);
// Set new Adapter from listView
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Setting the adapter to the listView
mListView.setAdapter(adapter);
// Click Listener + Intent DisplayInfo
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
//LinearLayout linearLayoutParent = (LinearLayout) container;
// Getting the inner Linear Layout
//LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);
// Getting the Country TextView
//TextView nama = (TextView) linearLayoutChild.getChildAt(0);
String nama = ((TextView) container.findViewById(R.id.nama)).getText().toString();
String idkos = ((TextView) container.findViewById(R.id.id)).getText().toString();
String alamat = ((TextView) container.findViewById(R.id.alamat)).getText().toString();
String kontak = ((TextView) container.findViewById(R.id.kontak)).getText().toString();
String jenis = ((TextView) container.findViewById(R.id.jenis)).getText().toString();
String harga = ((TextView) container.findViewById(R.id.harga)).getText().toString();
String info = ((TextView) container.findViewById(R.id.infotext)).getText().toString();
String gal1 = ((TextView) container.findViewById(R.id.gal1)).getText().toString();
String gal2 = ((TextView) container.findViewById(R.id.gal2)).getText().toString();
String gal3 = ((TextView) container.findViewById(R.id.gal3)).getText().toString();
String lati = ((TextView) container.findViewById(R.id.latitude)).getText().toString();
String longi = ((TextView) container.findViewById(R.id.longitude)).getText().toString();
//Toast.makeText(getBaseContext(), nama.getText().toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), nama, Toast.LENGTH_SHORT).show();
// Memulai memanggil ke class KontakActivity dengan data
Intent in = new Intent(getApplicationContext(),DisplayInfo.class);
in.putExtra("id", idkos);
in.putExtra("nama", nama);
in.putExtra("alamat", alamat);
in.putExtra("kontak", kontak);
in.putExtra("jenis", jenis);
in.putExtra("harga", harga);
in.putExtra("info", info);
in.putExtra("gallery1", gal1);
in.putExtra("gallery2", gal2);
in.putExtra("gallery3", gal3);
in.putExtra("lat", lati);
in.putExtra("lon", longi);
startActivity(in);
}
};
// Setting the item click listener for the listview
mListView.setOnItemClickListener(itemClickListener);
setUpMapIfNeeded();
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception download url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
@Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
JSONParser jsonParser = new JSONParser();
jsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
JSONParser jsonParser = new JSONParser();
//List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = jsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
//NGELEBOKNE LATITUDE LONGITUDE NENG MAPS, COBA LEWAT KENE
// Keys used in Hashmap
String[] from = { "id_kos", "nama_kos", "flag", "harga" ,"alamat", "cp", "jenis", "fasilitas",
"foto1", "foto2", "foto3", "koordinat1","koordinat2"};
// Ids of views in listview_layout
int[] to = { R.id.id, R.id.nama,R.id.gambar,R.id.harga,R.id.alamat, R.id.kontak, R.id.jenis,
R.id.infotext, R.id.gal1, R.id.gal2, R.id.gal3, R.id.latitude, R.id.longitude};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.listview_layout, from, to);
return adapter;
}
// Invoked by the Android on "doInBackground" is executed
@Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
// AsyncTask to download and load an image in ListView
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
@Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p/>
* If it isn't installed {@link SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
* method in {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {@link #mMap} is not null.
*/
private void setUpMap(){
mMap.setMyLocationEnabled(true);
double latitude;
double longitude;
int jumlahdata= countries.size();
for(int i=0;i<jumlahdata;i++){
latitude = (double) countries.get(i).get("koordinat1");
longitude = (double) countries.get(i).get("koordinat2");
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("You are here!")
.snippet("Consider yourself located"));
}
}
}
它应该显示一个带有一些标记的地图。没有countries.size和countries.get代码就可以正常工作,但是当我添加大小并获取代码时,应用程序将在设备上关闭。任何人都可以帮助我吗?
这是我的logcat:
05-30 21:24:52.322 23664-23664/com.example.sk.maplist E/ResourceType﹕ 0x5ace6988: Failed to ResTable::remove() cookie = 0x3, not last table. mHeaders.size() = 4. Warning for spontaneous crashes when the garbage collector runs.
05-30 21:24:52.322 23664-23664/com.example.sk.maplist E/asset﹕ Error removing runtime skin resource (cookie 0x3)
05-30 21:24:52.322 23664-23664/com.example.sk.maplist I/asset﹕ Problem removing all runtime skin resources
05-30 21:24:52.602 23664-23664/com.example.sk.maplist D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
05-30 21:24:52.612 23664-23664/com.example.sk.maplist D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
05-30 21:24:52.622 23664-23664/com.example.sk.maplist D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
05-30 21:24:52.632 23664-23664/com.example.sk.maplist I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_2.6.1.04.02.02.121.010_msm8960_JB_2.6_CL3869936_release_AU (CL3869936)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/16/13 Sat
Local Branch:
Remote Branch: quic/jb_2.6
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB_2.6.1.04.02.02.121.010 + NOTHING
05-30 21:24:52.732 23664-23664/com.example.sk.maplist D/OpenGLRenderer﹕ Enabling debug mode 0
05-30 21:25:06.136 23664-23664/com.example.sk.maplist I/dalvikvm﹕ Could not find method android.app.AppOpsManager.checkPackage, referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
05-30 21:25:06.146 23664-23664/com.example.sk.maplist W/dalvikvm﹕ VFY: unable to resolve virtual method 120: Landroid/app/AppOpsManager;.checkPackage (ILjava/lang/String;)V
05-30 21:25:06.146 23664-23664/com.example.sk.maplist D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0010
05-30 21:25:06.146 23664-23664/com.example.sk.maplist I/dalvikvm﹕ Could not find method android.content.pm.PackageManager.getPackageInstaller, referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zzg
05-30 21:25:06.146 23664-23664/com.example.sk.maplist W/dalvikvm﹕ VFY: unable to resolve virtual method 498: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
05-30 21:25:06.146 23664-23664/com.example.sk.maplist D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000b
05-30 21:25:06.156 23664-23664/com.example.sk.maplist I/zzx﹕ Making Creator dynamically
05-30 21:25:06.226 23664-23664/com.example.sk.maplist I/Google Maps Android API﹕ Google Play services client version: 7095000
05-30 21:25:06.246 23664-23664/com.example.sk.maplist I/Google Maps Android API﹕ Google Play services package version: 7571034
05-30 21:25:06.277 23664-23664/com.example.sk.maplist I/dalvikvm﹕ Could not find method android.app.AppOpsManager.checkPackage, referenced from method com.google.android.gms.common.ij.a
05-30 21:25:06.277 23664-23664/com.example.sk.maplist W/dalvikvm﹕ VFY: unable to resolve virtual method 111: Landroid/app/AppOpsManager;.checkPackage (ILjava/lang/String;)V
05-30 21:25:06.277 23664-23664/com.example.sk.maplist D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0012
05-30 21:25:06.277 23664-23664/com.example.sk.maplist I/dalvikvm﹕ Could not find method android.content.pm.PackageManager.getPackageInstaller, referenced from method com.google.android.gms.common.ij.a
05-30 21:25:06.277 23664-23664/com.example.sk.maplist W/dalvikvm﹕ VFY: unable to resolve virtual method 449: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
05-30 21:25:06.277 23664-23664/com.example.sk.maplist D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000d
05-30 21:25:06.287 23664-23664/com.example.sk.maplist I/dalvikvm﹕ Could not find method android.app.Notification$Builder.setLocalOnly, referenced from method com.google.android.gms.common.ij.b
05-30 21:25:06.287 23664-23664/com.example.sk.maplist W/dalvikvm﹕ VFY: unable to resolve virtual method 154: Landroid/app/Notification$Builder;.setLocalOnly (Z)Landroid/app/Notification$Builder;
05-30 21:25:06.287 23664-23664/com.example.sk.maplist D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0201
05-30 21:25:06.947 23664-23664/com.example.sk.maplist D/AndroidRuntime﹕ Shutting down VM
05-30 21:25:06.947 23664-23664/com.example.sk.maplist W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418ea8b0)
05-30 21:25:06.967 23664-23664/com.example.sk.maplist E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sk.maplist/com.example.sk.maplist.DisplayPeta}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.access$600(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.sk.maplist.DisplayPeta.setUpMap(DisplayPeta.java:400)
at com.example.sk.maplist.DisplayPeta.setUpMapIfNeeded(DisplayPeta.java:385)
at com.example.sk.maplist.DisplayPeta.onCreate(DisplayPeta.java:131)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.access$600(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)