我在运行代码时遇到错误。我不知道问题是什么原因我理论上告诉它它应该工作,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)
以上大部分内容都表明使用debug无法找到源代码。
答案 0 :(得分:1)
您正在主线程上执行网络请求,这将导致ANR和&amp;您正在为JSON中的每个人写入持久存储,这可能会导致长时间的操作。网络请求应该在一个单独的线程上完成,你应该能够将人员编译成一个游标,一次写入数据库。
答案 1 :(得分:0)
尝试设置一些消息框,以便找到运行时错误的位置。我认为JSONArray jArray = new JSONArray(result);
的初始化有问题可能导致没有valide