Because I do not have access to the activity- AndroidStudio

1

I'm doing a calendar-type application for a challenge, when I tried it I realized that I did not have access as I should to the activity that would be responsible for showing the events of a day. I put the code of the main activity and to see the events of a day, I think the error is when I create a Bundle object to collect the data although I see it well. Thanks for your help. MainActivity:

package com.alumno.calendario;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CalendarView;

public class MainActivity extends AppCompatActivity implements  
CalendarView.OnDateChangeListener{


private CalendarView calendarview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    calendarview= findViewById(R.id.calendarView);
    calendarview.setOnDateChangeListener(this);
}
// este método saltara cuando se cambie las fechas en el calendario
@Override
public void onSelectedDayChange(CalendarView view, int i, int i1, int i2) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    CharSequence [] items = new CharSequence[3]; //contenerá las opciones 
que podrá escoger el usuario
    items[0]= "Agregar eventos";
    items[1]="Ver eventos";
    items[2]="Cancelar";

    final int dia,mes,anio;
    dia=i;
    mes=i1+1;// esto es por que el més empieza en cero y de esta manera se 
evita eso
    anio=i2;


    //Le ponemos título a la alerta y le ponemos las opciones más un 
escuchador de cuando presione dichas opciones
    builder.setTitle("Seleccione una opción")
        .setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                //comparamos la opción seleccionada
                if (i==0){
                    //actividad agregar eventos
                    Intent intent=new Intent( getApplication(), 
AddActivity.class);
                    Bundle bundle =new Bundle();
                    bundle.putInt("dia",dia);
                    bundle.putInt("mes",mes);
                    bundle.putInt("anio",anio);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else if (i==1){
                    //ver actividad eventos
                    Intent intent=new Intent( getApplication(), ViewEventsActivity.class);
                    Bundle bundle =new Bundle();
                    bundle.putInt("dia",dia);
                    bundle.putInt("mes",mes);
                    bundle.putInt("anio",anio);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else{
                    //selecciona cancelar y salimos del método
                    return;
                }
            }
        });

    AlertDialog dialog=builder.create();
    dialog.show();
}
}

ViewEventsActivity:

package com.alumno.calendario;

import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ViewEventsActivity extends AppCompatActivity implements 
AdapterView.OnItemLongClickListener{

//Declaramos un array el cual uaremos para leer los datos de la base de 
datos
private SQLiteDatabase db;
private ListView listView;
private ArrayAdapter<String >arrayAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_events);

    listView=findViewById(R.id.ltvListaEventos);
    //nos sirve para cuando se mantiene presionado un item en la lista y 
    para borrar elementos
    listView.setOnItemLongClickListener(this);


    Bundle bundle = getIntent().getExtras();
    int dia=0,mes=0,anio=0;
    dia= bundle.getInt("dia");
    mes= bundle.getInt("mes");
    anio= bundle.getInt("anio");

    //metemos los valores en un String para poder validar los datos en la 
    BBDD
    String cadena= dia+ " - " +mes+ " - " +anio;

    //conectamos a nuestra BBDD en modo lectura
    BDSQLite bd= new BDSQLite(getApplicationContext(),"Agenda",null,1);
    db = bd.getReadableDatabase();//modo lectura

    String sql=" select * from eventos  where fechaDesde= '"+ cadena+"'";
    //delcaramos una variable de tipod Cursor que nos servira para guardar 
    los registros que nos devuelva la consulta
    Cursor c;
    //declaramos variables temporales para almacenar los datos temporalmente
    String nombre, fechadesde,fechahasta,descripcion,ubicacion;
    try{
        //los registros que nos devuelva los guardamos  en c
        c= db.rawQuery(sql,null);
        //instanciamos el arrayAdapter
        arrayAdapter= new ArrayAdapter<String>(this, 
android.R.layout.simple_list_item_1);
        //comparamos que haya datos para leer
        if(c.moveToNext()){
            do{
                nombre=c.getString(1);
                ubicacion=c.getString(2);
                fechadesde=c.getString(3);
                fechahasta=c.getString(5);
                descripcion=c.getString(7);

                arrayAdapter.add(nombre+", "+ubicacion+", "+fechadesde+", 
"+fechahasta+", "+descripcion);
            }while (c.moveToNext());
            listView.setAdapter(arrayAdapter);
        }else{
            //si no hay datos en el cursor no mostramos la interfaz
            this.finish();
        }

    }catch (Exception e){
        Toast.makeText(getApplication(),"Error"+e.getMessage(), 
Toast.LENGTH_SHORT).show();
        //si ocurre algun error cierra la interfaz
        this.finish();
    }

}

private void eliminar(String dato){
    String[]datos=dato.split(", ");

    String sql="Delete from eventos where nombreEvento='"+datos[0]+"' and 
ubicacion='"+datos[1]+"' and fechadesde='"+datos[2]+"' and 
fechahasta='"+datos[3]+"' and descripcion='"+datos[4]+"'";
    try {
        arrayAdapter.remove(dato);
        listView.setAdapter(arrayAdapter);
        db.execSQL(sql);
        Toast.makeText(getApplication(),"Evento eliminado", 
Toast.LENGTH_SHORT).show();
    }catch (Exception e){
        Toast.makeText(getApplication(),"Error"+e.getMessage(), 
Toast.LENGTH_SHORT).show();
    }
}

@Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, 
int position, long id) {
    //agregamos un dialogo para que el usuario pueda eliminar el evento
    AlertDialog.Builder builder= new AlertDialog.Builder(this);
    CharSequence[] items = new CharSequence[1];
    items[0]="Eliminar eventos";
    items[1]="Cancelar";
    builder.setTitle("Eliminar evento")
            .setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {
                    if (i == 0) {
                        //eliminar evento
                        //le pasamos el dato que selecciona el usuario

eliminar(adapterView.getItemAtPosition(i).toString());
                    }
                }
            });
    AlertDialog dialog =builder.create();
    dialog.show();
    return false;
}
}
asked by Hello There 17.12.2018 в 09:18
source

1 answer

0

To do the Intent , use as context getApplicationContext() or ViewEventsActivity.this instead of getApplication() which is not correct:

        ...
        ...
        }else if (i==1){
            //ver actividad eventos
            Intent intent=new Intent( getApplicationContext(), ViewEventsActivity.class);
            Bundle bundle =new Bundle();
            bundle.putInt("dia",dia);
            bundle.putInt("mes",mes);
            bundle.putInt("anio",anio);
            intent.putExtras(bundle);
            startActivity(intent);
        }else{
        ...
        ...
    
answered by 18.12.2018 / 01:15
source