Populate Jsonarray with Sqlite3 data

Asked

Viewed 38 times

1

I have a code that is to send my Android data to PHP in JSON, to save in Mysql. But I’m sending one at a time, I want this code to send one JsonArray at once.

Method that sends data by parameters to the responsible class to handle.

public void MySQL() {
    createBank = new CreateBank(this);
    connecting = createBank.getReadableDatabase();
    String[] colunas = new String[]{CHASSIII, NAVIOI, DESTINOI, PATIO, TRANSP, CHECK, HORAII, DATAII};
    Cursor c = connecting.query(TABELAMYSQL, colunas, null, null, null, null, null);

    String chassi, navio, destino, patio, transportadora, hora, data, check;
    int chassiCOluna = c.getColumnIndex(CHASSIII);
    int navioColuna = c.getColumnIndex(NAVIOI);
    int destinoColuna = c.getColumnIndex(DESTINOI);
    int patioColuna = c.getColumnIndex(PATIO);
    int transpColuna = c.getColumnIndex(TRANSP);
    int checkColuna = c.getColumnIndex(CHECK);
    int horaColuna = c.getColumnIndex(HORAII);
    int dataColuna = c.getColumnIndex(DATAII);

    if (c.getCount() > 0) {
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            chassi = c.getString(chassiCOluna);
            navio = c.getString(navioColuna);
            destino = c.getString(destinoColuna);
            patio = c.getString(patioColuna);
            transportadora = c.getString(transpColuna);
            check = c.getString(checkColuna);
            hora = c.getString(horaColuna);
            data = c.getString(dataColuna);
            Sender s = new Sender(workspaceConferente.this, urlAdress, chassi, navio, destino, patio, transportadora, data, hora, check);
            s.execute();
        }
    }else{Toast.makeText(getApplicationContext(), "O sistema já está sincronizado!", Toast.LENGTH_SHORT).show();}
    connecting.close();
}

Class Sender receiving data from the Mysql method.

package com.example.leandroramos.qualidade.MySQL;

import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.widget.Toast;

import com.example.leandroramos.qualidade.Bank.CreateBank;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;

import static com.example.leandroramos.qualidade.Bank.CreateBank.TABELAMYSQL;

public class Sender extends AsyncTask<Void,Void,String> {
    private CreateBank createBank;
    private SQLiteDatabase connecting;
    Context c;
    String urlAddress;
    String txtChassi,txtNavio,txtDestino, txtPatio, txtTransportadora, txtHora, txtData, txtCheck;

    String Echassi,Enavio,Edestino, Epatio, Etransportadora, Ehora, Edata, Echeck;

    ProgressDialog pd;

    public Sender(Context c, String urlAddress,String chassi, String navio, String destino, String patio, String transportadora, String data, String hora, String check) {
        this.c = c;
        this.urlAddress = urlAddress;

        this.txtChassi=chassi;
        this.txtNavio=navio;
        this.txtDestino=destino;
        this.txtPatio=patio;
        this.txtTransportadora=transportadora;
        this.txtHora=hora;
        this.txtData=data;
        this.txtCheck=check;

        Echassi=chassi;
        Enavio=navio;
        Edestino=destino;
        Epatio=patio;
        Etransportadora=transportadora;
        Ehora=hora;
        Edata=data;
        Echeck=check;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pd=new ProgressDialog(c);
        pd.setTitle("Enviando");
        pd.setMessage("Por favor aguarde...");
        pd.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        return this.send();
    }

    @Override
    protected void onPostExecute(String response) {
        super.onPostExecute(response);

        createBank = new CreateBank(c);
        connecting = createBank.getWritableDatabase();

        pd.dismiss();

        if(response == "Lista recebida")
        {
            //Toast.makeText(c,response,Toast.LENGTH_SHORT).show();
            connecting.execSQL("DELETE FROM "+TABELAMYSQL);

        }else
        {
            Toast.makeText(c,"Falha na conexão."+response,Toast.LENGTH_LONG).show();
        }
    }

    private String send()
    {
        HttpURLConnection con=HttpConnection.connect(urlAddress);

        if(con==null)
        {
            return null;
        }

        try
        {
            OutputStream os=con.getOutputStream();

            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            bw.write(new DataPackager(Echassi,Enavio,Edestino, Epatio, Etransportadora, Edata, Ehora, Echeck).packData());

            bw.flush();

            bw.close();
            os.close();

            int responseCode=con.getResponseCode();

            if(responseCode==con.HTTP_OK)
            {
                BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuffer response=new StringBuffer();

                String line;

                while ((line=br.readLine()) != null)
                {
                    response.append(line);
                }

                br.close();

                return response.toString();

            }else
            {

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}

Class DataPackager receiving the class data Sender, to be encapsulated.

package com.example.leandroramos.qualidade.MySQL;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;


public class DataPackager {

    String Echassi,Enavio,Edestino, Epatio, Etransportadora, Ehora, EdataReal, Echeck;

    public DataPackager(String chassi, String navio, String destino, String patio, String transportadora, String data, String hora, String check) {
        this.Echassi = chassi;
        this.Enavio = navio;
        this.Edestino = destino;
        this.Epatio = patio;
        this.Etransportadora = transportadora;
        this.Ehora = hora;
        this.EdataReal = data;
        this.Echeck = check;
    }

    public String packData()
    {
        JSONObject jo=new JSONObject();
        StringBuffer packedData=new StringBuffer();

        try
        {
            jo.put("chassi",Echassi);
            jo.put("navio",Enavio);
            jo.put("destino",Edestino);
            jo.put("patio",Epatio);
            jo.put("transportadora",Etransportadora);
            jo.put("hora",Ehora);
            jo.put("data",EdataReal);
            jo.put("check",Echeck);

            Boolean firstValue=true;

            Iterator it=jo.keys();

            do {
                String key=it.next().toString();
                String value=jo.get(key).toString();

                if(firstValue)
                {
                    firstValue=false;
                }else
                {
                    packedData.append("&");
                }

                packedData.append(URLEncoder.encode(key,"UTF-8"));
                packedData.append("=");
                packedData.append(URLEncoder.encode(value,"UTF-8"));

            }while (it.hasNext());

            return packedData.toString();

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

}

And the class HttpConnection that opens the connection.

package com.example.leandroramos.qualidade.MySQL;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpConnection {

    public static HttpURLConnection connect(String urlAddress) {

        try
        {
            URL url=new URL(urlAddress);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();

            con.setRequestMethod("POST");
            con.setConnectTimeout(3000);
            con.setReadTimeout(3000);
            con.setDoInput(true);
            con.setDoOutput(true);

            return con;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.