0

我创建了一个涉及 JSON 解析的 android 应用程序。当我在模拟器中运行该应用程序时,它可以工作,但是当我在我的 android 手机中运行它时,它会输出错误“不幸的是已停止”。

这是我的 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();
 }


}
4

2 回答 2

0

您在 android 中的主线程上执行网络调用,暂停主线程超过 5 秒将导致 ANR 错误或强制关闭。使用 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;
    }
于 2013-04-23T07:59:08.817 回答
0

您正在对Activity's Main Thread. 请使用AsyncTask从网络下载您的数据。

从 Android 4.0 + 版本开始,必须使用 Worker Thread。

异步任务文档链接:AsyncTask

于 2013-04-23T03:59:16.083 回答