Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

java - Dude into an Android App which RecycleView

Hi I was developing an Android App which show a RecycleView of "Recetas", based on the time and ingredients which you have.

My problem is that the data is on an SQLite database, and I don't know how to charge the content of the Receta class, specifically the name and description of it.

Another problem is that my chackBox I don't know why but don't get Selected when you click on it, although I put the "setEnable" and "clickable" attributes to true.

Here it's the code

MainActivity.class

public class MainActivity extends AppCompatActivity {


    private LinearLayoutManager layoutManager;
    private RecyclerView scroll_resul;
    private ArrayList<Receta>listaRecetas;
    private AdminSQLiteOpenHelper admin;
    private String categoriaSelected;
    private AdapterReceta adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        layoutManager = new LinearLayoutManager(this);
        scroll_resul = findViewById(R.id.recyclerView);
        scroll_resul.setLayoutManager (layoutManager);

        categoriaSelected = "";

        admin = new AdminSQLiteOpenHelper(this);

        for (int i=0; i<scroll_resul.getChildCount(); i++){


            View vista = scroll_resul.getChildAt(i);
            final CheckBox check = (CheckBox) vista;
            if(check.getTag() != null && vista.getTag().toString().equals("opcion")) {

                check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                        if (isChecked) {
                            if (!(categoriaSelected.isEmpty())) {
                                categoriaSelected = categoriaSelected + ", " + check.getText().toString() + "'";
                            } else {
                                categoriaSelected = "'" + check.getText().toString() + "'";
                            }
                        } else {

                            categoriaSelected = categoriaSelected.replace(check.getText().toString(),
                                    "");

                        }
                        //Esto se lanza siempre
                        InstanciarCategoria(categoriaSelected);
                    }
                });
            }
        }


    }

    private List<Receta> getListRecetas(String categoria, Integer tiempo) {

        listaRecetas = new ArrayList<Receta>();
        AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this);

        SQLiteDatabase database = admin.getReadableDatabase();
        if (tiempo != null) {
            Cursor fila = database.rawQuery("select descripcion, categoria, ingredientes from recetas where categoria in (" + categoria + ") and tiempo <=" + tiempo + ";", null);

            if (fila.moveToFirst()) {
                do {
                    listaRecetas.add(new Receta(fila.getString(0), fila.getString(2)));
                } while (fila.moveToFirst());
                database.close();
            }

        }else{
            Cursor fila = database.rawQuery("select descripcion, categoria, ingredientes from recetas where categoria in (" + categoria + ";", null);

            if (fila.moveToFirst()) {
                do {
                    listaRecetas.add(new Receta(fila.getString(0), fila.getString(2)));
                } while (fila.moveToFirst());
                database.close();
            }
        }
        return listaRecetas;
    }

    public void InstanciarCategoria(String categoria){

            adapter = new AdapterReceta(getListRecetas(categoria, null), this);
            scroll_resul.setAdapter(adapter);

    }


AdaterReceta.class

public class AdapterReceta extends RecyclerView.Adapter<AdapterReceta.ViewHolder>{
    private Context context;
    private List<Receta> localDataSet;

/**
 * Provide a reference to the type of views that you are using
 * (custom ViewHolder).
 */
public static class ViewHolder extends RecyclerView.ViewHolder {
    private final TextView txtTitulo;
    private final TextView txtDescripcion;

    public ViewHolder(View view) {
        super(view);
        // Define click listener for the ViewHolder's View

        txtTitulo = (TextView) view.findViewById(R.id.txtTitulo);
        txtDescripcion = (TextView) view.findViewById(R.id.txtDescripcion);
    }

    public TextView gettxtTitulo() {
        return txtTitulo;
    }

    public TextView getTxtDescripcion() {
        return txtDescripcion;
    }
}

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public AdapterReceta(List<Receta> dataSet, Context context) {
        this.localDataSet = dataSet;
        this.context=context;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_receta, viewGroup, false);

        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.gettxtTitulo().setText(localDataSet.get(position).getNombre());
        viewHolder.getTxtDescripcion().setText(localDataSet.get(position).getDescripcion());
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.size();
    }
}


AdminSQLiteHelper.class

public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {

    // If you change the database schema, you must increment the database version.
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "Recetas.db";
    public static final String TABLE_NAME = "recetas";

    public AdminSQLiteOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
       @Override
    public void onCreate(SQLiteDatabase db) {
           db.execSQL("create table  " +TABLE_NAME+ " ( codigo integer primary key autoincrement, categoria text, descripcion text, tiempo int, ingredientes text)");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (0, 'Pasta', 'Pasta con brócoli y nueces', 30, 'macarrones, brocoli, nueces')");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (1, 'Pasta', 'Pasta con verduras al estilo caponata siciliana', 40, '400 gr de pasta, la que prefieras, 2 berenjenas, 1 cebolla, 400 gr de tomate' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (2, 'Pasta', 'Tortellinis de pasta fresca casera rellenos con carrilleras de cerdo en salsa', 30, '160 gr de harina de trigo, 4 huevos L,Pimienta negra recién molida y sal, queso parmesano rallado')");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (3, 'Pasta', 'Spaghetti a la bolo?esa', 25, '400 gr de spaghetti,300 gr de carne picada, 1 zanahoria, 1 cebolla, 100 ml de vino blanco ')");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (4, 'Arroz', 'macarrones con brócoli y nueces', 30, 'macarrones, brocoli,' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (5, 'Arroz', 'Arroz con lomo ibérico', 30, 'Pimiento rojo, 1 peque?o, Pimiento verde, 1 peque?o, 1 diente de ajo, tomate frito, lomo ibérico' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (6, 'Arroz', 'Arroz frito rápido', 30, 'arroz, aceite, agua, sal, zanahoria, puerro, salsa de soja' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (7, 'Arroz', 'Arroz redondo', 30, 'arroz, caldo, tomate, cebolla , ajo, tabasco, cilantro' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (8, 'Arroz', 'Arroz cantonés', 40, 'Arroz basmati, agua, filete de ternera, zanahoria, guisantes' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (9, 'Huevos', 'Huevos rancheros', 45, '8 ud de Tortillas de maíz, 8 huevos, tomate maduros, 2 cebollas, carne picada, pimiento rojo' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (10,'Huevos', 'Huevos revueltos con espárragos trigueros y calabacín', 50, 'calabacín, espárragos verdes trigueros, aceite, queso rallado, cebollino' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (11,'Huevos', 'Tortilla de patatas', 25, '4 patatas, 6 huevos, aceite y sal' )");
           db.execSQL("insert into recetas (codigo, categoria, descripcion, tiempo, ingredientes) values (12,'Huevos', 'Huevos fritos con pisto manchego', 15, '4 huevos,  2 cebollas, 2 tomates maduros, pimienta' )");


       }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        db.execSQL(String.format("DROP TABLE IF EXISTS%s", TABLE_NAME));
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}


Receta.class

public class Receta {

    private String nombre;
    private String descripcion;

    public Receta(String nombre, String descripcion){
        this.nombre=nombre;
        this.descripcion=descripcion;

    }

    public String getNombre() {
        return nombre;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    @Override
    public String toString() {
        return "Receta{" +
                "nombre='" + nombre + ''' +
                ", descripcion='" + descripcion + ''' +
                '}';
    }
}
````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````

I hope you can guess where the problem is, and if is like this take thanks for advance!
question from:https://s

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First thing I see in your code is that Select you are missing a parenthesis

Cursor fila = database.rawQuery("select descripcion, categoria, ingredientes from recetas where categoria in (" + categoria + ");", null);

Other one is you have a global variable for your AdminSQLiteOpenHelper and you initialise it in the onCreate() why you need to do it again in the private List<Receta> getListRecetas(...)? You can use the this.admin one.

Also, I don't get this

public void InstanciarCategoria(String categoria){
    adapter = new AdapterReceta(getListRecetas(categoria, null), this);
    scroll_resul.setAdapter(adapter);
}

What are you trying to do here? I mean, for each "categoría" you create a new AdapterReceta? Could you explain better what is your desired output? You want only one list or more? And what are you doing with CheckBox?

If you want to update your RecyclerView you do not have to create it again and set it, you can do it from start and then on every change you do something like :

adapter.setRecetas(PASS_THE_NEW_LIST_OF_RECETAS)

and inside the AdapterReceta you create a method like this :

public void setRecetas(yourList) {
  localDataSet.clear();
  localDataSet.addAll(yourList);
  notifyDataSetChanged();
}

And doing this it will update the list for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...