[RESOLVIDO] Select com inner join retornando uma lista vazia - Android

Irmãos,

Boa tarde!

Criei um método para listar todos os dados referente a determinado usuário

O problema é que a minha tela de listagem está retornando em branco.

Estou utilizando INNER JOIN.

Seguem os dados.

Tabelas

Tabela Usuario


CREATE TABLE [USUARIO] (
[CDUSUARIO] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
[NMUSUARIO] VARCHAR(250) NOT NULL, 
[LOGIN] VARCHAR(250) NOT NULL, 
[SENHALOGIN] VARCHAR(250) NOT NULL, 
[SERVIDORSMTP] VARCHAR(250) NOT NULL, 
[SERVIDORPOP3] VARCHAR(250) NOT NULL, 
[EMAIL] VARCHAR(250) NOT NULL, 
[SENHAEMAIL] VARCHAR(250) NOT NULL, 
[EMAILSERVER] VARCHAR(250) NOT NULL);

Tabela Amostra



CREATE TABLE [AMOSTRA] (
[CDAMOSTRA] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
[IDAMOSTRA] VARCHAR(250), 
[IDPROCESSO] VARCHAR(250), 
[IDAUXCOLETA] INTEGER CONSTRAINT [IDAUXCOLETA] REFERENCES [COLETA]([IDAUXCOLETA]) ON DELETE RESTRICT ON UPDATE RESTRICT, 
[IDAUXPROCESSO] INTEGER, 
[IDAUXEMPRESA] INTEGER CONSTRAINT [IDAUXEMPRESA] REFERENCES [EMPRESA]([IDAUXEMPRESA]) ON DELETE RESTRICT ON UPDATE RESTRICT, 
[DTPREVISTA] DATETIME, 
[DTCOLETA] DATETIME, 
[FLCOLETADA] CHAR(1) NOT NULL, 
[DTDOWNLOAD] DATETIME, 
[DTUPLOAD] DATETIME, 
[ENDERECOCOLETA] VARCHAR(250), 
[OBSERVACAO] VARCHAR(250), 
[CDUSUARIO] INTEGER NOT NULL CONSTRAINT [CDUSUARIO] REFERENCES [USUARIO]([CDUSUARIO]) ON DELETE RESTRICT ON UPDATE RESTRICT);

Meu método Dao para listar


public List<Amostra> getLista(String usuario){
        
        
        Cursor c = getWritableDatabase().rawQuery("SELECT CDAMOSTRA, IDAMOSTRA, FLCOLETADA FROM AMOSTRA " +
                                                    "INNER JOIN USUARIO ON (AMOSTRA.CDUSUARIO = USUARIO.CDUSUARIO) "+
                                                    "WHERE USUARIO.CDUSUARIO = ?", null);
        
        
        
        List<Amostra> lista = new ArrayList<Amostra>();
        
        
        
          
                
                while(c.moveToNext()){
                    
                    Amostra amostraBean = new Amostra();
                        
                    amostraBean.setCodAmostra(c.getInt(0)); //CDAMOSTRA
                    amostraBean.setIdAmostra(c.getString(1)); //IDAMOSTRA
                    amostraBean.setFlColetada(c.getString(8)); // FLCOLETADA
                
                    lista.add(amostraBean);
            
                }
     
    
        c.close();
        return lista;

    }

ListaAmostraController


package br.com.mylims.controller;

import java.util.List;


import br.com.mylims.bean.Amostra;
import br.com.mylims.model.AmostraDao;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;



public class ListaAmostraController extends ListActivity {

    public static AmostraDao amostraDao;
    
    private List<Amostra> amostraBean;
    
    public void onCreate(Bundle icicle){
        
        super.onCreate(icicle);
        
        amostraDao = new AmostraDao(this);
        
        amostraBean = amostraDao.getLista("usuario");
        
        setListAdapter(new AmostraListAdapter(this, amostraBean));
        
        
        
    }
        
    
    public void onListItemClick(ListView l, View v, int posicao, long id){
        
        super.onListItemClick(l, v, posicao, id);
        
        /**CHAMA O METODO QUE NOS LEVARA PARA A TELA DE CADASTRO DAS INFORMACOES DAS AMOSTRAS**/
        
        cadastrarInformacoesColeta(posicao);
        
    }


    // RECUPERA O ID DA AMOSTRA E ABRE A TELA DE CADASTRO DAS INFORMACOES DAS AMOSTRAS
    private void cadastrarInformacoesColeta(int posicao) {
        
        Amostra amostBean = amostraBean.get(posicao);
        
        Intent it = new Intent(this, CadastroColetaController.class);

        it.putExtra("CDAMOSTRA", amostBean.getCodAmostra());
        
        startActivity(it);
        
    
    }
    

}

AmostraListAdapter


package br.com.mylims.controller;

import java.util.List;

import android.content.Context;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

import android.widget.TextView;
import br.com.mylims.R;
import br.com.mylims.bean.Amostra;

public class AmostraListAdapter extends BaseAdapter {

    
    private Context context;
    
    private List<Amostra> lista;
    
    private static final String CATEGORIA = "coleta";

    
    public AmostraListAdapter(Context context, List<Amostra> lista) {
        super();
        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;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        
        
        
            Amostra amostraBean = lista.get(position);
        
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            
            View view = inflater.inflate(R.layout.layout_amostra_linha_tabela, null);
            
            TextView codigoAmostra = (TextView) view.findViewById(R.id.codigoAmostra);
                        
            codigoAmostra.setText(String.valueOf(amostraBean.getCodAmostra()));
                        
            TextView idAmostra = (TextView) view.findViewById(R.id.idAmostra);
            idAmostra.setText(amostraBean.getIdAmostra());
            
            TextView flColetada = (TextView) view.findViewById(R.id.flColetada);
            flColetada.setText(amostraBean.getFlColetada());
            
            return view;
    
    }

}

Meu layout layout_amostra_linha_tabela


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

       
        
        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            
            <TextView android:text="Código" android:layout_height="wrap_content" />
            <TextView android:text="ID Amostra" android:layout_height="wrap_content" />
            <TextView android:text="Coletado?" android:layout_height="wrap_content" />
            
            
        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            
            <TextView android:id="@+id/codigoAmostra" android:layout_height="wrap_content" android:layout_width="160sp" />
            
            <TextView android:id="@+id/idAmostra" android:layout_height="wrap_content" android:layout_width="100sp" />
            
            <TextView android:id="@+id/flColetada" android:layout_height="wrap_content" android:layout_width="40sp" />
            
        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </TableRow>
    </TableLayout>

</LinearLayout>

Desde já agradeço pessoal.

nesse trecho :

public List<Amostra> getLista(String usuario){   
           
           
        Cursor c = getWritableDatabase().rawQuery("SELECT CDAMOSTRA, IDAMOSTRA, FLCOLETADA FROM AMOSTRA " +   
                                                    "INNER JOIN USUARIO ON (AMOSTRA.CDUSUARIO = USUARIO.CDUSUARIO) "+   
                                                    "WHERE USUARIO.CDUSUARIO = ?", null);   
           
           
           
        List<Amostra> lista = new ArrayList<Amostra>();   
           
           
           
             
                   
                while(c.moveToNext()){   
                       
                    Amostra amostraBean = new Amostra();   
                           
                    amostraBean.setCodAmostra(c.getInt(0)); //CDAMOSTRA   
                    amostraBean.setIdAmostra(c.getString(1)); //IDAMOSTRA   
                    amostraBean.setFlColetada(c.getString(8)); // FLCOLETADA   
                   
                    lista.add(amostraBean);   
               
                }   
       
       
        c.close();   
        return lista;   
  
    } 

você não está passando a variável “usuario” para o método getWritableDatabase().rawQuery, deve ser isto.
Aconselho a você colocar este bloco de código dentro de um try/catch para poder ver o erro.

Valeu pela força irmão.

Fiz o que vc me pediu.

Não gerou mensagem de erro e ainda continua em branco.

Atualizei da seguinte forma.

ListaAmostraController



package br.com.mylims.controller;

import java.util.List;


import br.com.mylims.bean.Amostra;
import br.com.mylims.model.AmostraDao;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;


public class ListaAmostraController extends ListActivity {

	public static AmostraDao amostraDao;
	
	private List<Amostra> amostraBean;
	
	public void onCreate(Bundle icicle){
		
		super.onCreate(icicle);
		
		amostraDao = new AmostraDao(this);
		
		amostraBean = amostraDao.getLista("CDUSUARIO");
		
		setListAdapter(new AmostraListAdapter(this, amostraBean));
		
		
		
	}
		
	
	public void onListItemClick(ListView l, View v, int posicao, long id){
		
		super.onListItemClick(l, v, posicao, id);
		
		/**CHAMA O METODO QUE NOS LEVARA PARA A TELA DE CADASTRO DAS INFORMACOES DAS AMOSTRAS**/
		
		cadastrarInformacoesColeta(posicao);
		
	}


	// RECUPERA O ID DA AMOSTRA E ABRE A TELA DE CADASTRO DAS INFORMACOES DAS AMOSTRAS
	private void cadastrarInformacoesColeta(int posicao) {
		
		Amostra amostBean = amostraBean.get(posicao);
		
		Intent it = new Intent(this, CadastroColetaController.class);

		it.putExtra("CDAMOSTRA", amostBean.getCodAmostra());
		
		startActivity(it);
		
	
	}
	

}


Meu Método.



public List<Amostra> getLista(String CDUSUARIO){
		
		//Cursor c = getWritableDatabase().query(TABELA, COLS, null, null, null, null, null);
		
		try {
			
			
			String[] args = new String[]{CDUSUARIO};
			
			Cursor c = getWritableDatabase().rawQuery("SELECT CDAMOSTRA, IDAMOSTRA, FLCOLETADA FROM AMOSTRA " +
					"INNER JOIN USUARIO ON (AMOSTRA.CDUSUARIO = USUARIO.CDUSUARIO) "+
					"WHERE USUARIO.CDUSUARIO = ?", args);



						List<Amostra> lista = new ArrayList<Amostra>();
						
						
						
								while(c.moveToNext()){
								
									Amostra amostraBean = new Amostra();
									
									amostraBean.setCodAmostra(c.getInt(0)); //CDAMOSTRA
									amostraBean.setIdAmostra(c.getString(1)); //IDAMOSTRA
									amostraBean.setFlColetada(c.getString(8)); // FLCOLETADA
									
									lista.add(amostraBean);
								
								}
						
					
						c.close();
						return lista;
						
						
						
					} catch (Exception e) {
						
						
						Log.i(CATEGORIA, "MENSAGEM DE ERRO" + e);
						
						return null;
					}
		
			
	}

Cara concertei um errinho no sql.

Agora aparece o erro do try.

Segue erro do try


12-07 19:14:10.637: I/coleta(310): MENSAGEM DE ERROandroid.database.sqlite.SQLiteException: bind or column index out of range: handle 0x26a3f8

Outro erro que aparece


12-07 19:14:10.707: E/AndroidRuntime(310): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.mylims/br.com.mylims.controller.ListaAmostraController}: java.lang.NullPointerException

Hoje está fogo cara.

na linha 29 você passa o parâmetro (amostraBean = amostraDao.getLista(“CDUSUARIO”):wink: como uma String, vi que este campo na sua tabela é um integer.
tente passando um número (ex: amostraDao.getLista(“1”)) ou caso a segunda tabela não esteja carregada troque o INNER JOIN por LEFT OUTHER JOIN.


12-07 19:14:10.637: I/coleta(310): MENSAGEM DE ERROandroid.database.sqlite.SQLiteException: bind or column index out of range: handle 0x26a3f8

Esse é por causa dessa linha:

O indice correto é 2, já que sua query definiu três campos: amostraBean.setFlColetada(c.getString(2));


12-07 19:14:10.707: E/AndroidRuntime(310): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.mylims/br.com.mylims.controller.ListaAmostraController}: java.lang.NullPointerException

Esse deve ser em virtude do anterior, altere e teste.

Fiz algumas alterações para tentar resolver.

Alterei o args para login e senha.

Segue


public List<Amostra> getLista(String login, String senha){
		
		//Cursor c = getWritableDatabase().query(TABELA, COLS, null, null, null, null, null);
		
		try {
			
			
			String[] args = new String[]{login, senha};
			
			Cursor c = getWritableDatabase().rawQuery("SELECT CDAMOSTRA, IDAMOSTRA, FLCOLETADA FROM AMOSTRA " +
					"INNER JOIN USUARIO ON (AMOSTRA.CDUSUARIO = USUARIO.CDUSUARIO) "+
					"WHERE USUARIO.LOGIN = ? AND USUARIO.SENHALOGIN = ?", args);



						List<Amostra> lista = new ArrayList<Amostra>();
						
						
						
								while(c.moveToNext()){
								
									Amostra amostraBean = new Amostra();
									
									amostraBean.setCodAmostra(c.getInt(0)); //CDAMOSTRA
									amostraBean.setIdAmostra(c.getString(1)); //IDAMOSTRA
									amostraBean.setFlColetada(c.getString(8)); // FLCOLETADA
									
									lista.add(amostraBean);
								
								}
						
					
						c.close();
						return lista;
						
						
						
					} catch (Exception e) {
						
						
						Log.i(CATEGORIA, "MENSAGEM DE ERRO" + e);
						
						return null;
					}
		
			
	}

Aqui eu atualizei.


amostraBean = amostraDao.getLista("login","senha");

Olha a mensagem agora.


12-07 19:22:21.287: I/coleta(341): MENSAGEM DE ERROjava.lang.IllegalStateException: get field slot from row 0 col 8 failed

A linha 27 amostraBean.setFlColetada(c.getString( 8 )); // FLCOLETADA tem que alterar o indice para 2;

Maravilha irmão.

Consegui resolver graças a sua ajuda.

Grande abraço cara e muito obrigado.

De nada, fico feliz em ajudar.