2

AndroidでJSONをListviewに解析するための優れたチュートリアルを探しています。

問題は私のJSONファイルがこのようなものだということです

[{"location_id":"823","company_id":"41","name":"Milj\u00f8station","address":"Aldersro \/ Aldersro 8","place":"","postal":"5700","city":"Svendborg","monday":"","tuesday":"","wednesday":"","thursday":"","friday":"","saturday":"","sunday":"","type":"2","lat":"55.061426149085","lng":"10.5927246809006","nocar":"0","distance":"0.00023254303859579"}]

ほとんどのチュートリアルはJson配列で始まり、後でデータになります。たくさんの例があることは知っていますが、私の問題に一致するものを見つけることができませんでした。

コードを追加しましたが、まだ機能していません。これが私の3つのクラスです。

SingleMenuItemActivity

public class SingleMenuItemActivity  extends Activity {

// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list_item);

    // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String name = in.getStringExtra(TAG_NAME);
    String cost = in.getStringExtra(TAG_EMAIL);
    String description = in.getStringExtra(TAG_PHONE_MOBILE);

    // Displaying all values on the screen
    TextView lblName = (TextView) findViewById(R.id.name_label);
    TextView lblCost = (TextView) findViewById(R.id.email_label);
    TextView lblDesc = (TextView) findViewById(R.id.mobile_label);

    lblName.setText(name);
    lblCost.setText(cost);
    lblDesc.setText(description);
} }

JSONParser

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        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) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
} }

AndroidJSONParserActvity

public class AndroidJSONParsingActivity extends ListActivity {

// url to make request
private static String url = "http://webservice.xxx.com/webservice/getLocationList.php?lat=55.061424255371094&lng=10.592724800109863";

// JSON Node names
private static final String TAG_Location = "location_id";
private static final String TAG_Company = "company_id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_PLACE = "place";
private static final String TAG_POSTAL = "postal";
private static final String TAG_CITY = "city";
private static final String TAG_MONDAY = "monday";
private static final String TAG_TUESDAY = "tuesday";
private static final String TAG_WEDNESDAY = "wednesday";
private static final String TAG_THURSDAY = "thursday";
private static final String TAG_FRIDAY = "friday";
private static final String TAG_SATURDAY = "saturday";
private static final String TAG_SUNDAY = "sunday";
private static final String TAG_TYPE = "type";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_NOCAR = "nocar";



// contacts JSONArray
JSONArray contacts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {

        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String location_id = c.getString(TAG_Location);
            String company_id = c.getString(TAG_Company);
            String name = c.getString(TAG_NAME);
            String address = c.getString(TAG_ADDRESS);
            String place = c.getString(TAG_PLACE);  
            String postal = c.getString(TAG_POSTAL);
            String city = c.getString(TAG_CITY);
            String monday = c.getString(TAG_MONDAY);
            String tuesday = c.getString(TAG_TUESDAY);
            String wednesday = c.getString(TAG_WEDNESDAY);  
            String thursday = c.getString(TAG_THURSDAY);
            String friday = c.getString(TAG_FRIDAY);
            String saturday = c.getString(TAG_SATURDAY);
            String sunday = c.getString(TAG_SUNDAY);
            String type = c.getString(TAG_TYPE);
            String lat = c.getString(TAG_LAT);
            String lng = c.getString(TAG_LNG);
            String nocar = c.getString(TAG_NOCAR);


        // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_Location, location_id);
            map.put(TAG_Company, company_id);
            map.put(TAG_NAME, name);
            map.put(TAG_ADDRESS, address);
            map.put(TAG_PLACE, place);
            map.put(TAG_POSTAL, postal);
            map.put(TAG_CITY, city);
            map.put(TAG_MONDAY, monday);
            map.put(TAG_TUESDAY, tuesday);
            map.put(TAG_WEDNESDAY, wednesday);
            map.put(TAG_THURSDAY, thursday);
            map.put(TAG_FRIDAY, friday);
            map.put(TAG_SATURDAY, saturday);
            map.put(TAG_SUNDAY, sunday);
            map.put(TAG_TYPE, type);
            map.put(TAG_LAT, lat);
            map.put(TAG_LNG, lng);
            map.put(TAG_NOCAR, nocar);

                // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item,
            new String[] { TAG_NAME, TAG_LAT, TAG_Company }, new int[] {
                    R.id.name, R.id.email, R.id.mobile });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_Location, cost);
            in.putExtra(TAG_Company, description);
            startActivity(in);

        }
    });
} }

LogCatのエラー

     02-06 10:06:19.025: D/AbsListView(9115): Get MotionRecognitionManager 02-06 10:06:19.705: D/dalvikvm(9115): GC_CONCURRENT freed 206K, 6% free 12315K/12999K, paused 13ms+14ms, total 40ms 02-06 10:06:19.725: E/JSON Parser(9115): Error parsing data org.json.JSONException: Value [{"nocar":"0","company_id":"41","postal":"5700","thursday":"","monday":"","lng":"10.5927246809006","type":"2","city":"Svendborg","location_id":"823","distance":"0.00023254303859579","wednesday":"","address":"Aldersro \/ Aldersro 8","sunday":"","name":"Miljøstation","saturday":"","friday":"","tuesday":"","place":"","lat":"55.061426149085"},
02-06 10:06:19.730: D/AndroidRuntime(9115): Shutting down VM
02-06 10:06:19.730: W/dalvikvm(9115): threadid=1: thread exiting with uncaught exception (group=0x4100f2a0)
02-06 10:06:19.740: E/AndroidRuntime(9115): FATAL EXCEPTION: main
02-06 10:06:19.740: E/AndroidRuntime(9115): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.jsonparsing/com.androidhive.jsonparsing.AndroidJSONParsingActivity}: java.lang.NullPointerException
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.os.Looper.loop(Looper.java:137)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.main(ActivityThread.java:4898)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at java.lang.reflect.Method.invokeNative(Native Method)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at java.lang.reflect.Method.invoke(Method.java:511)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at dalvik.system.NativeStart.main(Native Method)
02-06 10:06:19.740: E/AndroidRuntime(9115): Caused by: java.lang.NullPointerException
02-06 10:06:19.740: E/AndroidRuntime(9115):     at com.androidhive.jsonparsing.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:69)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.Activity.performCreate(Activity.java:5206)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
02-06 10:06:19.740: E/AndroidRuntime(9115):     ... 11 more
4

3 に答える 3

3

JSONArrayあなたのWebサービスは代わりにを返しJSONObjectますが、それを JSONObject に変換しようとしているためです。getJSONFromUrlメソッドの戻り値の型をasJSONArrayではなくに変更します。JSONObject

public JSONArray getJSONFromUrl(String url) {
 JSONArray jsonarr=null;
    // Making HTTP request

    // try parse the string to a JSONArray
    try {
        jsonarr = new JSONArray(json);
    } catch (JSONException e) {

    }

    // return JSON String
    return jsonarr;  //<<<< return JSONArray instead of JSONObject
}

getJSONFromUrlActivity の onCreate から呼び出します:

 JSONArray json = jParser.getJSONFromUrl(url);

try {

    // looping through All Contacts
    for(int i = 0; i < json.length(); i++){
        JSONObject c = json.getJSONObject(i);

        // put your parsing code here
    }
} catch (JSONException e) {
    e.printStackTrace();
}
于 2013-02-06T09:18:01.397 に答える
0
try{
        // String t;
        Boolean found=false;

            JSONArray jArray = new JSONArray(result);
         int jArrayLength = jArray.length(); 
       ArrayList<String> listContents = new ArrayList<String>(jArrayLength);

            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
               // t[i]=json_data.getString("hotelname");


            listContents.add(json_data.getString("hotelname"));







            }






            arr = new String[listContents.size()];
            for(int i=0;i<listContents.size();i++)
                arr[i]= listContents.get(i);
             setListAdapter(new ArrayAdapter<String>(this,
                     android.R.layout.simple_list_item_1,arr));




    }
    catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }




}

public void onListItemClick( ListView parent, View v, int position, long id) { Intent myIntent = new Intent(getBaseContext(), Hotelinfo.class); myIntent.putExtra("ホテル名",arr[位置]);

        startActivity(myIntent);
        }

}
于 2013-02-06T09:27:54.053 に答える