1

关于这里的另一个线程,我也尝试从 json 中获取 json 数组。我有以下文件:

地震.json

[{
        "eqid": "合并",
        “幅度”:8.8,
        “液化天然气”:142.369,
        “src”:“我们”,
        "日期时间": "2011-03-11 04:46:23",
        “深度”:24.4,
        “纬度”:38.322
    }, {
        "eqid": "merge2",
        “幅度”:8.6,
        “液化天然气”:93.0632,
        “src”:“我们”,
        "日期时间": "2012-04-11 06:38:37",
        “深度”:22.9,
        “纬度”:2.311
    }, {
        "eqid": "2007hear",
        “幅度”:8.4,
        “液化天然气”:101.3815,
        “src”:“我们”,
        "日期时间": "2007-09-12 09:10:26",
        “深度”:30,
        “纬度”:-4.5172
    }, {
        "eqid": "c00090da",
        “幅度”:8.2,
        “液化天然气”:92.4522,
        “src”:“我们”,
        "日期时间": "2012-04-11 08:43:09",
        “深度”:16.4,
        “纬度”:0.7731
    }, {
        "eqid": "2007aqbk",
        “大小”:8,
        “液化天然气”:156.9567,
        “src”:“我们”,
        "日期时间": "2007-04-01 18:39:56",
        “深度”:10,
        “纬度”:-8.4528
    }, {
        "eqid": "2007hec6",
        “幅度”:7.8,
        “液化天然气”:100.9638,
        “src”:“我们”,
        "日期时间": "2007-09-12 21:49:01",
        “深度”:10,
        “纬度”:-2.5265
    }, {
        “eqid”:“b000g7x7”,
        “幅度”:7.8,
        “液化天然气”:62.0532,
        “src”:“我们”,
        "日期时间": "2013-04-16 08:44:20",
        “深度”:82,
        “纬度”:28.1069
    }, {
        "eqid": "a00043nx",
        “幅度”:7.7,
        “液化天然气”:100.1139,
        “src”:“我们”,
        "日期时间": "2010-10-25 12:42:22",
        “深度”:20.6,
        “纬度”:-3.4841
    }, {
        "eqid": "2010utc5",
        “幅度”:7.7,
        “液化天然气”:97.1315,
        “src”:“我们”,
        "日期时间": "2010-04-06 20:15:02",
        “深度”:31,
        “纬度”:2.3602
    }, {
        "eqid": "2009mebz",
        “幅度”:7.6,
        “液化天然气”:99.9606,
        “src”:“我们”,
        "日期时间": "2009-09-30 08:16:09",
        “深度”:80,
        “纬度”:-0.7889
    }]

MainActivity.java

package ayub.khosa.json_parsing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity 
{
String tag = "AYUB";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{ super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.listplaceholder);
    Log.d(tag, "setContentView  ");
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


    JSONArray json = null;
    try {
        json = JSONfunctions.getJSONfromURL("http://192.168.0.104/earthquakes.json");
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    Log.d(tag, "json object  "); 
    try{
        Collection<?> result = null;
        JSONArray json1 = new JSONArray(result);
 //         // ...

        for(int i=0;i<json.length();i++){                        
            HashMap<String, String> map = new HashMap<String, String>();    
            JSONObject e = json1.getJSONObject(i);

            map.put("id",  String.valueOf(i));
            map.put("name", "Earthquake name:" + e.getString("eqid"));
            map.put("magnitude", "Magnitude: " +  e.getString("magnitude"));
            mylist.add(map);            
        }
    }catch(JSONException e)        {
         Log.e("log_tag", "Error parsing data "+e.toString());
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.activity_main, 
                    new String[] { "name", "magnitude" }, 
                    new int[] { R.id.item_title, R.id.item_subtitle });

    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);  
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);   
            Log.d(tag, "json object  " + lv.getItemAtPosition(position)); 
            Toast.makeText(MainActivity.this, "ID " + o.get("id")+" " + o.get("name") + o.get("magnitude")+".", Toast.LENGTH_SHORT).show(); 

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
 } 
}

JSONFunctions.java

package ayub.khosa.json_parsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) throws ClientProtocolException, IOException, JSONException{
InputStream is = null;
String result = "";
JSONArray jArray = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        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();
        result=sb.toString();

    jArray = new JSONArray(result);            
return jArray;
}
}

问题是屏幕上没有数据,我只收到警告:

09-21 12:09:26.225: W/ActivityManager(59): Launch timeout has expired, giving up wake lock!
09-21 12:09:26.500: W/ActivityManager(59): Activity idle timeout for HistoryRecord{43ee8ee8 ayub.khosa.json_parsing/.MainActivity}

更新 :

事实上,网络服务器在我没有注意到的情况下关闭了。现在好了,我在浏览器中看到了 json,但现在我收到以下错误:

     09-21 12:30:52.301: W/ActivityManager(59): Activity destroy timeout for HistoryRecord{43f44da0 ayub.khosa.json_parsing/.MainActivity}
     09-21 12:30:57.449: I/ActivityManager(59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=ayub.khosa.json_parsing/.MainActivity }
     09-21 12:30:57.609: I/ActivityManager(59): Start proc ayub.khosa.json_parsing for activity ayub.khosa.json_parsing/.MainActivity: pid=287 uid=10036 gids={3003}
     09-21 12:30:58.179: D/AYUB(287): setContentView  
     09-21 12:30:58.339: D/AYUB(287): json object  
     09-21 12:30:58.339: D/AndroidRuntime(287): Shutting down VM
     09-21 12:30:58.339: W/dalvikvm(287): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
     09-21 12:30:58.349: E/AndroidRuntime(287): FATAL EXCEPTION: main
     09-21 12:30:58.349: E/AndroidRuntime(287): java.lang.RuntimeException: Unable to start activity ComponentInfo{ayub.khosa.json_parsing/ayub.khosa.json_parsing.MainActivity}: java.lang.NullPointerException
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.os.Handler.dispatchMessage(Handler.java:99)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.os.Looper.loop(Looper.java:123)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.app.ActivityThread.main(ActivityThread.java:4627)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at java.lang.reflect.Method.invokeNative(Native Method)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at java.lang.reflect.Method.invoke(Method.java:521)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at dalvik.system.NativeStart.main(Native Method)
     09-21 12:30:58.349: E/AndroidRuntime(287): Caused by: java.lang.NullPointerException
     09-21 12:30:58.349: E/AndroidRuntime(287):     at java.util.ArrayList.addAll(ArrayList.java:193)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at org.json.JSONArray.<init(JSONArray.java:70)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at ayub.khosa.json_parsing.MainActivity.onCreate(MainActivity.java:58)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
     09-21 12:30:58.349: E/AndroidRuntime(287):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
     09-21 12:30:58.349: E/AndroidRuntime(287):     ... 11 more
     09-21 12:30:58.419: D/dalvikvm(287): GC_FOR_MALLOC freed 3711 objects / 261576 bytes in 67ms
     09-21 12:30:58.429: W/ActivityManager(59):   Force finishing activity ayub.khosa.json_parsing/.MainActivity
     09-21 12:30:58.958: W/ActivityManager(59): Activity pause timeout for HistoryRecord{440757b8 ayub.khosa.json_parsing/.MainActivity}
     09-21 12:31:02.689: I/Process(287): Sending signal. PID: 287 SIG: 9
     09-21 12:31:02.709: I/ActivityManager(59): Process ayub.khosa.json_parsing (pid 287) has died.
     09-21 12:31:02.729: W/InputManagerService(59): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@43e4ec30
     09-21 12:31:09.089: W/ActivityManager(59): Activity destroy timeout for HistoryRecord{440757b8 ayub.khosa.json_parsing/.MainActivity}


UPDATE 2 - after Max edit suggestion

>  09-21 13:08:24.395: D/AYUB(272): setContentView 

>  09-21 13:08:24.475: I/global(272): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.

>  09-21 13:08:24.475: W/System.err(272): org.json.JSONException: End of input at character 0 of 

>  09-21 13:08:24.485: W/System.err(272):   at org.json.JSONTokener.syntaxError(JSONTokener.java:446)

>  09-21 13:08:24.485: W/System.err(272):   at org.json.JSONTokener.nextValue(JSONTokener.java:93)

>  09-21 13:08:24.495: W/System.err(272):   at org.json.JSONArray.<init>(JSONArray.java:87)

>  09-21 13:08:24.495: W/System.err(272):   at org.json.JSONArray.<init>(JSONArray.java:103)

>  09-21 13:08:24.495: W/System.err(272):   at ayub.khosa.json_parsing.JSONfunctions.getJSONfromURL(JSONfunctions.java:41)

>  09-21 13:08:24.495: W/System.err(272):   at ayub.khosa.json_parsing.MainActivity.onCreate(MainActivity.java:44)

>  09-21 13:08:24.495: W/System.err(272):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

>  09-21 13:08:24.495: W/System.err(272):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

>  09-21 13:08:24.495: W/System.err(272):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)

>  09-21 13:08:24.495: W/System.err(272):   at android.app.ActivityThread.access$2300(ActivityThread.java:125)

>  09-21 13:08:24.495: W/System.err(272):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

>  09-21 13:08:24.495: W/System.err(272):   at android.os.Handler.dispatchMessage(Handler.java:99)

>  09-21 13:08:24.495: W/System.err(272):   at android.os.Looper.loop(Looper.java:123)

>  09-21 13:08:24.495: W/System.err(272):   at android.app.ActivityThread.main(ActivityThread.java:4627)

>  09-21 13:08:24.495: W/System.err(272):   at java.lang.reflect.Method.invokeNative(Native Method)

>  09-21 13:08:24.505: W/System.err(272):   at java.lang.reflect.Method.invoke(Method.java:521)

>  09-21 13:08:24.505: W/System.err(272):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

>  09-21 13:08:24.505: W/System.err(272):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

>  09-21 13:08:24.505: W/System.err(272):   at dalvik.system.NativeStart.main(Native Method)

>  09-21 13:08:24.505: D/AYUB(272): json object  

>  09-21 13:08:24.505: D/AndroidRuntime(272): Shutting down VM

>  09-21 13:08:24.505: W/dalvikvm(272): threadid=1: thread exiting with uncaught exception (group=0x4001d800)

>  09-21 13:08:24.515: E/AndroidRuntime(272): FATAL EXCEPTION: main

>  09-21 13:08:24.515: E/AndroidRuntime(272): java.lang.RuntimeException: Unable to start activity ComponentInfo{ayub.khosa.json_parsing/ayub.khosa.json_parsing.MainActivity}: java.lang.NullPointerException

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.app.ActivityThread.access$2300(ActivityThread.java:125)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.os.Handler.dispatchMessage(Handler.java:99)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.os.Looper.loop(Looper.java:123)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.app.ActivityThread.main(ActivityThread.java:4627)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at java.lang.reflect.Method.invokeNative(Native Method)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at java.lang.reflect.Method.invoke(Method.java:521)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at dalvik.system.NativeStart.main(Native Method)

>  09-21 13:08:24.515: E/AndroidRuntime(272): Caused by: java.lang.NullPointerException

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at java.util.ArrayList.addAll(ArrayList.java:193)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at org.json.JSONArray.<init>(JSONArray.java:70)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at ayub.khosa.json_parsing.MainActivity.onCreate(MainActivity.java:58)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

>  09-21 13:08:24.515: E/AndroidRuntime(272):   ... 11 more

>  09-21 13:08:27.035: I/Process(272): Sending signal. PID: 272 SIG: 9
4

3 回答 3

1

尝试改变你的 GET 一点:

DefaultHttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet(url);
StringBuilder sb = new StringBuilder();

HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();

if (entity != null) {
  entity.consumeContent();
}

...

InputStream is = entity.getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader sb = new BufferedReader(isr);
String line = null;

while ( (line = br.readLine()) != null) {
     sb.append(line + "\n");
    }
    is.close();

    result=sb.toString();

   // before conversion to JSONArray print it:
   Log.d("Fess", result);

   jArray = new JSONArray(result);   

[编辑]

从您的日志中我看到:

 Caused by: java.lang.NullPointerException 
at java.util.ArrayList.addAll(ArrayList.java:193)
于 2013-09-21T12:39:09.920 回答
0

我想建议将 JSON 格式更改为:

{"earthquake" : [Your Original JSON Here]}

要解析 JSON,您将需要创建一个新JSONObject的 ,例如,我们将 json 字符串保存到一个名为 的字符串jsontext中,创建一个新的JSONObjectlike :

JSONObject mainObject = new JSONObject(jsontext);

取数组“地震”:

JSONArray Earthquake = mainObject.getJSONArray("earthquake");

然后像往常一样解析它。

出于某种原因,如果您在创建 JSONArray 时未将其封装在对象中,则 JSONArray 将为空。

希望这会有所帮助,祝你好运^^

问候,

里德

编辑: 检查此代码是否具有 JSON 字符串->result=sb.toString();

像这样附加字符串:String jsondata = "{\"data\":" + result + "}";

像我上面解释的那样解析 json

于 2013-09-21T12:36:12.160 回答
0

我在http://remotegun.com上看到了一个关于 Android 和 Xcode的开源项目。与此地址地震应用程序联系

于 2015-03-31T11:59:46.757 回答