vendredi 13 février 2015

CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 // cursor

in my application, i try to clean the table category and fill the table from the json of the central database "external db"


so i get this error, mybe the insert methode is the problem get it from, the cursor....


this my code ;



public class SplashActivity extends Activity{


// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> categoryList;
ArrayList<HashMap<String, String>> ingredientList;
ArrayList<HashMap<String, String>> stockageList;

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CATEGORYS = "category";
private static final String TAG_INGREDIENTS = "ingredient";
private static final String TAG_STOCKAGE = "stockage";

// JSONArray
JSONArray categorys= null;
JSONArray ingredients= null;
JSONArray stockages= null;

private CategorieDAO mCategorieDao;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);

this.mCategorieDao = new CategorieDAO(this);



if (isNetworkOnline(SplashActivity.this) == false) {
buildAlertMessageNoNetWork();

}else {


// Hashmap
categoryList = new ArrayList<HashMap<String, String>>();
ingredientList = new ArrayList<HashMap<String, String>>();
stockageList = new ArrayList<HashMap<String, String>>();

new LoadAllCategorys().execute();
//new LoadAllIngredient().execute();
//new LoadAllStockage().execute();

}

}



/////////test connexion////////////
public boolean isNetworkOnline(Activity a) {
boolean status=false;
try{
ConnectivityManager cm = (ConnectivityManager) a.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
status= true;
}else {
netInfo = cm.getNetworkInfo(1);
if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
status= true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return status;

}
/////////msg no network////////////
private void buildAlertMessageNoNetWork() {
final AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
builder.setMessage("No Internet connection when WiFi seems to be disabled, please sign in ?")
.setTitle("Authorization ?")
.setIcon(R.drawable.warning)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS),0);


}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();

}
});
final AlertDialog alert = builder.create();
alert.show();

}
///////////////asy methode///////////////////
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllCategorys extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SplashActivity.this);
pDialog.setMessage("Loading data from server. 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(Config.URL_GET_ALL_CATEGORY_PHP, "GET", params);

// Check your log cat for JSON reponse
Log.d("All categorys: ", json.toString());

try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
//drop old Data Base
//SQLiteDatabase db;
//new DataBaseHelper(SplashActivity.this).onUpgrade(db, DataBaseHelper.DATABASE_VERSION, DataBaseHelper.DATABASE_VERSION + 1);
mCategorieDao.clearTableSec();
mCategorieDao.clearTableCategory();
// products found
// Getting Array of Products
categorys = json.getJSONArray(TAG_CATEGORYS);

// looping through All Products
for (int i = 0; i < categorys.length(); i++) {
JSONObject c = categorys.getJSONObject(i);

// saving each json item in variable
long idcat = Integer.valueOf(c.getString("id_categorie"));
String namecat = c.getString("name_categorie");
String desccat = c.getString("description_categorie");
String pathcat = c.getString("image_categorie");

System.out.println("hhhhhhhhhhhhhhhh"+namecat);

Categorie createdCategorie = mCategorieDao.createCategorieWithId(idcat, namecat, desccat, pathcat);




}

} else {
// no category found

}
} 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 data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into local database
* */
///////////go to main///////////
new Handler().postDelayed(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
finish();
}
}, 2000);
////////////////////////////////
}
});

}

}
/////////////////////////////////////////////

}


this is the categoryDAO ;



public class CategorieDAO {

public static final String TAG = "CategorieDAO";

// Database fields
private SQLiteDatabase mDatabase;
private DataBaseHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {
DataBaseHelper.ID_COLUMN_CAT,
DataBaseHelper.NAME_COLUMN_CAT,
DataBaseHelper.DESC_COLUM_CAT,
DataBaseHelper.PATH_CAT,

};

public CategorieDAO(Context context) {
this.mContext = context;
mDbHelper = new DataBaseHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}

public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}

public void close() {
mDbHelper.close();
}

public Categorie createCategorie(String name, String desc, String path) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.NAME_COLUMN_CAT, name);
values.put(DataBaseHelper.DESC_COLUM_CAT, desc);
values.put(DataBaseHelper.PATH_CAT, path);

long insertId = mDatabase
.insert(DataBaseHelper.CATEGORIE_TABLE, null, values);
Cursor cursor = mDatabase.query(DataBaseHelper.CATEGORIE_TABLE, mAllColumns,
DataBaseHelper.ID_COLUMN_CAT + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
Categorie newCategorie = cursorToCategorie(cursor);
cursor.close();
return newCategorie;
}


public Categorie createCategorieWithId(long id, String name, String desc, String path) {
ContentValues values = new ContentValues();

values.put(DataBaseHelper.NAME_COLUMN_CAT, name);
values.put(DataBaseHelper.DESC_COLUM_CAT, desc);
values.put(DataBaseHelper.PATH_CAT, path);

long insertId = mDatabase
.insert(DataBaseHelper.CATEGORIE_TABLE, null, values);
Cursor cursor = mDatabase.query(DataBaseHelper.CATEGORIE_TABLE, mAllColumns,
DataBaseHelper.ID_COLUMN_CAT + " = " + id, null, null,
null, null);
cursor.moveToFirst();
Categorie newCategorie = cursorToCategorie(cursor);
cursor.close();
return newCategorie;
}


public void deletecategorie(Categorie categorie) {
int id = categorie.getIdCat();
// delete all employees of this company
ProduitDAO produitDao = new ProduitDAO(mContext);
List<Produit> listProduits = produitDao.getProduitsOfCategorie(id);
if (listProduits != null && !listProduits.isEmpty()) {
for (Produit e : listProduits) {
produitDao.deleteProduit(e);
}
}

System.out.println("the deleted company has the id: " + id);
mDatabase.delete(DataBaseHelper.CATEGORIE_TABLE, DataBaseHelper.ID_COLUMN_CAT
+ " = " + id, null);
}

public List<Categorie> getAllCategories() {
List<Categorie> listCategories = new ArrayList<Categorie>();

Cursor cursor = mDatabase.query(DataBaseHelper.CATEGORIE_TABLE, mAllColumns,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Categorie categorie = cursorToCategorie(cursor);
listCategories.add(categorie);
cursor.moveToNext();
}

// make sure to close the cursor
cursor.close();
}
return listCategories;
}

public Categorie getCategorieById(int id) {
Cursor cursor = mDatabase.query(DataBaseHelper.CATEGORIE_TABLE, mAllColumns,
DataBaseHelper.ID_COLUMN_CAT + " = ?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}

Categorie categorie = cursorToCategorie(cursor);
return categorie;
}

protected Categorie cursorToCategorie(Cursor cursor) {
Categorie categorie = new Categorie();
categorie.setIdCat(cursor.getInt(0));
categorie.setNameCat(cursor.getString(1));
categorie.setDescCat(cursor.getString(2));
categorie.setPathCat(cursor.getString(3));

return categorie;
}
public void loadCategories() {
Categorie c1 = new Categorie(1,"Development1", "dep1","");
Categorie c2 = new Categorie(2,"Development2", "dep2","");
Categorie c3 = new Categorie(3,"Development3", "dep3","");


List<Categorie> categories = new ArrayList<Categorie>();
categories.add(c1);
categories.add(c2);
categories.add(c3);

for (Categorie dept : categories) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.NAME_COLUMN_CAT, dept.getNameCat());
mDatabase.insert(DataBaseHelper.CATEGORIE_TABLE, null, values);
}
}

public void clearTableCategory() {
mDatabase.delete(DataBaseHelper.CATEGORIE_TABLE, null,null);
}

public void clearTableSec() {
mDatabase.delete(DataBaseHelper.SQLSEQ_TABLE, null,null);
}

}

Aucun commentaire:

Enregistrer un commentaire