Reputation: 81
all I have an error begin thrown up when I am running my code. I have no idea what the issue could be cause I have been told in theory it should work and eclipse does not seem to detect any errors with coding. Any help on how to improve the code or how to solve the runtime error would be much appreciated.
The code is the following:
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;
}
}
The DPAdapter is:
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);
}
}
Error Log:
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)
Most of the above has shown that the source cannot be found using debug.
Upvotes: 0
Views: 2336
Reputation: 10938
You're doing a network request on the main thread, which will cause ANRs & you're writing to persistent storage for each person in the JSON, which could add up to a long operation. The network request should be done on a separate thread, and you should be able to compile the people into one cursor to write into the database all at once.
Upvotes: 1
Reputation: 4741
Try to set some of message boxes or so to locate place of runtime error. I think something wrong with initialization of JSONArray jArray = new JSONArray(result);
perhaps result not valide
Upvotes: 0