Insert webservice data into sqlite

1

I have a webservice that returns me the following data

CodeDiscipline, Discipline, CodeTurma.

Starting from a principle that the teacher can have more than one discipline, for example,

Code Discipline: 22, Discipline: Portuguese, CodeTurma: 40

CodigoDisciplina 23 Subject: Mathematics, CodigoTurma: 40

I have a table in SQLite the same attributes as above, I need to receive this data and insert into the database. Below is the code that implemented, however the problem is that it is only by entering the last record in the case by exmplo:

CodeDiscipline: 23, Discipline: Mathematics, CodeTurma: 40

WebService Class

public class WsDisciplinas {
private static String SOAP_ACTION ="http://feol/DisciplinasProfessor";
private static String NAMESPACE = "http://feol/";
private static String METHOD_NAME= "DisciplinasProfessor";
private static String URL = "http://192.168.43.175/ServiceFeol.asmx?WSDL";

ArrayList<Disciplinas> listDisciplinas = new ArrayList<>();
Disciplinas disciplinas = new Disciplinas();

public ArrayList<Disciplinas> disciplinas(String codProfessor){

    try {
        SoapObject resposta = new SoapObject(NAMESPACE, METHOD_NAME);

            resposta.addProperty("CodigoPro", codProfessor);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(resposta);

        HttpTransportSE http = new HttpTransportSE(URL);
        http.call(SOAP_ACTION, envelope);

        String resultado = envelope.getResponse().toString();

        JSONArray jsonArray = new JSONArray(resultado);

        for(int i=0;i<jsonArray.length();i++ ) {

            JSONObject jsonObject =jsonArray.getJSONObject(i);

            disciplinas.setCodDisciplina(jsonObject.getString("CodMat"));
            disciplinas.setDisciplina(jsonObject.getString("Materia"));
            disciplinas.setCodTurma(jsonObject.getString("CodTur"));


            listDisciplinas.add(i,disciplinas);
        }
    }  catch (HttpResponseException e) {
        e.printStackTrace();
    } catch (SoapFault soapFault) {
        soapFault.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }


    return listDisciplinas;
}

}

DAO class persists data

public class DaoDisciplinas {

private SQLiteDatabase dataBase;
private BancoDados bancoDados;

public DaoDisciplinas(Context context) {bancoDados = new BancoDados(context);}
public String insereDisciplinas(ArrayList<Disciplinas> disciplinasList) {

    ContentValues valores;
    long resultado = 1;

    for (int i =0; i<disciplinasList.size();i++){
        dataBase = bancoDados.getWritableDatabase();
        valores = new ContentValues();

        valores.put("CODDISCIPLINA", disciplinasList.get(i).getCodTurma());
        valores.put("DISCIPLINA", disciplinasList.get(i).getDisciplina());
        valores.put("CODTURMA", disciplinasList.get(i).getCodTurma());


        resultado = dataBase.insertOrThrow("DISCIPLINA", null, valores);
        dataBase.close();

        valores.put("CODDISCIPLINA", disciplinasList.get(i).getCodTurma());
        valores.put("DISCIPLINA", disciplinasList.get(i).getDisciplina());
        valores.put("CODTURMA", disciplinasList.get(i).getCodTurma());

        dataBase.close();

    }
    if (resultado == -1)
        return "Erro de registro";
    else
        return "Registro Inserido com sucesso";

}

}

class of activity that performs the action of lowering the webservice and call the class dao through the ArrayList returned by the web service.

public class DisciplinaActivity extends Activity {


DaoDisciplinas daoDisciplinas = new DaoDisciplinas(this);
WsDisciplinas wsDisciplinas = new WsDisciplinas();
private Button btSincronizar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_disciplina);

btSynchronize = (Button) findViewById (R.id.btSynchronize);         btSynchronize.setOnClickListener (new View.OnClickListener () {             public void onClick (View v) {                 btSynchronizeOnClick ();

        }

    });


}

private void btSincronizarOnClick() {


    String msg = getString(R.string.dlg_msg);
    String titulo = getString(R.string.dlg_titulo);

    final ProgressDialog dialog = ProgressDialog.show(this, titulo, msg);

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                ArrayList<Disciplinas> disciplinasList = wsDisciplinas.disciplinas("101");
                daoDisciplinas.insereDisciplinas(disciplinasList);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                            Toast t = Toast.makeText(getBaseContext(), "Inserido com sucesso", Toast.LENGTH_SHORT);
                            t.show(); ///gravar na tabela
                    }
                });
            } catch (Exception e) {
            } finally {
                dialog.dismiss();
            }
        }
    }).start();


}

}

    
asked by anonymous 05.09.2016 / 18:15

1 answer

1

The problem here is this: You are allocating the SAME object in the list. Look:

Disciplinas disciplinas = new Disciplinas();
...
for(int i=0;i<jsonArray.length();i++ ) {
   ...
   disciplinas.setCodDisciplina(jsonObject.getString("CodMat"));
   disciplinas.setDisciplina(jsonObject.getString("Materia"));
   disciplinas.setCodTurma(jsonObject.getString("CodTur"));
   listDisciplinas.add(i,disciplinas);
}

You have created a discipline variable and have allocated memory to store your data using the new command. When this happens, changing the data of that object only changes the data stored in that memory address. It means that anything pointing to that memory address will be affected. In this case, the disciplines list has n references to this variable, but all of them pointing to the same memory address. Therefore only the last item added is inserted because each set in the disciplines variable overwrites the value for all references to the memory location of that variable, i.e., listDisciplines will contain 'n' items with the data of the last discipline. For you to be able to create different object disciplines and change them independently, just move the declaration of the disciplines variable into the for:

for(int i=0;i<jsonArray.length();i++ ) {
   Disciplinas disciplinas = new Disciplinas();
   disciplinas.setCodDisciplina(jsonObject.getString("CodMat"));
   disciplinas.setDisciplina(jsonObject.getString("Materia"));
   disciplinas.setCodTurma(jsonObject.getString("CodTur"));
   listDisciplinas.add(i,disciplinas);
}

Each iteration of for you constructs a different object. Thus, adding an object to the list can be done without affecting the other objects in the list. I hope I have helped ^^

    
05.09.2016 / 20:41