运行代码时,我遇到的所有错误都会开始抛出。我不知道这个问题可能是什么原因,因为从理论上我已经被告知它应该起作用,并且eclipse似乎无法检测到任何编码错误。任何有关如何改进代码或如何解决运行时错误的帮助将不胜感激。

代码如下:

public class DatabaseActivity extends Activity {
/** Called when the activity is first created. */

public DBAdapter
DBAdapter =new DBAdapter(this);

TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);

// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText(getServerData(KEY_153));

}

public static final String KEY_153 = "http://xxxx.xxxx.com/api/execute.php";


private String getServerData(String returnString) {

InputStream is = null;

String result = "";
//the train line to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("gender","M"));

//http post
try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(KEY_153);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

}catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
}

//convert response to string
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();
        result=sb.toString();
}catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
}

//parse json data
try{
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                DBAdapter.insertPerson(json_data.getString("id"),
                                json_data.getString("firstname"),
                                json_data.getString("surname"),
                                json_data.getString("gender"),
                                json_data.getString("age"),
                                json_data.getString("race"),
                                json_data.getString("height"),
                                json_data.getString("weight"));

                //Get an output to the screen
                returnString += "\n\t" + jArray.getJSONObject(i);
        }
}catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}

}


DPAdapter是:

public class DBAdapter{
public static final String KEY_ID = "id";
public static final String KEY_FIRSTNAME = "firstname";
public static final String KEY_SURNAME = "surname";
public static final String KEY_GENDER = "gender";
public static final String KEY_AGE = "age";
public static final String KEY_RACE = "race";
public static final String KEY_HEIGHT = "height";
public static final String KEY_WEIGHT = "weight";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "survey";
private static final String DATABASE_TABLE = "people";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
    "create table titles (id integer primary key, "
    + "firstname text not null,"
    + "surname text not null,"
    + "gender text not null,"
    + "age text not null,"
    + "race text not null,"
    + "height text not null,"
    + "weight text not null);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
  {
      this.context = ctx;
      DBHelper = new DatabaseHelper(context);
      this.db=DBHelper.getWritableDatabase();
  }

private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL(DATABASE_CREATE);        }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion,
    int newVersion)
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion
                + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS titles");
        onCreate(db);
    }
}

//---opens the database---
public DBAdapter open() throws SQLException
{
    db = DBHelper.getWritableDatabase();
    return this;
}
//---closes the database---
public void close()
{
    DBHelper.close();
}

//---insert a title into the database---
public long insertPerson(String id, String firstname, String surname, String gender, String age, String race, String height, String weight)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_ID, id);
    initialValues.put(KEY_FIRSTNAME, firstname);
    initialValues.put(KEY_SURNAME, surname);
    initialValues.put(KEY_GENDER, gender);
    initialValues.put(KEY_AGE, age);
    initialValues.put(KEY_RACE, race);
    initialValues.put(KEY_HEIGHT, height);
    initialValues.put(KEY_WEIGHT, weight);
    return db.insert(DATABASE_TABLE, null, initialValues);
}
}


错误日志:

Database [Android Application]
DalvikVM[localhost:9115]
    Thread [<1> main] (Suspended (exception RuntimeException))
        ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1680
        ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1784
        ActivityThread.access$1500(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 123
        ActivityThread$H.handleMessage(Message) line: 939
        ActivityThread$H(Handler).dispatchMessage(Message) line: 99
        Looper.loop() line: 130
        ActivityThread.main(String[]) line: 3835
        Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
        Method.invoke(Object, Object...) line: 507
        ZygoteInit$MethodAndArgsCaller.run() line: 847
        ZygoteInit.main(String[]) line: 605
        NativeStart.main(String[]) line: not available [native method]
    Thread [<8> Binder Thread #2] (Running)
    Thread [<7> Binder Thread #1] (Running)


上面的大多数内容表明,使用调试无法找到源。

最佳答案

您正在主线程上执行网络请求,这将导致ANR,并且您正在写入JSON中每个人的持久性存储,这可能会导致较长的操作。网络请求应在单独的线程上完成,并且您应该能够将人员编译为一个游标以一次全部写入数据库。

关于java - 主线程被挂起并且运行时异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8324635/

10-10 16:10