2013-04-20 106 views
0

我創建了一個涉及JSON解析的android應用程序。當我在我的模擬器中運行該應用程序時,它工作正常,但是當我在我的android手機中運行它時,它會輸出一個錯誤「不幸已停止」。用Java解析JSON

這是我的JSON類:

package com.example.uichandbook; 


import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.graphics.Paint; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Gravity; 
import android.view.View; 
import android.widget.Button; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.widget.Toast; 



public class MainActivity extends Activity {  
    Button b1; 
    Button copy; 
    Button search; 
    int final_id = 0; 
    int final_id2 = 0; 
    int large1 = 0; 
    int large2 = 0; 
    int counter2; 
    int counter1; 
    String parse; 


    // url to make request 
    private static String url = "http://lynda.byethost32.com/UICHandbook/contents.json"; 
    private static String url2 = "http://lynda.byethost32.com/UICHandbook/sub_contents.json"; 

int id; 
    DatabaseHandler db = new DatabaseHandler(this); 
    // contacts JSONArray 
    JSONArray contacts = null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


        if (DetectConnection 
          .checkInternetConnection(MainActivity.this) == true) { 
         Toast.makeText(MainActivity.this, 
          "You have Internet Connection", Toast.LENGTH_LONG) 
          .show(); 
        updates(); 
        } 
     DatabaseHandler db = new DatabaseHandler(this); 
     List<data2> contacts = db.getAllContent(); 

     for (data2 cn : contacts) { 

      LinearLayout lnr = (LinearLayout) findViewById(R.id.container); 
      lnr.setPadding(1, 1, 1, 1); 
      b1 = new Button(this); 
      LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Verbose! 
      lp.weight = 1.0f; // This is critical. Doesn't work without it. 
      b1.setId(cn.getid()); 

      final int _id = b1.getId(); 
      b1.setText(cn.getcontentname()); 
      lnr.addView(b1, lp); 

      copy = ((Button)findViewById(_id)); 

      copy.setOnClickListener(new View.OnClickListener(){   
       public void onClick(View view){ 
        Intent intent = new Intent(MainActivity.this, subcontent.class); 
        intent.putExtra("id", _id);   
        startActivity(intent); 
       } 
       }); 
       } 

     db.close(); 

      } 


    public void getjson() 
    { 
      // Creating JSON Parser instance 
     JSONParser jParser = new JSONParser(); 
     // getting JSON string from URL 
     JSONObject json = jParser.getJSONFromUrl(url); 
     try{ 
      // Create a new HTTP Client 
      DefaultHttpClient defaultClient = new DefaultHttpClient(); 
      // Setup the get request 
      HttpGet httpGetRequest = new HttpGet(url); 
      // Execute the request in the client 
      HttpResponse httpResponse = defaultClient.execute(httpGetRequest); 
      // Grab the response 
      BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); 
      String jsonreader = reader.readLine(); 
      // Instantiate a JSON object from the request response 
      JSONObject jsonObject = new JSONObject(jsonreader); 
      contacts = jsonObject.getJSONArray("tbl_content"); 
      for(int i = 0; i < contacts.length(); i++){ 
      JSONObject c = contacts.getJSONObject(i); 
      Log.d("contact", c.getString("content_name")); 
      Log.d("contact", c.getString("content")); 
      Log.d("contact", c.getString("content_id")); 
      Log.d("contact", c.getString("book_id")); 
      DatabaseHandler db = new DatabaseHandler(this); 
      db.addcontent(new data2(c.getInt("content_id"), c.getString("content_name"),c.getString("content"),c.getInt("book_id"))); 
      } 
      } catch(Exception e){ 
      // In your production code handle any errors and catch the individual exceptions 
      e.printStackTrace(); 
      } 
     } 

public void getjson2() 
{ 
     // Creating JSON Parser instance 
    JSONParser jParser = new JSONParser(); 

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

    try{ 
     // Create a new HTTP Client 
     DefaultHttpClient defaultClient = new DefaultHttpClient(); 
     // Setup the get request 
     HttpGet httpGetRequest = new HttpGet(url2); 
     // Execute the request in the client 
     HttpResponse httpResponse = defaultClient.execute(httpGetRequest); 
     // Grab the response 
     BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); 
     String jsonreader = reader.readLine(); 
     // Instantiate a JSON object from the request response 
     JSONObject jsonObject = new JSONObject(jsonreader); 
     contacts = jsonObject.getJSONArray("subcontent"); 
     for(int i = 0; i < contacts.length(); i++){ 
     JSONObject c = contacts.getJSONObject(i); 
     Log.d("contact", c.getString("subcontent_name")); 
     Log.d("contact", c.getString("subcontent")); 
     Log.d("contact", c.getString("subcontent_id")); 
     Log.d("contact", c.getString("content_id")); 

     DatabaseHandler db = new DatabaseHandler(this); 

     db.subaddcontent(new data3(c.getInt("subcontent_id"), c.getString("subcontent_name"),c.getString("subcontent"),c.getInt("content_id"))); 

     } 
     } catch(Exception e){ 
     // In your production code handle any errors and catch the individual exceptions 
     e.printStackTrace(); 
     } 


     } 





final static String SYSTEM_NEWLINE = "\n"; 
final static float COMPLEXITY = 5.12f; //Reducing this will increase effici ency but will decrease effectiveness 
final static Paint p = new Paint(); 

public static void justifyText(final TextView tv, final float origWidth){ 
    String s = tv.getText().toString(); 
    p.setTypeface(tv.getTypeface());   
    String [] splits = s.split(SYSTEM_NEWLINE); 
    float width = origWidth - 5; 
    for(int x = 0; x<splits.length;x++) 
     if(p.measureText(splits[x])>width){ 
      splits[x] = wrap(splits[x], width, p); 
      String [] microSplits = splits[x].split(SYSTEM_NEWLINE); 
      for(int y = 0; y<microSplits.length-1;y++) 
       microSplits[y] = justify(removeLast(microSplits[y], " "), width, p); 
      StringBuilder smb_internal = new StringBuilder(); 
      for(int z = 0; z<microSplits.length;z++) 
       smb_internal.append(microSplits[z]+((z+1<microSplits.length) ? SYSTEM_NEWLINE : "")); 
      splits[x] = smb_internal.toString(); 
     }  
    final StringBuilder smb = new StringBuilder(); 
    for(String cleaned : splits) 
     smb.append(cleaned+SYSTEM_NEWLINE); 
    tv.setGravity(Gravity.LEFT); 
    tv.setText(smb); 
} 
private static String wrap(String s, float width, Paint p){ 
    String [] str = s.split("\\s"); //regex 
    StringBuilder smb = new StringBuilder(); //save memory 
    smb.append(SYSTEM_NEWLINE); 
    for(int x = 0; x<str.length; x++){ 
     float length = p.measureText(str[x]); 
     String [] pieces = smb.toString().split(SYSTEM_NEWLINE); 
     try{ 
      if(p.measureText(pieces[pieces.length-1])+length>width)   
       smb.append(SYSTEM_NEWLINE); 
     }catch(Exception e){} 
     smb.append(str[x] + " "); 
    } 
    return smb.toString().replaceFirst(SYSTEM_NEWLINE, ""); 
} 
private static String removeLast(String s, String g){ 
    if(s.contains(g)){ 
     int index = s.lastIndexOf(g); 
     int indexEnd = index + g.length(); 
     if(index == 0) return s.substring(1); 
     else if(index == s.length()-1) return s.substring(0, index); 
     else 
      return s.substring(0, index) + s.substring(indexEnd); 
    } 
    return s; 
} 
private static String justifyOperation(String s, float width, Paint p){ 
    float holder = (float) (COMPLEXITY*Math.random()); 
    while(s.contains(Float.toString(holder))) 
     holder = (float) (COMPLEXITY*Math.random()); 
    String holder_string = Float.toString(holder); 
    float lessThan = width; 
    int timeOut = 100; 
    int current = 0; 
    while(p.measureText(s)<lessThan&&current<timeOut) { 
     s = s.replaceFirst(" ([^"+holder_string+"])", " "+holder_string+"$1"); 
     lessThan = p.measureText(holder_string)+lessThan-p.measureText(" "); 
     current++;   
    } 
    String cleaned = s.replaceAll(holder_string, " "); 
    return cleaned; 
} 
private static String justify(String s, float width, Paint p){ 
    while(p.measureText(s)<width){ 
     s = justifyOperation(s,width, p); 
    } 
    return s; 

} 

public void updates() 
{ 
    DatabaseHandler db = new DatabaseHandler(this); 
    db.deletetable1(); 
    db.deletetable2(); 
    getjson(); 
    //getjson2(); 
} 


} 
+3

我不會讀這段代碼行數。請減少它,以便只包含相關部分(從刪除'imports'開始)。 – Maroun 2013-04-20 08:33:25

+5

請從'logcat'發佈日誌。 – 2013-04-20 08:33:31

+1

粘貼你的日誌請... – 2013-04-20 08:34:31

回答

0

你正在做的Activity's Main Thread所有的操作。請使用AsyncTask從網上下載您的數據。

從Android 4.0 +版本開始,必須使用Worker Thread。

異步任務的文檔鏈接:AsyncTask

0

UR在機器人mainthread被暫停mainthread超過5秒以上會導致ANR錯誤或強制close.Make使用的AsyncTask的執行網絡呼叫。

public class WS_GetSMS_Asynctask extends AsyncTask<Void,Void,Void>{ 
     @Override 
     protected Void doInBackground(Void... params) { 
     //do your work here 

       // Creating JSON Parser instance 
      JSONParser jParser = new JSONParser(); 
      // getting JSON string from URL 
      JSONObject json = jParser.getJSONFromUrl(url); 
      try{ 
       // Create a new HTTP Client 
       DefaultHttpClient defaultClient = new DefaultHttpClient(); 
       // Setup the get request 
       HttpGet httpGetRequest = new HttpGet(url); 
       // Execute the request in the client 
       HttpResponse httpResponse = defaultClient.execute(httpGetRequest); 
       // Grab the response 
       BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); 
       String jsonreader = reader.readLine(); 
       // Instantiate a JSON object from the request response 
       JSONObject jsonObject = new JSONObject(jsonreader); 
       contacts = jsonObject.getJSONArray("tbl_content"); 
       for(int i = 0; i < contacts.length(); i++){ 
       JSONObject c = contacts.getJSONObject(i); 
       Log.d("contact", c.getString("content_name")); 
       Log.d("contact", c.getString("content")); 
       Log.d("contact", c.getString("content_id")); 
       Log.d("contact", c.getString("book_id")); 
       DatabaseHandler db = new DatabaseHandler(this); 
       db.addcontent(new data2(c.getInt("content_id"), c.getString("content_name"),c.getString("content"),c.getInt("book_id"))); 
       } 
       } catch(Exception e){ 
       // In your production code handle any errors and catch the individual exceptions 
       e.printStackTrace(); 
       } 
    return null; 
    }