Problem retrieving item clicked on Listactivity and return it to previous Activity

Asked

Viewed 175 times

0

I have an Activity where I call another Activity using the startActivityForResult. In the Activity that was called, I have a list filled by products already registered. In this list, I needed to, when clicking on some of the products on the list, return the product to the previous Activity.

The problem is: by clicking on the list item, I cannot retrieve it and return it as a result for the previous Activity.

//Classe  CadPreVenda.Java 
     @Override
        public boolean onMenuItemSelected(int featureId, MenuItem item){
            switch (item.getItemId()) {
            case ADICIONAR:
                Toast.makeText(CadPreVenda.this, "Clicou em ADD", Toast.LENGTH_LONG).show();
                Log.d(TAG,"Log: Clicou em add");
                Intent i = new Intent(CadPreVenda.this, pvConsProduto.class);
                startActivityForResult(i, 1);
                return true;

            case CANCELAR:
                Toast.makeText(CadPreVenda.this, "Clicou em CANCELAR", Toast.LENGTH_LONG).show();
                Log.d(TAG,"Log: Clicou em CANCELAR");
                return true;

            case SALVAR:
                Toast.makeText(CadPreVenda.this, "Clicou em SALVAR", Toast.LENGTH_LONG).show();
                Log.d(TAG,"Log: CLICOU EM SALVAR");
                return true;
            }
            return false;
        }
//verifica se usuário confirmou a inclusão de algum item
public void onActivityResult(int requestCode, int resultCode, Intent it) {
    if(it == null){

        Context contexto = getApplicationContext();
        int duracao = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(contexto, "Atenção! Produto não incluído!",duracao); 
        toast.show();
        Log.d(TAG, "Cancelou o processo.");
        Log.d(TAG, "Erro: Processo Abortado." );

    }
    else{
        Bundle params = it !=null ? it.getExtras(): null;
        if (params != null){
            String produto = params.getString("produto");
            Log.d(TAG, "Produto Add: "+produto);
        }
    }

In this class, I load the list of products and try to return the return to the previous Activity.

package br.sysandroid;

import java.util.List;

import br.sysandroid.dao.Lcm001DAO;
import br.sysandroid.dao.ProdutoAdapter;
import br.sysandroid.dao.banco.BancoDAO;
import br.sysandroid.model.LCM001;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class pvConsProduto extends ListActivity{
    Button btPesquisar, btSair;
    private Lcm001DAO ProdutoDAO;
    List<LCM001> produtos;
    ProdutoAdapter adapter;
    BancoDAO bancoDAO;

    public static final String TAG = "LOGVENDAS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState); 
        setContentView(R.layout.consproduto);
        bancoDAO = new BancoDAO(this);

        //Código que não é relevante para o problema

        @Override
        protected void onListItemClick(ListView list, View v, int position, long id) {
            super.onListItemClick(list, v, position, id);

            try {
                Intent it = new Intent();
                it.putExtra("produto",produtos.get(position));                              
                Log.d(TAG, "Adicionando produto: "+produtos.get(position));   
                setResult(RESULT_OK,it);
                finish();
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "Algum erro aconteceu");
            } 
      }

    @Override
    protected void onResume() {
        ProdutoDAO = new Lcm001DAO(this);
        ProdutoDAO.open();
        //Lê produtos do banco
        produtos = ProdutoDAO.lerProdutos();
        //seta produtos na lista
        ListView listaProduto = (ListView) findViewById(android.R.id.list);
        //ListView listaProduto = getListView();
        adapter = new ProdutoAdapter(this, produtos);
        listaProduto.setAdapter(adapter);
        super.onResume();

    }   
}

When clicking on any of the items in the list, Log get that:

10-31 09:08:47.002: D/LOGVENDAS(1663): Adicionando produto: br.sysandroid.model.LCM001@b2e9e0a8
10-31 09:08:47.212: D/GRAVANDOLOGS(1663): Produto Add: null

And generates this warn in the Logcat:

10-31 09:08:37.232: W/Bundle(1663): Key produto expected String but value was a br.sysandroid.model.LCM001.  The default value <null> was returned.
10-31 09:08:37.322: W/Bundle(1663): Attempt to cast generated internal exception:
10-31 09:08:37.322: W/Bundle(1663): java.lang.ClassCastException: br.sysandroid.model.LCM001 cannot be cast to java.lang.String
10-31 09:08:37.322: W/Bundle(1663):     at android.os.Bundle.getString(Bundle.java:1121)
10-31 09:08:37.322: W/Bundle(1663):     at br.sysandroid.CadPreVenda.onActivityResult(CadPreVenda.java:107)
10-31 09:08:37.322: W/Bundle(1663):     at android.app.Activity.dispatchActivityResult(Activity.java:5423)
10-31 09:08:37.322: W/Bundle(1663):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3361)
10-31 09:08:37.322: W/Bundle(1663):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3408)
10-31 09:08:37.322: W/Bundle(1663):     at android.app.ActivityThread.access$1300(ActivityThread.java:135)
10-31 09:08:37.322: W/Bundle(1663):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
10-31 09:08:37.322: W/Bundle(1663):     at android.os.Handler.dispatchMessage(Handler.java:102)
10-31 09:08:37.322: W/Bundle(1663):     at android.os.Looper.loop(Looper.java:136)
10-31 09:08:37.322: W/Bundle(1663):     at android.app.ActivityThread.main(ActivityThread.java:5017)
10-31 09:08:37.322: W/Bundle(1663):     at java.lang.reflect.Method.invokeNative(Native Method)
10-31 09:08:37.322: W/Bundle(1663):     at java.lang.reflect.Method.invoke(Method.java:515)
10-31 09:08:37.322: W/Bundle(1663):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-31 09:08:37.322: W/Bundle(1663):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-31 09:08:37.322: W/Bundle(1663):     at dalvik.system.NativeStart.main(Native Method)
  • 1

    Check your code, especially where the product variable is returning a null value. This is causing the error: 10-31 09:08:37.232: W/Bundle(1663): Key product expected String but value was a br.sysandroid.model.LCM001. The default value <null> was returned. The variable expects a value of type String and is returning null.

1 answer

3


The problem is that it is recovering the value of the key "product" in the onActivityResult (CadPreVenda), and assigning to an object of the type String. Whereas in the Activity that provides that return (pvConsProduto), added a LCM001 as a value to "product".

To work change the variable that receives the value of Bundle for LCM001:

LCM001 produto = params.getString("produto");

And make sure that LCM001 be a subclass of Serializable or Parcelable.

Browser other questions tagged

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