I'm having troubles deleting rows in the sqlite database.
What I'm trying to do is getting the Id's I want to delete from the Remote Database, and then use them to delete the rows in the SQLite DataBase.
But so far is not working
Here is where I first delete the items, and then insert items if needed.
// Method to Sync MySQL to SQLite DB
public void syncSQLiteMySQLDB() {
// Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
// Show ProgressBar
prgDialog.show();
//Llamada HTTP a getdeletes.php
client.post("http://restaurantechinaimperial.com/mysqlsqlitesync/getDeletes.php", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
deleteSQLite(response);
}
});
// Make Http call to getplatos.php
client.post("http://restaurantechinaimperial.com/mysqlsqlitesync/getplatos.php", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// Hide ProgressBar
prgDialog.hide();
// Update SQLite DB with response sent by getusers.php
updateSQLite(response);
}
// When error occured
#Override
public void onFailure(int statusCode, Throwable error, String content) {
// TODO Auto-generated method stub
// Hide ProgressBar
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Recurso no encontrado", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Algo ha fallado en el servidor", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Inesperado! [Razon mas probable: El dispositivo no esta conectado a Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
Here is the method which call the method in the sqlitecontroller to delete.
public void deleteSQLite(String response){
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has deleteid
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
String id=obj.getString("Id");
controller.deletePlato(id);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is the delete method on the sqlitehelper
public void deletePlato(String deleteid){
SQLiteDatabase database = this.getWritableDatabase();
database.delete("platos", "platoId = 'deleteid'", null);
database.close();
}
Can anybody help?
Related
I'm using Volley in my android application but I'm facing a problem, I have to use volley only for async connections?
Because per example I have an 1800 record database from web service to my application I start my volley and retrieve fine but I'm inserting this records on my SQLite and when I do that my application freezy why?
I thinking volley have async methods to handle this but it freezy when I loop on a volley and insert. My dialogue stops animation and everything.
Before volley I use the Assyntask from android and never freezy my application and I'm using httpost but now I change to volley and I'm facing this issue I will share my code :
public void volleyJsonObjectRequest(String url) {
String REQUEST_TAG = "com.androidtutorialpoint.volleyJsonObjectRequest";
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Sincronizando pedidos..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
List<HashMap<String,String>> listObjectsServer = new ArrayList<>();
try {
MDAutomap controller;
controller = new MDAutomap(getActivity());
JSONArray jsonArrayPedidos = response.getJSONArray("pedidos");
if (jsonArrayPedidos != null && jsonArrayPedidos.length() > 0) {
HashMap<String, String> pedidos = new HashMap<String, String>();
for (int i = 0; i < jsonArrayPedidos.length(); i++) {
JSONObject obj = jsonArrayPedidos.getJSONObject(i);
pedidos.put("nomeusuario", obj.getString("nomeUsuario"));
pedidos.put("id", obj.getString("id"));
pedidos.put("nome", obj.getString("nome"));
pedidos.put("eventoid", obj.getString("eventoid"));
pedidos.put("descricao", obj.getString("descricao"));
pedidos.put("valor", obj.getString("valor"));
pedidos.put("veiculo", obj.getString("veiculo"));
pedidos.put("transactioncode", obj.getString("transactioncode"));
pedidos.put("referencecode", obj.getString("referencecode"));
pedidos.put("status", obj.getString("status"));
pedidos.put("flag", obj.getString("flag"));
pedidos.put("usuario", obj.getString("usuario"));
pedidos.put("created_at", obj.getString("created_at"));
pedidos.put("updated_at", obj.getString("updated_at"));
if (controller.checkPedido(pedidos.get("id"))) {
controller.updatePedido(pedidos);
}else {
controller.inserirPedido(pedidos);
}
}
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
//userMsg("Sincronizado com sucesso os pedidos.");
}else {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
//userMsg("Não existe pedidos para sincronizar.");
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
userMsg("Não foi possível fazer conexão, por favor tenta novamente.");
}
}
);
Yes it will freeze because it is getting huge data from service and inserting in Db on main UI thread . So i solved that problem by taking a async task inside volley response and it worked in my case
private void hitApiForSyncDropdownsData(final String ApiType) {
showDialog();
String jsonAsParamstr = makeJsonStr(ApiType);
JsonObjectRequest req = new JsonObjectRequest(wholeUrl, makeJsonFromStrJson(jsonAsParamstr),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString(Constant.Utils.responseCode).equals("1")) {
new ProcessJsonAsync(ApiType).execute(response, null, null);
//processing response in Async as getting heavy reponse and inserting into DB
} else {
showShortToast(response.getString(Constant.Utils.responseMessage));
dismissDialog();
}
} catch (JSONException e) {
e.printStackTrace();
dismissDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
showmsgForVolleyIfConnProb(error, context);
}
});
req = setretryPolicy(req);
AppController.getInstance().addToRequestQueue(req);
}
and that async Code would look like
private class ProcessJsonAsync extends AsyncTask<JSONObject, Void, Integer> {
String ApiType;
ProcessJsonAsync(String ApiType) {
this.ApiType = ApiType;
}
protected Integer doInBackground(JSONObject... jsonObjects) {
ArrayList<DataModel> dataModelArraylist = new ArrayList<>();
Integer insertedResult = -1;
try {
JSONObject response = jsonObjects[0];
if (response.getString(Constant.Utils.responseCode).equalsIgnoreCase("1")) {
JSONArray jsonarray = response.getJSONArray(Constant.Utils.responseObject);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
dataModelArraylist.add(new DataModel(jsonObj.getString("data1"), jsonObj.getString("data2"));
}
DataStrucTable dataStrucTable=new DataStructTable();
insertedResult=dataStrucTable.insertArrayInDb(dataModelArraylist);
//here it will insert thousands of entries in DB on background thread and will not hang your UI
}
} catch (JSONException e) {
e.printStackTrace();
}
return insertedResult;
}
#Override
protected void onPostExecute(Integer integer) {
Toast.makeText(context, integer == -1 ? "Data couldn't insert in DB" :"Data successfully inserted", Toast.LENGTH_SHORT).show();
}
}
I am using volley in my android app and i add Torrent objects to the Arraylist and it fills the list but after the program exits this method getAllDetails() the arraylist is empty..could someone please explain what is really going on???
private void getAllDetails() {
String URL = MOVIE_DETAILS_URL + movie.getId() + CAST_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject dataObject = response.getJSONObject(Keys.DATA);
JSONObject movieObject = dataObject.getJSONObject(Keys.MOVIE);
JSONArray torrentsArray = movieObject.getJSONArray(Keys.TORRENTS);
for (int i = 0; i < torrentsArray.length(); i++) {
JSONObject torrentObject = torrentsArray.getJSONObject(i);
Torrent torrent = new Torrent();
torrent.setUrl(torrentObject.getString(Keys.URL));
torrent.setSize(torrentObject.getString(Keys.SIZE));
torrent.setQuality(torrentObject.getString(Keys.QUALITY));
torrent.setSeeds(Integer.parseInt(torrentObject.getString(Keys.SEEDS)));
torrent.setPeers(Integer.parseInt(torrentObject.getString(Keys.PEERS)));
torrentList.add(torrent);
}
getTorrent();//when this method is called here the list has items on it and it works fine
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
this method uses the torrentlist arraylist to download the .torrent file
private void getTorrent() {
String mUrl = torrentList.get(0).getUrl();
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response != null) {
String name = movie.getMovie_title() + ".torrent";
File torrentDirectory = createFolder();
File file = new File(torrentDirectory, name);
FileOutputStream fos = new FileOutputStream(file);
fos.write(response);
Toast.makeText(ViewMovie.this,"Successfully Downloaded",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);
}
A quick fix you can try to pass your ArrayList to your getTorrent() function.
getTorrent(torrentList);
You will call your function like this.
private void getTorrent(ArrayList<Torrent> passedList) {
String mUrl = passedList.get(0).getUrl();
// rest of your code here
}
But you need to know that, this function will always give you the result of first torrent. Because you are getting 0 index in ArrayList. Maybe by passing index also, you can create more functional method.
In my Android application I have passed the sqlite data into remote mysql database using JSON over AsyncHttp protocol.
Now I want the data from Mysql database to SQLite database so that from server I am fetching the data and converting it to JSON.
Since server has many rows of data I need to fetch only my mobiles sqlite data so that I need to pass the variables and check if the data is mine or not rather than fetching all the users data.
How to pass the variables in the url so that while fetching only I want to search my users data and insert them to SQLITE database.
Here is my code
public void syncMySQLDBSQLite(){
// Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
// Show ProgressBar
prgDialog.show();
// Make Http call to getusers.php
client.post("http://10.0.2.2/tafapps/getuser.php", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// Hide ProgressBar
prgDialog.hide();
// Update SQLite DB with response sent by getusers.php
updateSQLite(response);
}
// When error occured
#Override
public void onFailure(int statusCode, Throwable error, String content) {
// TODO Auto-generated method stub
// Hide ProgressBar
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
public void updateSQLite(String response){
ArrayList<HashMap<String, String>> usersynclist;
usersynclist = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
Toast.makeText(getApplicationContext(), response, 5000).show();
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has userid and username
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("userId"));
System.out.println(obj.get("userName"));
db = this.openOrCreateDatabase("Hangman", MODE_PRIVATE, null);
// String id = obj.get("userId").toString();
name = obj.get("userName").toString();
email = obj.get("userEmail").toString();
phn = obj.get("userPhnum").toString();
plyd = obj.get("userPlayed").toString();
crct = obj.get("userCorrect").toString();
//Toast.makeText(getApplicationContext(), email, 5000).show();
db.execSQL("insert into scores(userName,userEmail,userPhnum,userPlayed,userCorrect)values('"+name+"','"+email+"','"+phn+"','"+plyd+"','"+crct+"')");
}
//Toast.makeText(getApplicationContext(), ""+queryValues, 5000).show();
// Inform Remote MySQL DB about the completion of Sync activity by passing Sync status of Users
updateMySQLSyncSts(gson.toJson(usersynclist));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use HTTP GET or POST requests.
GET example with parametrs:
http://example.com/tafapps/getuser.php?user=user1&user_age=21
In POST request this parametrs will be not visible inside URL and encoded instead inside request body.
You can use the parse_url() and parse_str() for parsing:
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['user'];
Or even better as I knew:
$user = $_GET['user']
PHP Manual: Predefined _GET variable
I am parsing a JSON Data with Volley library and I retrieve the data in ListView but only the last value is printed.. Here is my implementation :
public void getListElem(final Context context) {
apws = new APWSManager(context, new APWSRequestState() {
#Override
public void customURLFinishedDownload(String response) {
// TODO Auto-generated method stub
Log.i("RESPONSE LISTVIEWPARSER : ", response);
try {
JSONObject json = null;
JSONArray array = new JSONArray(response);
for (int j = 0; j < array.length(); j++) {
json = array.getJSONObject(j);
Log.i("JSONOBJECT : ", json.toString());
parseJsonItem(json);
/* myItemList = new ItemObject(json.getString("title"),
json.getString("value_out"), json.getString("picture")); */
// m_ListItem.add(myItemList);
myList.setAdapter(myAdapter);
Log.i("LISTVIEW TITLE", array.getJSONObject(j).getString("title"));
Log.i("LISTVIEW VALUE", array.getJSONObject(j).getString("value_out"));
Log.i("LISTVIEW PICTURE", array.getJSONObject(j).getString("picture"));
}
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void customURLFailedDownload(String errorMessage) {
// TODO Auto-generated method stub
Log.i("ERROR REQUEST : ", errorMessage.toString());
}
});
apws.callAPWSRequest("getnews", null, null, TypeMethod.GET, true);
}
private void parseJsonItem(JSONObject item) {
try {
ItemObject itemObject = new ItemObject(item.getString("title"), item.getString("value_out"), item.getString("picture"));
// Ici à la place tu ajoutes ton objet dans ton array
m_ListItem.add(itemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
My ListView is printed correctly but always with the same value (the last value in json). How Can I do to retrieve each value in each item of my ListView ?
Thank you guys !
This might be a simple question, but I just can't figure it out. Consider the code below:
private void getJSONData() {
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://dev.vision-is.nl/klanten/so/content.json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// TODO Auto-generated method stub
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String titleString = (String) jsonObject.get("title");
titleArray = new ArrayList<String>();
titleArray.add(titleString);
System.out.println(titleArray.get(0));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0, String arg1) {
// TODO Auto-generated method stub
System.out.println(arg1);
}
});
}
This code works and gives me the output:
01-20 13:11:48.076 31508-31508/com.soccer.soccerapp I/System.out﹕ OUTPUT: Barcelona - Real Madrid
01-20 13:11:48.076 31508-31508/com.soccer.soccerapp I/System.out﹕ OUTPUT: Ajax - Barcelona
01-20 13:11:48.077 31508-31508/com.soccer.soccerapp I/System.out﹕ OUTPUT: Manchester United - Chelsea
01-20 13:11:48.078 31508-31508/com.soccer.soccerapp I/System.out﹕ OUTPUT: Ajax - PSV
Here comes the problem! When I try to retrieve the array in the "onCreate void" the app will crash...
Code:
public class ActivitiesViewController extends Activity {
ArrayList<String> titleArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitiesviewcontroller);
getJSONData();
System.out.println(titleArray.get(0));
}
}
What is wrong with the code? I retrieve the json data. Store this data in an array and when I try to retrieve this data the app will crash.
Change your getJSONData() method like this
private ArrayList<String>() getJSONData() {
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://dev.vision-is.nl/klanten/so/content.json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// TODO Auto-generated method stub
try {
JSONArray jsonArray = new JSONArray(response);
titleArray = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String titleString = (String) jsonObject.get("title");
titleArray.add(titleString);
System.out.println(titleArray.get(0));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0, String arg1) {
// TODO Auto-generated method stub
System.out.println(arg1);
}
});
return titleArray;
}
then your activity oncreate code should be
public class ActivitiesViewController extends Activity {
ArrayList<String> titleArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitiesviewcontroller);
titleArray = getJSONData();
System.out.println(titleArray.get(0));
}
}
Since you're using an AsyncHttpClient the code to execute the network request will not execute parallel to the rest of your code.
Let's take a look at your code:
getJSONData();
System.out.println(titleArray.get(0));
This way, getJSONData() will execute, as will the System.out.println(). But the println() will (probably) give an IndexOutOfBoundsException since titleArray is still empty.
Why is it empty? The AsyncHttpClient will load the data in the background, so your ArrayList will get its content in the onSuccess of the AsyncHttpResponseHandler after the request succeeded and not right after you started the task to download your data. Calling get() will start a procedure that will not prevent the rest of your code to execute, thus the println is reading an empty array.
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://dev.vision-is.nl/klanten/so/content.json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// Process data after request succeeded
}
#Override
public void onFailure(Throwable arg0, String arg1) {
// Print error after request failed
}
});
The pattern of asynchronous methods is the way we prevent our apps from freezing or crashing, which (of course) irritates our users.
You should execute your task and then process all data whenonSuccess is called by the AsyncHttpClient to confirm that the information you asked for was successfully received. Just don't try to access data of which you're not sure you already have.
You might want to take a look here: http://developer.android.com/guide/components/processes-and-threads.html
Since you using AsyncHttpClient client = new AsyncHttpClient();.
So it is Executing the Next Statement in Asyn Manner.
i.e:It is Executing the Next statement in Parallel with Previous way
getJSONData();
System.out.println(titleArray.get(0));
Change the return of getJSONData() to ArrayList<String> from void
Now if you try to get the value at different position you can find it
Hope this could help ...