如何将所有数据从SQLite发送到Android中的服务器

时间:2019-02-27 10:39:36

标签: android sqlite

这里我正在将数据从本地数据库发送到mysql数据库服务器,但是第一行数据正在上传 谁能帮助我

在这里我正在使用模型类从sqlite获取数据并在recyclerview中显示 现在我想以阵列或任何其他方式将所有recyclerview数据发送到服务器数据库

这里从sqlite获取了6张图像,它们也直接发送到服务器而无需在UI中将setImage直接发送到服务器

先谢谢了......

活动代码

   public class FetchLocalInsuranceListActivity extends AppCompatActivity {


    protected ViewDialog viewDialog;
    private RecyclerView recyclerview;
    RequestQueue requestQueue;
    private MyCustomAdapter myCustomAdapter;
    Context context;
    DatabaseHelper database;
    List<DataModel> datamodel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fetch_local_insurance_list);
        context = this;
        datamodel = new ArrayList<DataModel>();
        viewDialog = new ViewDialog(this);
        viewDialog.setCancelable(false);

        database = new DatabaseHelper(context);
        datamodel = database.getAllSyncData();

        recyclerview = (RecyclerView) findViewById(R.id.recycler_view__local_my_insurance);
        LinearLayoutManager layoutManager = new LinearLayoutManager(FetchLocalInsuranceListActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);
        recyclerview.setHasFixedSize(true);
        myCustomAdapter = new MyCustomAdapter(datamodel);
        recyclerview.setAdapter(myCustomAdapter);


    }

    public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {

        private List<DataModel> moviesList;

        public class MyViewHolder extends RecyclerView.ViewHolder {
            public TextView farmer_name, tv_Tagging_Date, tv_insurance_id;

            protected ImageButton editButton;

            public MyViewHolder(View view) {
                super(view);

                farmer_name = view.findViewById(R.id.text_insured_name);
                tv_Tagging_Date = view.findViewById(R.id.tv_Tagging_Date);
                tv_insurance_id = view.findViewById(R.id.tv_insurance_id);
                editButton = itemView.findViewById(R.id.edit_button);
            }

        }


        public MyCustomAdapter(List<DataModel> moviesList) {
            this.moviesList = moviesList;
        }

        @Override
        public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.layout_local_insurance_list, parent, false);

            return new MyCustomAdapter.MyViewHolder(itemView);
        }

        public void clear() {
            int size = this.moviesList.size();
            if (size > 0) {
                for (int i = 0; i < size; i++) {
                    this.moviesList.remove(0);
                }

                this.notifyItemRangeRemoved(0, size);
            }
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(MyCustomAdapter.MyViewHolder holder, final int position) {


            final DataModel datum = moviesList.get(position);
            Log.e("image", datum.getAnimal_Tail_Photo() + "");

            holder.farmer_name.setText("Farmer Name : " + datum.getFarmer_name() + "");
            holder.tv_Tagging_Date.setText("Tagging Date : " + datum.getTagging_date() + "");
            holder.tv_insurance_id.setText("#SNV_INSURANCE_" + datum.getId() + "  ");
            holder.editButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editDataParticularRow(datum);
                }
            });

        }

        @Override
        public int getItemCount() {
            return moviesList.size();
        }

    }


    private void editDataParticularRow(DataModel dataModel) {
        Intent intent = new Intent(FetchLocalInsuranceListActivity.this, EditBankAndFarmerActivity.class);
        intent.putExtra("BANK_ID", dataModel.getId() + "");
        Log.e("id", dataModel.getId() + "");
        startActivity(intent);
    }

    protected final void hideProgressDialog() {
        viewDialog.dismiss();

    }

    protected void showProgressDialog() {
        viewDialog.show();
    }

    protected void showProgressDialog(String message) {

        showProgressDialog();

    }

    public void doNormalPostOperation(final int i) {
        requestQueue = Volley.newRequestQueue(FetchLocalInsuranceListActivity.this);
        final ProgressDialog progressDialog = new ProgressDialog(FetchLocalInsuranceListActivity.this);
        progressDialog.setMessage("Saving Name...");
        progressDialog.show();


        final StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://thelastoffers.com/snv/webservices/test.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();

                        database.deleteData(Integer.parseInt(datamodel.get(i).getId() + ""));

                        database.deleteAnimalData(Integer.parseInt(datamodel.get(i).getFarmer_id() + ""));


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();

                        Toast.makeText(FetchLocalInsuranceListActivity.this, "Something went Wrong.. Please Try again..", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                HashMap<String, String> params = new HashMap<String, String>();


                //    params.put("id", datamodel.get(i).getINSURANCE_ID() + "");

                // REMAINING PARAMS WITH SAME datamodel.get(i) item

                params.put("type", "insertOfflineData");

                params.put("id", datamodel.get(i).getINSURANCE_ID() + "");
                params.put("head_image_blob", String.valueOf(datamodel.get(i).getAnimal_Tag_Photo()));
                params.put("farmer_bank_hypo", datamodel.get(i).getFarmer_bank_hypo() + "");
                params.put("farmer_name", datamodel.get(i).getFarmer_name() + "");
                params.put("farmer_village", datamodel.get(i).getVillage() + "");
                params.put("farmer_taluka", datamodel.get(i).getTaluka() + "");
                params.put("farmer_district", datamodel.get(i).getDistrict() + "");
                params.put("tagging_date", datamodel.get(i).getTagging_date() + "");

                Log.e("Data", params + "");
                return params;
            }

        };

        requestQueue.add(stringRequest);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.sync_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_sync:
                for (int i = 0; i < datamodel.size(); i++) {

                    doNormalPostOperation(i);

                }

                return true;
        }
        return super.onOptionsItemSelected(item);
    }


}

数据库代码

 public List<DataModel> getAllSyncData() {
    List<DataModel> data = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT *  FROM FARMER_SYNC_TABLE LEFT JOIN ANIMAL_SYNC_TABLE ON farmer_id = new_insurane_id ORDER BY new_insurane_id DESC";
    Cursor cursor = db.rawQuery(query, null);

    Log.e("value", query + ";" + " ");

    StringBuilder stringBuffer = new StringBuilder();

    if (cursor.moveToFirst()) {
        do {

            DataModel dataModel_1 = new DataModel();

            int NEW_INSURANCE_ID_1 = cursor.getInt(cursor.getColumnIndexOrThrow("new_insurane_id"));
            String INSURANCE_ID_1 = cursor.getString(cursor.getColumnIndexOrThrow("insurance_id"));
            String INSURED_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("insured_name"));
            String BANKHYPO_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("bankhypo_name"));
            String FARMER_NAME_1 = cursor.getString(cursor.getColumnIndexOrThrow("farmer_name"));
            String VILLAGE_1 = cursor.getString(cursor.getColumnIndexOrThrow("village"));
            String TALUKA_1 = cursor.getString(cursor.getColumnIndexOrThrow("taluka"));
            String DISTRICT_1 = cursor.getString(cursor.getColumnIndexOrThrow("district"));
            String TAGGING_DATE_1 = cursor.getString(cursor.getColumnIndexOrThrow("tagging_date"));
            int NEW_ANIMAL_ID = cursor.getInt(cursor.getColumnIndexOrThrow("new_animal_id"));
            int FARMER_ID_1 = cursor.getInt(cursor.getColumnIndexOrThrow("farmer_id"));
            String TAG_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("tag_no"));
            String ANIMAL_EAR_POSITION_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_ear_position"));
            String ANIMAL_SPECIES_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_species"));
            String ANIMAL_BREED_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_breed"));
            String ANIMAL_BODY_COLOR_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_body_color"));
            String ANIMAL_SHAPE_RIGHT_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_shape_right"));
            String ANIMAL_SHAPE_LEFT_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_shape_left"));
            String ANIMAL_SWITCH_OF_TAIL_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_sitch_of_tail"));
            String AGE_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("age_years"));
            String ANIMAL_OTHER_MARKS_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("animal_other_marks"));
            String PRAG_STATUS_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("prag_status"));
            String NUMBER_OF_LACTATION_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("number_of_lactation"));
            String CURRENT_MILK_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("current_milk"));
            String SUM_INSURED_COLUMN_1 = cursor.getString(cursor.getColumnIndexOrThrow("sum_insured"));



            dataModel_1.setId(NEW_INSURANCE_ID_1);
            dataModel_1.setINSURANCE_ID(INSURANCE_ID_1);
            dataModel_1.setFarmer_insure_name(INSURED_NAME_1);
            dataModel_1.setFarmer_bank_hypo(BANKHYPO_NAME_1);
            dataModel_1.setFarmer_name(FARMER_NAME_1);
            dataModel_1.setVillage(VILLAGE_1);
            dataModel_1.setTaluka(TALUKA_1);
            dataModel_1.setDistrict(DISTRICT_1);
            dataModel_1.setTagging_date(TAGGING_DATE_1);
            dataModel_1.setAnimal_id(NEW_ANIMAL_ID);
            dataModel_1.setFarmer_id(FARMER_ID_1);
            dataModel_1.setTag_no(TAG_COLUMN_1);
            dataModel_1.setEar_position(ANIMAL_EAR_POSITION_COLUMN_1);
            dataModel_1.setAnimal_species(ANIMAL_SPECIES_COLUMN_1);
            dataModel_1.setAnimal_breed(ANIMAL_BREED_COLUMN_1);
            dataModel_1.setBody_color(ANIMAL_BODY_COLOR_COLUMN_1);
            dataModel_1.setShape_right(ANIMAL_SHAPE_RIGHT_COLUMN_1);
            dataModel_1.setShape_left(ANIMAL_SHAPE_LEFT_COLUMN_1);
            dataModel_1.setTail_switch(ANIMAL_SWITCH_OF_TAIL_COLUMN_1);
            dataModel_1.setAge(AGE_COLUMN_1);
            dataModel_1.setOther_marks(ANIMAL_OTHER_MARKS_COLUMN_1);
            dataModel_1.setPrag_status(PRAG_STATUS_COLUMN_1);
            dataModel_1.setLactations(NUMBER_OF_LACTATION_COLUMN_1);
            dataModel_1.setMilk_qty(CURRENT_MILK_COLUMN_1);
            dataModel_1.setSum_insured(SUM_INSURED_COLUMN_1);

            dataModel_1.setAnimal_Tag_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("tag_image"))));
            dataModel_1.setAnimal_Head_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("head_image"))));
            dataModel_1.setAnimal_Left_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("left_side_image"))));
            dataModel_1.setAnimal_Right_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("right_side_image"))));
            dataModel_1.setAnimal_Tail_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("tail_image"))));
            dataModel_1.setAnimal_Farmer_Photo(Utils.getBitmapFromByte(cursor.getBlob(cursor.getColumnIndex("farmer_image"))));



            stringBuffer.append(dataModel_1);
            data.add(dataModel_1);
        } while (cursor.moveToNext());
    }

    db.close();
    return data;


}

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

  1. 通过选择查询获取要发送的所有数据,并将此数据存储在数组列表中。

  2. 使用GSON库,您可以将该arraylist转换为json数据

  3. 现在,您必须创建一个API,该API接收该json数据并进行解析并将每条记录插入数据库。

  4. 在应用程序端,您必须点击该API并将json数据传递给它。

答案 1 :(得分:1)

    First you collect the Data from sqltables

    /* Collecting Information */

    public Cursor getAllData() {
       String selectQuery = "Select * from "+TABLE_MEMBER; 
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
         return cursor;
    }


    public JSONObject createJsonObject(){
        Cursor cursor = getAllData(); 
        JSONObject jobj ;
        JSONArray arr = new JSONArray();
        cursor.moveToFIrst();
        while(cursor.moveToNext()) {
            jobj = new JSONObject();
            jboj.put("Id", cursor.getInt("Id"));
            jboj.put("Name", cursor.getString("Name"));
            arr.put(jobj);
        }
        jobj = new JSONObject();
        jobj.put("data", arr);
    }


public void postJsonToServer(){
   JSONObject js = createJsonObject();
   String url = "YOUR -- Post Url";
   JsonObjectRequest jsonObjReq = new JsonObjectRequest(
        Request.Method.POST,url, js,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());

                msgResponse.setText(response.toString());
                hideProgressDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideProgressDialog();
            }
        }) {

    /**
     * Passing some request headers
     * */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
         HashMap<String, String> headers = new HashMap<String, String>();
         headers.put("Content-Type", "application/json; charset=utf-8");
        return headers;
    }
}

答案 2 :(得分:1)

这是一个简单的问题。您只在使用 使用for循环遍历所有项目,例如

for(int i=0; i<datamodel.size(); i++){
 doNormalPostOperation(i)
}

和doNormalPostOperation方法中

public void doNormalPostOperation(int i) {

  // PREVIOUS CODE
 @Override
    protected Map<String, String> getParams() {
     params.put("id", datamodel.get(i).getINSURANCE_ID() + "");

    // REMAINING PARAMS WITH SAME datamodel.get(i) item

   }
}

导致该问题的原因,并且仅发送第一项。您将需要通过所有项目 迭代 生成参数并将其发送到服务器,否则,您可以将它们组合为一个 json数组并修改代码服务器端