在Android Studio中使用SQLite的值更新mysql Row

时间:2018-09-22 03:06:16

标签: android mysql android-sqlite android-broadcastreceiver

我想制作一个Android应用,当它打开互联网连接时,它将使用本地SQLite数据库中的值更新服务器上的数据

这是我的活动代码。

public class SyncCollectActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

private CollectDataHelper dbHelper;
private ListView list;
private List<SyncCollect> syncs;
Cursor cursor;

public static final int NAME_SYNCED_WITH_SERVER = 1;
public static final int NAME_NOT_SYNCED_WITH_SERVER = 0;
public static final String DATA_SAVED_BROADCAST = "id.habatus.datasaved";

private BroadcastReceiver broadcastReceiver;
private SyncCollectAdapter adapter;
Button col, drop;
ImageButton back;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sync_collect);
    dbHelper = new CollectDataHelper(this);
    syncs = new ArrayList<>();

    list = findViewById(R.id.listViewNames);
    list.setOnItemClickListener(this);

    drop = findViewById(R.id.btncanvas);
    back = findViewById(R.id.kembali);
    loadData();
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //loading the names again
            loadData();
            refresh();

        }
    };
    registerReceiver(broadcastReceiver, new IntentFilter(DATA_SAVED_BROADCAST));


    drop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(SyncCollectActivity.this,SyncActivity.class);
            startActivity(i);
        }
    });
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(SyncCollectActivity.this,DecisionActivity.class);
            startActivity(i);
        }
    });


}

private void loadData() {
    syncs.clear();
    Cursor cursor = dbHelper.getData();
    if (cursor.moveToFirst()){
        while (cursor.moveToNext()){
            SyncCollect sync = new SyncCollect(
                    cursor.getString(cursor.getColumnIndexOrThrow("id_p")),
                    cursor.getString(cursor.getColumnIndexOrThrow("nama")),
                    cursor.getString(cursor.getColumnIndexOrThrow("alamat")),
                    cursor.getString(cursor.getColumnIndexOrThrow("saldo")),
                    cursor.getString(cursor.getColumnIndexOrThrow("pinjaman")),
                    cursor.getString(cursor.getColumnIndexOrThrow("angsuran")),
                    cursor.getString(cursor.getColumnIndexOrThrow("keterangan")),
                    cursor.getString(cursor.getColumnIndexOrThrow("latitude")),
                    cursor.getString(cursor.getColumnIndexOrThrow("longitude")),
                    cursor.getString(cursor.getColumnIndexOrThrow("status")),
                    cursor.getInt(cursor.getColumnIndexOrThrow(CollectDataHelper.syncstatus))

            );
            syncs.add(sync);
        }
    }
    adapter = new SyncCollectAdapter(this.getApplicationContext(),R.layout.sync_item2,syncs);
    list.setAdapter(adapter);

}

public void refresh(){
    adapter.notifyDataSetChanged();
}

@Override
public void onResume() {
    super.onResume();
    registerReceiver(broadcastReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}

@Override
public void onPause() {
    unregisterReceiver(broadcastReceiver);
    super.onPause();
}


@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

}
}

这是我的网址。

public static final String URL_COL_SYNC = "http://192.168.4.9/SqliteSync/colsync.php?id_p=";

该类是我将SQLite数据库中的数据更新到服务器的方法。

public class NetworkCollect  extends BroadcastReceiver {
private Context context;
private CollectDataHelper db;
@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;
    db = new CollectDataHelper(context);
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null){
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
            Cursor cursor = db.getUnsynced();
                while (cursor.moveToNext()){
                    save(

                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.nama)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.alamat)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.saldo)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.pinjaman)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.angsuran)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.keterangan)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.latitude)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.longitude)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.status)),
                            cursor.getString(cursor.getColumnIndex(CollectDataHelper.id_p))
                    );
                }

        }
    }
}

private void save( final String nama, final String alamat,final String saldo,final String pinjaman,
                  final String angsuran, final String keterangan,final String latitude,final String longitude,final String status,final String id_p){
    StringRequest request = new StringRequest(Request.Method.POST, Konfigurasi.URL_COL_SYNC, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject obj = new JSONObject(response);
                if (!obj.getBoolean("error")) {
                    //updating the status in sqlite
                    db.updatelocal(id_p, SyncCollectActivity.NAME_SYNCED_WITH_SERVER);

                    //sending the broadcast to refresh the list
                    context.sendBroadcast(new Intent(SyncCollectActivity.DATA_SAVED_BROADCAST));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> Params = new HashMap<>();
            Params.put("nama",nama);
            Params.put("alamat",alamat);
            Params.put("saldo",saldo);
            Params.put("pinjaman",pinjaman);
            Params.put("angsuran",angsuran);
            Params.put("keterangan",keterangan);
            Params.put("latitude",latitude);
            Params.put("longitude",longitude);
            Params.put("status",status);
            Params.put("id_p",id_p);
            return Params;
        }
    };
    VolleySingleton.getInstance(context).addToRequestQueue(request);
}

}

这是我的php代码,用于更新服务器数据。

    <?php 
/*
* Database Constants
* Make sure you are putting the values according to your database here 
*/
define('DB_HOST','localhost');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME', 'user');

//Connecting to the database
$conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

//checking the successful connection
if($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//making an array to store the response
$response = array(); 

//if there is a post request move ahead 
if($_SERVER['REQUEST_METHOD']=='POST'){

 //getting the name from request 
 $id_p = $_POST['id_p'];
$nama =$_POST['nama'];
$alamat = $_POST['alamat'];
$saldo = $_POST['saldo'];
$pinjaman = $_POST['pinjaman'];
$angsuran = $_POST['angsuran'];
$keterangan = $_POST['keterangan'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$status = $_POST['status'];
//creating a statement to insert to database 
 $stmt = $conn->prepare("UPDATE collect SET nama=?, alamat=?, saldo=?, pinjaman=?, angsuran=?, keterangan=?, latitude=?, longitude=?, status=?, WHERE id_p=?");

 //binding the parameter to statement 
 $stmt->bind_param("ssssssssss", $nama,$alamat,$saldo,$pinjaman,$angsuran,$keterangan,$latitude,$longitude,$status,$id_p);

 //if data inserts successfully
 if($stmt->execute()){
 //making success response 
 $response['error'] = false; 
 $response['message'] = 'Saved successfully'; 
 }else{
 //if not making failure response 
 $response['error'] = true; 
 $response['message'] = 'Please try later';
 }

}else{
 $response['error'] = true; 
 $response['message'] = "Invalid request"; 
}

//displaying the data in json format 
echo json_encode($response);
?>  

在我的php代码中,我使用了一条准备好的语句来将数据更新到服务器。

我是根据网站上的教程制作的,但这是用于插入的,我要使其不插入而是更新。我试图对广播接收器使用intent.putextra,但是NetworkCollect类的save方法不起作用。更糟糕的是也不例外。也许有人可以帮忙吗?

我希望有人能帮助我找到解决方案。

非常感谢您。

0 个答案:

没有答案