Основной поток приостановлен и исключение времени выполнения - PullRequest
0 голосов
/ 30 ноября 2011

все, что у меня появляется, начинают появляться, когда я запускаю свой код.Я понятия не имею, в чем может быть проблема, потому что мне в теории сказали, что она должна работать, и затмение, похоже, не обнаруживает ошибок при кодировании.Любая помощь в том, как улучшить код или как решить ошибку времени выполнения, будет высоко ценится.

Код следующий:

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) 

Большинство из вышеперечисленного показали, что источник не может быть найден с помощью отладки.

Ответы [ 2 ]

1 голос
/ 30 ноября 2011

Вы выполняете сетевой запрос в главном потоке, который вызывает ANR, и вы пишете в постоянное хранилище для каждого человека в JSON, что может привести к длительной операции.Сетевой запрос должен выполняться в отдельном потоке, и вы должны иметь возможность скомпилировать людей в один курсор для одновременной записи в базу данных.

0 голосов
/ 30 ноября 2011

Попробуйте установить несколько окон сообщений или около того, чтобы определить место ошибки во время выполнения.Я думаю, что что-то не так с инициализацией JSONArray jArray = new JSONArray(result); возможно, результат не валидный

...