Insert website data into sqlite

Asked

Viewed 185 times

1

I have a webservice that returns to me the following data

Codigodisciplina, Disciplina, Codigoturma.

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

Codigodisciplina: 22, Disciplina: Portugues, Codigoturma:40

Codediscipline: 23, Discipline: Matematica, Codeclass:40

I have a table in Sqlite the same attributes above, I need to receive this data and insert in the database. Below follows the code I implemented, but the problem is that it is only inserting the last record, in this case for example:

Codediscipline: 23, Discipline: Matematica, Codeclass:40

Class of the Webservice

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";

}

}

Activity class that executes the download action from the webservice and call the dao class by passing the Arraylist returned by the webservice.

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);

btSincronizar = (Button) findViewById(R.id.btSincronizar); btSincronize.setOnClickListener(new View.Onclicklistener() { public void onClick(View v) { btSincronizarOnClick();

        }

    });


}

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();


}

}

  • Debug and see the amount you have within "disciplinesList.size()" in your DAO, and the moment you add, you can do only "disciplinesList.add(discipline)", instead of setting a position by passing the "i".

  • I am beginner in android, how do I debug?

  • In the IDE you use, (Android Studio or Eclipse), position over the line and hit Ctrl+F8, it will mark the line for debugging. And in the "Run" menu, choose "Debug app". It will run and stop on that line.

  • Friend with debugging I found the following, my Jsonobject, this correct it is with the 2 different disciplines, ie the webservice is returning correctly. The problem and in the list of disciplines it is being filled 2 times with the last discipline of Jsonobject. I will debug the line of Return

1 answer

1

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

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 created a discipline variable and allocated memory to store your data using the new command. When this happens, changing the data of that object just changes the data stored in that memory address. It means anything pointing to this memory address will be affected. In this case, the listDisciplines have 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 position of that variable, i.e., listDisciplines will contain 'n' items with the data of the last discipline. To get you to create different subjects objects and change them independently, just move the statement 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);
}

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

  • Excellent explanation.

Browser other questions tagged

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