Problems sending data from one Listview to another Activity

Asked

Viewed 692 times

1

Questionadapter

public class Questionaadapter extends Basepter Implements Onclicklistener {

private List<Pergunta> lista;
private Context context;

public PerguntaAdapter(Context context, List<Pergunta> lista){
    this.context = context;
    this.lista = lista;
}

@Override
public int getCount() {
    return lista.size();
}

@Override
public Object getItem(int position) {
    return lista.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

static class ViewHolder{
     TextView tvPergunta;
     Button btnSim, btnNao, btnEnviarRespostas;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;
    try{
        Pergunta pergunta = lista.get(position);

        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.modelo_questionario, null);

            viewHolder = new ViewHolder();

            viewHolder.btnSim.setOnClickListener(this);
            viewHolder.btnNao.setOnClickListener(this);

            viewHolder.tvPergunta = (TextView) convertView.findViewById(R.id.textPerguntas);
            viewHolder.btnSim = (Button) convertView.findViewById(R.id.btnSim);
            viewHolder.btnNao = (Button) convertView.findViewById(R.id.btnNao);

        }
        else{
            viewHolder = (ViewHolder) convertView.getTag();
        }
        //convertView.setTag(viewHolder);
        viewHolder.btnSim.setTag(R.layout.modelo_questionario, position);
        viewHolder.btnNao.setTag(R.layout.modelo_questionario, position);

        viewHolder.tvPergunta.setText(pergunta.getPergunta());



    }catch(Exception erro){
        Log.e("Erro", "Erro: "+erro.getStackTrace());
    }

    return convertView;
}

public void onClick(View v) {
    // Com essa posicao eh possivel saber qual pergunta ele respondeu

    int position = (Integer) v.getTag(R.layout.modelo_questionario);

    Pergunta pergunta = lista.get(position);

    // Comparo o ID da View que foi clicada com o ID do botao SIM,
    // gerando um booleano

    boolean resposta = v.getId() == R.id.btnSim;

    // Criar um campo na pergunta para armazenar a resposta
    // Ou usar um ArrayList ou SparseArray para armezar.

    pergunta.setResposta(resposta);
}

public List<Pergunta> getPerguntas() {
    return lista;
}

Activity of the questionnaire

public class Activity_questionario extends Activity {

Funcoes funcoes = new Funcoes();
String[] perguntas;
String[] id;
int posicao = 0;
int posicao2 = 0;
Activity_Login l;
public String resposta2;
public String idQues;

public void onCreate(Bundle bundle){
    super.onCreate(bundle);
    setContentView(R.layout.layout_questionario);

    l = new Activity_Login();



    //-------------------------------------------------------------------------------

    Log.i("Logar", "Entrou no evento");
    String url = "http://"+l.ip+"/projetotcc/android/questionario.php";

    String respostaRetornada = null;

    Log.i("Logar", "Vai entrar no try");

    try{
        respostaRetornada = ConexaoHttpClient.executaHttpGet(url);
        String resposta = respostaRetornada.toString();
        resposta = resposta.replaceAll("\\s+", "");
        Log.i("Perguntas", "Perguntas: "+resposta);


        char separador = '#';
        int contaPerguntas = 0;

        for (int i=0; i < resposta.length(); i++){
            if (separador == resposta.charAt(i)){
                contaPerguntas++;
                perguntas = new String[contaPerguntas];
            }
        }

        char caracterLido = resposta.charAt(0);
        String pergunta = "";

        for (int i=0; caracterLido != '^'; i++){
            caracterLido = resposta.charAt(i);
            Log.i("Chars", "Chars das perguntas"+caracterLido);

            if (caracterLido != '#'){

                //pergunta+= (char) caracterLido;
                if (caracterLido == '*'){
                    pergunta = pergunta + " ";
                }else
                    pergunta = pergunta + caracterLido;
            }else{
                Log.i("Nome", "Nome: "+pergunta);
                perguntas[posicao] =""+ pergunta;
                Log.i("Nome posição ["+posicao+"]", ""+perguntas[posicao]);
                posicao = posicao + 1;
                pergunta = "";
            }
        }
        Log.i("Fim", "Fim do for");

    }catch(Exception erro){
        Toast.makeText(getBaseContext(), "Erro: "+erro, Toast.LENGTH_LONG).show();
        Log.e("Erro", "Erro: "+erro.getStackTrace());
    }

    ListView lv = (ListView) findViewById(R.id.lvPre);

    List<Pergunta> perguntasList = new ArrayList<Pergunta>();
    Pergunta p = new Pergunta();

    for (final String k : perguntas) {
        p = new Pergunta();
        p.setPergunta(k);
        perguntasList.add(p);
    }
    lv.setAdapter(new PerguntaAdapter(this, perguntasList));

    PerguntaAdapter adapter = (PerguntaAdapter) lv.getAdapter();
    List<Pergunta> ListaPergunta = adapter.getPerguntas();

    ArrayList<Boolean> respostas = new ArrayList<Boolean>(ListaPergunta.size());

    for(Pergunta pergunta : ListaPergunta) {
        respostas.add(pergunta.getResposta());
    }

    Intent i = new Intent(this, Activity_Conf_Inicio_Ques.class);

    i.putExtra("RESPOSTAS", respostas);

    startActivity(i);

    //-------------------------------------------------------------------------------


            String url3 = "http://"+l.ip+"/projetotcc/android/parametroQuestionario.php";
            ArrayList<NameValuePair> parametrosPost3 = new ArrayList<NameValuePair>();
            parametrosPost3.add(new BasicNameValuePair("pq", Pq));

            String respostaRetornada3 = null;

            Log.i("Logar", "Vai entrar no try");

            try{
                respostaRetornada3 = ConexaoHttpClient.executaHttpPost(url3, parametrosPost3);
                idQues = respostaRetornada3.toString();
                idQues = idQues.replaceAll(" ", "*");
                idQues = idQues.replaceAll("\\s+", "");
                Log.i("Pacientes", "Id do questionario: "+idQues);

            }catch(Exception erro){
                Toast.makeText(getBaseContext(), "Erro: "+erro, Toast.LENGTH_LONG).show();
            }



    //-------------------------------------------------------------------------------


    PerguntaAdapter pr = new PerguntaAdapter(this, perguntasList);

    String urlInserirPacRes = "http://"+l.ip+"/projetotcc/android/inserirPacRes.php";
    ArrayList<NameValuePair> parametrosPost2 = new ArrayList<NameValuePair>();
    parametrosPost2.add(new BasicNameValuePair("id", resposta2));


}

}

Confirmation of the questionnaires

public class Activity_conf_home_ques extends Activity {

Button btnConfirma, btnCancela;
EditText editConfirm;
AutoCompleteTextView acPacientes2;
String[] pacientes;
String[] pacientes2;
int posicao = 0;
int posicao2 = 0;
public static int senhaDigitada2;
Activity_Login l;

public void onCreate(Bundle bundle){
    super.onCreate(bundle);
    setContentView(R.layout.layout_conf_inicio_ques);

    l = new Activity_Login();

    ArrayList<Boolean> respostas = (ArrayList<Boolean>) getIntent().getSerializableExtra("RESPOSTAS");

    Log.i("Logar", "Entrou no evento");
    String url = "http://"+l.ip+"/projetotcc/android/listarPacientes.php";

    String respostaRetornada = null;

    Log.i("Logar", "Vai entrar no try");

    try{
        respostaRetornada = ConexaoHttpClient.executaHttpGet(url);
        String resposta = respostaRetornada.toString();
        resposta = resposta.replaceAll("\\s+", "");
        Log.i("Pacientes", "Pacientes: "+resposta);         

        //-------------------------------------------------------------------------------

        char separador  = '#';
        int contaPacientes = 0;

        for (int i=0; i < resposta.length(); i++){
            if (separador == resposta.charAt(i)){
                contaPacientes++;
                pacientes  = new String[contaPacientes];
            }
        }

        char caracterLido = resposta.charAt(0);
        String nome  = "";

        for (int i=0; caracterLido != '^'; i++){
            caracterLido = resposta.charAt(i);
            Log.i("Chars", "Chars do paciente"+caracterLido);

            if (caracterLido != '#'){
                nome+= (char) caracterLido;
            }else{
                Log.i("Nome", "Nome: "+nome);
                pacientes[posicao] =""+ nome;
                Log.i("Nome posição ["+posicao+"]", ""+pacientes[posicao]);
                posicao = posicao + 1;
                nome = "";
            }
        }

    }catch(Exception erro){
        Toast.makeText(getBaseContext(), "Erro: "+erro, Toast.LENGTH_LONG).show();
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, layout.simple_dropdown_item_1line, pacientes);
    acPacientes2 = (AutoCompleteTextView) findViewById(R.id.acPacientes2);
    acPacientes2.setAdapter(adapter);


    //-------------------------------------------------------------------------------

    final Intent intent2 = new Intent(getBaseContext(), Activity_Questionario.class);
    final Intent intent = getIntent();
    final int Senha = intent.getIntExtra("senha", 0);
    Toast.makeText(getBaseContext(), "Senha: "+Senha, Toast.LENGTH_SHORT).show();

    editConfirm = (EditText) findViewById(R.id.editSenhaConfirm);

    btnConfirma = (Button) findViewById(R.id.btnConfirmarQues);
    btnConfirma.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View arg0) {
            String senhaDigitada = editConfirm.getText().toString();
            if (!(senhaDigitada.length() == 0)){
                senhaDigitada2 = Integer.parseInt(senhaDigitada);
                Log.v("???", "Valor = " + senhaDigitada2);

                if (senhaDigitada2 == Senha){
                    intent2.putExtra("paciente", acPacientes2.getText().toString());
                    startActivity(intent2);
                }
                else
                    Toast.makeText(getBaseContext(), "Senha incorreta", Toast.LENGTH_SHORT).show();

            }   
        }
    });

    btnCancela = (Button) findViewById(R.id.btnCancelarQues);
    btnCancela.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            cancelaQues();

        }
    });
}

public void cancelaQues(){
    finish();
}
  • 1

    Emerson, you can send data from a Activity to another in two ways: static variables (bad) and Itent Extras (good). Take a look at my answer to that question: http://answall.com/questions/27175/enviar-um-arraylist-de-objetos-para-uma-activity/27195#27195 that can help you get started. It would be good for you to start with some code and if you have any questions, edit this question and include the code that doesn’t work.

  • So Wakim, the problem is that when I do it this way, to send with Intent Extras, he ends up sending only from the first position......

  • Emerson, how are you building your ListView? Put your code to make it more palpable.

  • I updated the answer...

1 answer

1


There’s still plenty to be done on this one Adapter. I will try to make a general outline in the solution.

The points I will address:

  1. Lack of storage in Adapter what is the answer to each question, using the OnClickListener on the buttons, as it came to do.

  2. In the Activity you need to consult the Adapter for the answers.

  3. Send the ArrayList with the answers as Intent Extra to the other Activity.

Adapter

// O próprio Adapter é o ClickListener das views, pode mudar isso, mas fiz dessa forma por simplicidade e reducao do numero de objetos criados.
public Adapter extends BaseAdapter implements View.OnClickListener {

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        // Codigo que popula a view

        viewHolder.btnSim.setOnClickListener(this);
        viewHolder.btnNao.setOnClickListener(this);

        // Guardo na View, a posicao da lista ao qual ela se refere.
        // Sera usado depois para saber qual pergunta ele respondeu
        // A tag precisa ser um valor autogerado e unico para nao ter conflito.
        viewHolder.btnSim.setTag(R.layout.modelo_questionario, position);
        viewHolder.btnNao.setTag(R.layout.modelo_questionario, position);
    }

    @Override
    public void onClick(View v) {
        // Com essa posicao eh possivel saber qual pergunta ele respondeu
        int position = (Integer) v.getTag(R.layout.modelo_questionario);

        Pergunta pergunta = lista.get(position);

        // Comparo o ID da View que foi clicada com o ID do botao SIM,
        // gerando um booleano
        boolean resposta = v.getId() == R.id.btnSim;

        // Criar um campo na pergunta para armazenar a resposta
        // Ou usar um ArrayList ou SparseArray para armezar.
        pergunta.setResposta(resposta);
    }
}

In his Activity

// Considerando que o Adapter ja tem as respostas armazenas nas perguntas
List<Pergunta> perguntas = adapter.getPerguntas();

ArrayList<Boolean> respostas = new ArrayList<Boolean>(perguntas.size());

for(Pergunta pergunta : perguntas) {
    respostas.add(pergunta.getResposta());
}

Intent i = new Intent(this, NovaActivity.class);

i.putExtra("RESPOSTAS", respostas);

startActivity(i);

In the NovaActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Restante do codigo...

    ArrayList<Boolean> respostas = getIntent().getSerializableExtra("RESPOSTAS");

    // Usar o array
}

Of course you can pass all the questions, but then you’ll have to see in my answer in that question how to do this. Be through the interface Serializable or Parcelable.

Edit:

To get the list of Pergunta first take the instance of Adapter and then get the list through it.

PerguntaAdapter adapter = (PerguntaAdapter) lv.getAdapter();

// Criar o metodo getPerguntas para retornar a lista
List<Pergunta> perguntas = adapter.getPerguntas();
  • Guys, the discussion in the comments was spreading too thin, so moved to chat OK? You can continue there. Thank you.

  • Ah, thanks @bfavaretto, I even tried but he didn’t have enough reputation :/

Browser other questions tagged

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