I am a VERY new android user. I try to save a Json object into a sqlite data base in my android. I saw the Json array ok in android log but, in my slqlite db there is no info (all null). ¿What I am doing wrong? (beside my bad english redaction)
AllStatActivity
public class AllStatActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// url to get all products list
private static String url_all_exams = "http://myweb.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_EXAMS = "exams";
private TextView txtResultado;
private SQLiteDatabase db;
// products JSONArray
JSONArray exams = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_stat);
//Abrimos la base de datos 'DBUsuarios' en modo escritura
ExamsSQLiteHelper usdbh = new ExamsSQLiteHelper(this, "DBAAExams", null, 1);
db = usdbh.getWritableDatabase();
txtResultado = (TextView)findViewById(R.id.txtResultado);
// Loading products in Background Thread
new LoadAllExams().execute();
}
/**
* Background Async Task to Load all exams by making HTTP Request
*/
class LoadAllExams extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllStatActivity.this);
pDialog.setMessage("Loading exams. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_exams, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Exams: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
exams = json.getJSONArray(TAG_EXAMS);
// looping through All Products
for (int i = 0; i < exams.length(); i++) {
JSONObject c = exams.getJSONObject(i);
ContentValues values = new ContentValues();
values.put("exa_id", c.getString("exa_id"));
values.put("exa_date", c.getString("exa_date"));
values.put("tye_name", c.getString("tye_name"));
db.insert("TableExam", null, values);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//método rawQuery()
Cursor cur = db.rawQuery("SELECT exa_id, exa_date, tye_name FROM TableExam", null);
//int total = 0;
//Recorremos los resultados para mostrarlos en pantalla
txtResultado.setText("");
if (cur.moveToFirst()) {
//Recorremos el cursor hasta que no haya más registros
do {
String pos0 = cur.getString((c.getColumnIndex("exa_id")));
String pos1 = cur.getString((c.getColumnIndex("exa_date")));
String pos2 = cur.getString((c.getColumnIndex("tye_name")));
txtResultado.append(" " + pos0 + " - " + pos1 + " - " + pos2 + " \n");
} while(cur.moveToNext());
}
}
});
}
}
}
ExamsSQLiteHelper class
public class ExamsSQLiteHelper extends SQLiteOpenHelper {
//Sentencia SQL para crear la tabla de Usuarios
String sqlCreate = "CREATE TABLE TableExam (exa_id INTEGER, exa_date DATE, tye_name VARCHAR)";
public ExamsSQLiteHelper (Context contexto, String nombre,
CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//Se ejecuta la sentencia SQL de creación de la tabla
db.execSQL(sqlCreate);
}
@Override
public void onUpgrade(SQLiteDatabase db, int versionAnterior,
int versionNueva) {
//NOTA: Por simplicidad del ejemplo aquí utilizamos directamente
// la opción de eliminar la tabla anterior y crearla de nuevo
// vacía con el nuevo formato.
// Sin embargo lo normal será que haya que migrar datos de la
// tabla antigua a la nueva, por lo que este método debería
// ser más elaborado.
//Se elimina la versión anterior de la tabla
db.execSQL("DROP TABLE IF EXISTS TableExam");
//Se crea la nueva versión de la tabla
db.execSQL(sqlCreate);
}
}
Aucun commentaire:
Enregistrer un commentaire