Android:Json解析错误

时间:2014-07-30 08:53:58

标签: android json

我正在尝试从json url获取数据 但是我得到了一个错误。

这是我的Json

[
    {
        "id": "1",
        "contest_name": "BOB",
        "url": "http://campaign.apps.com/bob",
        "start_date": "2014-07-01",
        "end_date": "2014-08-31"
    }
]

这是我的代码

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

    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(contestUrl);
    try {
          // Getting JSON Array

          contest = json.getJSONArray(TAG_ITEM_ID);
          JSONObject c = contest.getJSONObject(0);
          // Storing  JSON item in a Variable
          String url = c.getString(TAG_URL);
          String start_date = c.getString(TAG_START_DATE);
          String end_date = c.getString(TAG_END_DATE);
      } catch (JSONException e) {
        e.printStackTrace();
      }

这是我的错误

07-30 15:50:02.952: E/AndroidRuntime(12393): FATAL EXCEPTION: main
07-30 15:50:02.952: E/AndroidRuntime(12393): Process: com.indomultimedia.hellobali, PID: 12393
07-30 15:50:02.952: E/AndroidRuntime(12393): java.lang.NullPointerException
07-30 15:50:02.952: E/AndroidRuntime(12393):    at com.indomultimedia.hellobali.SecondFragment.onActivityCreated(SecondFragment.java:59)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:891)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:139)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.support.v4.view.ViewPager.populate(ViewPager.java:804)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1016)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.View.measure(View.java:17357)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.View.measure(View.java:17357)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.View.measure(View.java:17357)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.View.measure(View.java:17357)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:382)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.View.measure(View.java:17357)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2505)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.View.measure(View.java:17357)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2175)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1316)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1200)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6388)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.Choreographer.doCallbacks(Choreographer.java:603)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.Choreographer.doFrame(Choreographer.java:573)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.os.Handler.handleCallback(Handler.java:733)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.os.Handler.dispatchMessage(Handler.java:95)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.os.Looper.loop(Looper.java:157)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at android.app.ActivityThread.main(ActivityThread.java:5293)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at java.lang.reflect.Method.invokeNative(Native Method)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at java.lang.reflect.Method.invoke(Method.java:515)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-30 15:50:02.952: E/AndroidRuntime(12393):    at dalvik.system.NativeStart.main(Native Method)

我按照本教程http://www.learn2crack.com/2013/10/android-json-parsing-url-example.html

以下是learn2crack的代码

//URL to get JSON Array
  private static String url = "http://10.0.2.2/JSON/";
  //JSON Node Names
  private static final String TAG_USER = "user";
  private static final String TAG_ID = "id";
  private static final String TAG_NAME = "name";
  private static final String TAG_EMAIL = "email";
  JSONArray user = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    // Creating new JSON Parser
    JSONParser jParser = new JSONParser();
    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
      // Getting JSON Array
      user = json.getJSONArray(TAG_USER);
      JSONObject c = user.getJSONObject(0);
      // Storing  JSON item in a Variable
      String id = c.getString(TAG_ID);
      String name = c.getString(TAG_NAME);
      String email = c.getString(TAG_EMAIL);
      //Importing TextView
      final TextView uid = (TextView)findViewById(R.id.uid);
      final TextView name1 = (TextView)findViewById(R.id.name);
      final TextView email1 = (TextView)findViewById(R.id.email);
      //Set JSON Data in TextView
      uid.setText(id);
      name1.setText(name);
      email1.setText(email);
  } catch (JSONException e) {
    e.printStackTrace();
  }

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;
  }
}

如何修复该错误以及如何设置url globaly以便我可以将其发送到另一个活动中? 有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:2)

要将全局网址设置为跨活动使用,

  1. 使用静态最终变量声明:

    static final String url = c.getString(TAG_URL);
    

    要检索它, 使用classname.url

  2. 使用android的sharedpreference选项。

    以共享偏好保存:

    String url = c.getString(TAG_URL);
    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
    editor.putString("URL", url );
    editor.apply();
    

    从其他活动中检索:

    SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
    String url = prefs.getString("URL", null);
    
  3. 对于JSON解析,我想这会对你有帮助。也许,你的json输出只有一个对象[{}]。如果json输出是对象[{},{},{},{}]

    的集合,则应使用JSONArray
    String jsonStr = ; //{"id":"1","contest_name":"BOB","url":"http:\/\/campaign.apps.com\/bob","start_date":"2014-07-01","end_date":"2014-08-31"}
     JSONObject jsonObj = new JSONObject(jsonStr);
     String url = jsonObj .getString(TAG_URL);
    

答案 1 :(得分:0)

第1部分:请在内联添加错误。 (由于其他原因,我无法访问它。)

第2部分:要全局设置网址,您可以将网址变量配置为公开,并将其配置为Activity.urlVariable。

前:

public static string urlVariable; // (in MainActivity.java)
// and use it as 
MainActivity.urlVariable; // In other java class.

答案 2 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

public class MainActivty extends Activity {

    private JSONParser jParser;
    TextView uid;
    TextView name1;
    TextView email1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        uid = (TextView) findViewById(R.id.uid);
        name1 = (TextView) findViewById(R.id.name);
        email1 = (TextView) findViewById(R.id.email);

        try {
            jParser = new JSONParser();
            JSONArray json = jParser.getJSONFromUrl(url);

            uid.setText(json.getJSONObject(0).getString(TAG_ID));
            name1.setText(json.getJSONObject(0).getString(TAG_ID));
            email1.setText(json.getJSONObject(0).getString(TAG_ID));
        } catch (Throwable e) {
            e.printStackTrace();
        }

    }

    class JSONParser {
        InputStream is = null;
        JSONArray jArray = null;
        public JSONParser() {
        }
        public JSONArray getJSONFromUrl(String url) {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.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();
                jArray = new JSONArray(sb.toString());
            } catch (Throwable e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            return jArray;
        }
    }
}