Получить данные из sqlite и попытаться вставить их в MySQL с помощью json в сервис в Android
У меня есть класс обработчика базы данных, и в этом у меня есть функция для получения данных из базы данных sq-lite. Этот код отлично работает в действии, но не работает в сервисе. Этот код не выдает никакой ошибки.
package services;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.varad.URL_OF_SERVER;
import com.example.varad.VaradSuccess;
import com.example.varad.lib.DatabaseHandler;
import com.example.varad.lib.JSONParser;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.example.varad.VaradSuccess;
public class Sync extends Service {
//strings
String id="";
String name="";
String contact="";
String occup="";
String org="";
String proptype="";
String propfur="";
String uptofloor="";
String loc="";
String pricefrom="";
String priceto="";
String property="";
String[][] aryDB = new String[5][12];
JSONObject json;
static URL_OF_SERVER os = new URL_OF_SERVER();
static String return_url = os.RETURN_URL();
private static String url_insert = return_url + "/sell.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
// Progress Dialog
private ProgressDialog pDialog;
int i=0,last_i=0,j=0;
JSONParser jsonParser = new JSONParser();
private static final String TAG = "Sync";
private static Timer timer = new Timer();
private Context ctx;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.i("Where in service","In oncreate startup");
DatabaseHandler db=new DatabaseHandler(getApplicationContext());
Log.i("Where in service","after db object createdp");
j=0;
Log.i("Where in service","after j=0");
Cursor c=db.getData();
Log.i("Where in service","after Cursor c=db.getData();");
//Note:-This code run upto here. code not goes in if statement
if(c.moveToFirst()){
Log.i("Where in service","after if(c.moveToNext()){");
do{
Log.i("Where in service","after do{");
id=c.getString(c.getColumnIndex("id"));
name=c.getString(c.getColumnIndex("name"));
contact=c.getString(c.getColumnIndex("contact"));
occup=c.getString(c.getColumnIndex("occupation"));
org=c.getString(c.getColumnIndex("organization"));
proptype=c.getString(c.getColumnIndex("proptype"));
propfur=c.getString(c.getColumnIndex("propfur"));
uptofloor=c.getString(c.getColumnIndex("uptofloor"));
loc=c.getString(c.getColumnIndex("location"));
pricefrom=c.getString(c.getColumnIndex("pricefrom"));
priceto=c.getString(c.getColumnIndex("priceto"));
property=c.getString(c.getColumnIndex("property"));
aryDB[i][0]=id;
aryDB[i][1]=name;
aryDB[i][2]=contact;
aryDB[i][3]=occup;
aryDB[i][4]=org;
aryDB[i][5]=proptype;
aryDB[i][6]=propfur;
aryDB[i][7]=uptofloor;
aryDB[i][8]=loc;
aryDB[i][9]=pricefrom;
aryDB[i][10]=priceto;
aryDB[i][11]=property;
Toast.makeText(getApplicationContext(), aryDB[i][0]+" "+aryDB[i][1]+" "+aryDB[i][2]+" "+aryDB[i][3],Toast.LENGTH_SHORT).show();
Log.i("Data=", ""+i);
i++;
}while(c.moveToNext());
last_i=i;
new addCommsell().execute();
i=0;
db.close();
}
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
class addCommsell extends AsyncTask<String, String, String> {
int success=0;
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Sync.this);
pDialog.setMessage("Inserting Details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// Building Parameters
params.add(new BasicNameValuePair("name", aryDB[j][1]));
params.add(new BasicNameValuePair("contact", aryDB[j][2]));
params.add(new BasicNameValuePair("occupation", aryDB[j][3]));
params.add(new BasicNameValuePair("organization", aryDB[j][4]));
params.add(new BasicNameValuePair("proptype", aryDB[j][5]));
params.add(new BasicNameValuePair("propfur", aryDB[j][6]));
params.add(new BasicNameValuePair("uptofloor", aryDB[j][7]));
params.add(new BasicNameValuePair("location", aryDB[j][8]));
params.add(new BasicNameValuePair("pricefrom", aryDB[j][9]));
params.add(new BasicNameValuePair("priceto", aryDB[j][10]));
params.add(new BasicNameValuePair("property", aryDB[j][11]));
json = jsonParser.makeHttpRequest(url_insert, "POST",
params);
// getting JSON Object
// Note that create product url accepts POST method
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
}
else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
j++;
if(j!=last_i){
new addCommsell().execute();
}
Toast.makeText(Sync.this, " s="+success+" j= "+ j +" last_i = "+last_i, Toast.LENGTH_SHORT).show();
Log.i("posation of post "," s="+success+" j= "+ j +" last_i = "+last_i );
return ;
}
}
}
Я использую этот код для синхронизации sq-lite с MySQL, используя JSON
веб-сервисы
1 ответ
Решение
Ваш код содержит прогресс для в Android-сервис. В Activity он работает нормально, потому что в Activity позволяет вам создавать диалог прогресса, но в сервисе вы не можете этого сделать. так что просто используйте следующий код.
package services;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.varad.URL_OF_SERVER;
import com.example.varad.VaradSuccess;
import com.example.varad.lib.DatabaseHandler;
import com.example.varad.lib.JSONParser;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.example.varad.VaradSuccess;
public class Sync extends Service {
//strings
String id="";
String name="";
String contact="";
String occup="";
String org="";
String proptype="";
String propfur="";
String uptofloor="";
String loc="";
String pricefrom="";
String priceto="";
String property="";
String[][] aryDB = new String[5][12];
JSONObject json;
static URL_OF_SERVER os = new URL_OF_SERVER();
static String return_url = os.RETURN_URL();
private static String url_insert = return_url + "/sell.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
// Progress Dialog
//private ProgressDialog pDialog;
int i=0,last_i=0,j=0;
JSONParser jsonParser = new JSONParser();
private static final String TAG = "Sync";
private static Timer timer = new Timer();
private Context ctx;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.i("Where in service","In oncreate startup");
DatabaseHandler db=new DatabaseHandler(getApplicationContext());
Log.i("Where in service","after db object createdp");
j=0;
Log.i("Where in service","after j=0");
Cursor c=db.getData();
Log.i("Where in service","after Cursor c=db.getData();");
//Note:-This code run upto here. code not goes in if statement
if(c.moveToFirst()){
Log.i("Where in service","after if(c.moveToNext()){");
do{
Log.i("Where in service","after do{");
id=c.getString(c.getColumnIndex("id"));
name=c.getString(c.getColumnIndex("name"));
contact=c.getString(c.getColumnIndex("contact"));
occup=c.getString(c.getColumnIndex("occupation"));
org=c.getString(c.getColumnIndex("organization"));
proptype=c.getString(c.getColumnIndex("proptype"));
propfur=c.getString(c.getColumnIndex("propfur"));
uptofloor=c.getString(c.getColumnIndex("uptofloor"));
loc=c.getString(c.getColumnIndex("location"));
pricefrom=c.getString(c.getColumnIndex("pricefrom"));
priceto=c.getString(c.getColumnIndex("priceto"));
property=c.getString(c.getColumnIndex("property"));
aryDB[i][0]=id;
aryDB[i][1]=name;
aryDB[i][2]=contact;
aryDB[i][3]=occup;
aryDB[i][4]=org;
aryDB[i][5]=proptype;
aryDB[i][6]=propfur;
aryDB[i][7]=uptofloor;
aryDB[i][8]=loc;
aryDB[i][9]=pricefrom;
aryDB[i][10]=priceto;
aryDB[i][11]=property;
Toast.makeText(getApplicationContext(), aryDB[i][0]+" "+aryDB[i][1]+" "+aryDB[i][2]+" "+aryDB[i][3],Toast.LENGTH_SHORT).show();
Log.i("Data=", ""+i);
i++;
}while(c.moveToNext());
last_i=i;
new addCommsell().execute();
i=0;
db.close();
}
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
class addCommsell extends AsyncTask<String, String, String> {
int success=0;
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(Sync.this);
pDialog.setMessage("Inserting Details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
*/
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// Building Parameters
params.add(new BasicNameValuePair("name", aryDB[j][1]));
params.add(new BasicNameValuePair("contact", aryDB[j][2]));
params.add(new BasicNameValuePair("occupation", aryDB[j][3]));
params.add(new BasicNameValuePair("organization", aryDB[j][4]));
params.add(new BasicNameValuePair("proptype", aryDB[j][5]));
params.add(new BasicNameValuePair("propfur", aryDB[j][6]));
params.add(new BasicNameValuePair("uptofloor", aryDB[j][7]));
params.add(new BasicNameValuePair("location", aryDB[j][8]));
params.add(new BasicNameValuePair("pricefrom", aryDB[j][9]));
params.add(new BasicNameValuePair("priceto", aryDB[j][10]));
params.add(new BasicNameValuePair("property", aryDB[j][11]));
json = jsonParser.makeHttpRequest(url_insert, "POST",
params);
// getting JSON Object
// Note that create product url accepts POST method
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
}
else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
//pDialog.dismiss();
j++;
if(j!=last_i){
new addCommsell().execute();
}
Toast.makeText(Sync.this, " s="+success+" j= "+ j +" last_i = "+last_i, Toast.LENGTH_SHORT).show();
Log.i("posation of post "," s="+success+" j= "+ j +" last_i = "+last_i );
return ;
}
}
}