Bring information from one activity to another

3

My project consists of a student agenda which can have different users per device, I want to take the ID of who enters (in the login ) and pass it to my second activity ( navigation drawer ) and with this to replace the title generated by the android studio in the menu by the name of the user (looking for the id in the database, id previously supplied in the%% income), you can do a login but do not know how to load it from the database ...

SQLite.java my database ...

    public class SQLite extends SQLiteOpenHelper {

    //constructor.......
    public SQLite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }



    //aqui se crea la tabla...
    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create table usuarios (id integer primary key autoincrement, " +
                "nombre text, clave text)");

        db.execSQL("create table profesores (id integer primary key autoincrement, " +
                "nombre text, detalle text)");


        db.execSQL("create table materias (id integer primary key autoincrement, " +
                "nombre text, id_profesor integer, id_periodo integer, detalle text, " +
                "foreign key(id_profesor) references profesores (id)," +
                "foreign key(id_periodo) references periodo(id))");

        db.execSQL("create table periodo (id integer primary key autoincrement, " +
                "nombre text, id_usuario integer, fechainicio integer, fechacierre integer," +
                "foreign key(id_usuario) references usuarios(id))");

        db.execSQL("create table caracteristicas (id integer primary key autoincrement, " +
                "nombre text)");

        db.execSQL("create table asignacion (id integer primary key autoincrement, " +
                "detalle text, id_materia integer, fecha integer, id_periodo integer, id_tarea integer," +
                "foreign key(id_materia) references materias(id)," +
                "foreign key(id_periodo) references periodo(id)," +
                "foreign key(id_tarea) references tarea(id))");

        db.execSQL("create table tarea (id integer primary key autoincrement, " +
                "nombre text)");

        db.execSQL("create table caracteristica_profesor (id_profesor integer, id_caracteristica integer," +
                "foreign key(id_profesor) references profesores(id)," +
                "foreign key(id_caracteristica) references caracteristicas(id))");


        db.execSQL("insert into usuarios values('0','admin','admin')");


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("create table usuarios (id integer primary key autoincrement, " +
                "nombre text, clave text)");

        db.execSQL("create table profesores (id integer primary key autoincrement, " +
                "nombre text, detalle text)");


        db.execSQL("create table materias (id integer primary key autoincrement, " +
                "nombre text, id_profesor integer, id_periodo integer, detalle text, " +
                "foreign key(id_profesor) references profesores (id)," +
                "foreign key(id_periodo) references periodo(id))");

        db.execSQL("create table periodo (id integer primary key autoincrement, " +
                "nombre text, id_usuario integer, fechainicio integer, fechacierre integer," +
                "foreign key(id_usuario) references usuarios(id))");

        db.execSQL("create table caracteristicas (id integer primary key autoincrement, " +
                "nombre text)");

        db.execSQL("create table asignacion (id integer primary key autoincrement, " +
                "detalle text, id_materia integer, fecha integer, id_periodo integer, id_tarea integer," +
                "foreign key(id_materia) references materias(id)," +
                "foreign key(id_periodo) references periodo(id)," +
                "foreign key(id_tarea) references tarea(id))");

        db.execSQL("create table tarea (id integer primary key autoincrement, " +
                "nombre text)");

        db.execSQL("create table caracteristica_profesor (id_profesor integer, id_caracteristica integer," +
                "foreign key(id_profesor) references profesores(id)," +
                "foreign key(id_caracteristica) references caracteristicas(id))");


        db.execSQL("insert into usuarios values('0','admin','admin')");
    }
}

MainActivity.java activity which has the login

    package company.viral.organizadorjec.ActivitysPrincipales;

import android.content.DialogInterface;
import android.content.Intent;
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.EditText;
import android.widget.Toast;

import company.viral.organizadorjec.R;

//aqui empieza...
public class MainActivity extends AppCompatActivity {

    //creamos variables EditText para capturar los datos
    private EditText aetid,aetpass;
    private Cursor fila;


    //en este metodo SIEMPRE se dibuja la app correspondiente
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    //antes de dibujar definimos las variables y a quienes pertecen en el layout

        aetid = (EditText) findViewById(R.id.etid);
        aetpass = (EditText) findViewById(R.id.etpass);

    }

    //creamos los metodos con los que reaccionan los btn (onClick)
    /*metodo para entrar y buscar (en construccion.... explorando metodos)*/

    public void onClickAcepta (View view) {
        String auxn = aetid.getText().toString();
        String auxp = aetpass.getText().toString();

        SQLite admin = new SQLite(this,"administracion", null, 1);
        SQLiteDatabase bd = admin.getWritableDatabase();

        //modifique el llamado de la base de datos agregando el id
        fila=bd.rawQuery("select nombre, clave, id from usuarios where nombre='"+auxn+"'and clave='"+auxp+"'",null);



        if(fila.moveToFirst()==true){

            //capturamos los valores del cursos y lo almacenamos en variable
            String usua=fila.getString(0);
            String pass=fila.getString(1);
            //y almacenandolo en esta variable
            int id=fila.getInt(2);

            //preguntamos si los datos ingresados son iguales
            if (auxn.equals(usua)&&auxp.equals(pass)){

                //si son iguales entonces vamos a otra ventana
                //Menu es una nueva actividad empty
                Intent ven=new Intent(this,MenuCentral.class);

                //agregue el put extra aqui...----
                ven.putExtra("identificador",id);
                //--------------------------------
                startActivity(ven);

                //limpiamos las las cajas de texto
                aetid.setText("");
                aetpass.setText("");

                finish();

            }

        }else {

            Toast.makeText(getApplicationContext(), "Usuario o contraseña erroneo", Toast.LENGTH_LONG).show();
        }

        bd.close();

    }

    //metodo para entrar a la actividad de registro

    public void onClickRegistro(View view){
        Intent i = new Intent(this,Registro.class);
        startActivity(i);

        finish();
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("¿Desea Salir de la Aplicación?");
        builder.setTitle("Alerta!");
        builder.setPositiveButton("SI", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

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

// as you can see the activity capture and validate the user, what I want is to take the id of the user in question and take it to the next activity

MenuCentral.java activity that contains the central menu where my app is developed

    package company.viral.organizadorjec.ActivitysPrincipales;

import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import company.viral.organizadorjec.FragmentMenu.CaracteristicasF;
import company.viral.organizadorjec.FragmentMenu.PeriodosF;
import company.viral.organizadorjec.FracmentPopUp.ConfiguracionActividadF;
import company.viral.organizadorjec.FracmentPopUp.ConfiguracionMateriaF;
import company.viral.organizadorjec.FracmentPopUp.ConfiguracionPeriodoF;
import company.viral.organizadorjec.FracmentPopUp.ConfiguracionProfesorF;
import company.viral.organizadorjec.FragmentMenu.InicioF;
import company.viral.organizadorjec.FragmentMenu.MateriaF;
import company.viral.organizadorjec.FragmentMenu.PerfilF;
import company.viral.organizadorjec.FragmentMenu.ProfesoresF;
import company.viral.organizadorjec.R;

public class MenuCentral extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private PopupWindow popupadicion;
    private DrawerLayout posicionpopup;
    //agregue el cursor----------
    private Cursor nombreid;
    //--------------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_central);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //codigo modificado-----------------------------------------------------------------
        //teoria implementada pero no corre :S

        Bundle bundle=getIntent().getExtras();
        int identificar = bundle.getInt("identificador");

        SQLite admin = new SQLite(this,"administracion",null,1);
        SQLiteDatabase bd = admin.getWritableDatabase();

        nombreid=bd.rawQuery("select nombre from usuarios where id='"+identificar+"'",null);
        TextView correo = (TextView) findViewById(R.id.textViewcorreo);


        if (nombreid.moveToFirst()==true){
            String usuarioid=nombreid.getString(0);
            correo.setText(usuarioid);
        }
        //---------------------------------------------------------------------------------

        posicionpopup = (DrawerLayout) findViewById(R.id.drawer_layout);



        //colocamos el fragment con que inicia el menu

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.contenedor,new InicioF()).commit();


        //este es el apartado para el botonsito flotante

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {

            //metodo de escucha para el popup
            @Override
            public void onClick(View view) {

               if(popupadicion!=null){
                    popupadicion.dismiss();
               }



                //implementamos el popup
                LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                final View vistaadicion = inflater.inflate(R.layout.activity_pop_adicion,null);

                popupadicion = new PopupWindow(
                        vistaadicion, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT
                );


                //luego de clicear y abrir el popup le decimos...
                //si das al profe ve a profe
                LinearLayout btnprofe = (LinearLayout) vistaadicion.findViewById(R.id.btnagregarprofesor);
                btnprofe.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.contenedor,new ConfiguracionProfesorF()).commit();
                        popupadicion.dismiss();

                    }
                });
                //si le das actividad ve actividad
                LinearLayout btnactividad = (LinearLayout) vistaadicion.findViewById(R.id.btnagregaractividad);
                btnactividad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.contenedor,new ConfiguracionActividadF()).commit();
                        popupadicion.dismiss();

                    }
                });
                //si le das a materias ve a materias
                LinearLayout btnmaterias = (LinearLayout) vistaadicion.findViewById(R.id.btnagregarmateria);
                btnmaterias.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.contenedor,new ConfiguracionMateriaF()).commit();
                        popupadicion.dismiss();

                    }
                });
                //si le das a periodo ve a periodo
                LinearLayout btnperiodo = (LinearLayout) vistaadicion.findViewById(R.id.btnagregarperiodo);
                btnperiodo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        FragmentManager fragmentManager = getSupportFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.contenedor,new ConfiguracionPeriodoF()).commit();
                        popupadicion.dismiss();

                    }
                });
                //luego le decimos que cierre el popup con el boton

                Button cerrarboton = (Button) vistaadicion.findViewById(R.id.btnpopupcerrar);
                cerrarboton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupadicion.dismiss();
                    }
                });


                //hubicamos donde queremos el popup
                popupadicion.showAtLocation(posicionpopup, Gravity.CENTER,0,0 );
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("¿Desea Salir de la Aplicación?");
            builder.setTitle("Alerta!");
            builder.setPositiveButton("SI", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_central, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        FragmentManager fragmentManager = getSupportFragmentManager();

        if (id == R.id.nav_camera) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new InicioF()).commit();

        } else if (id == R.id.nav_gallery) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new ProfesoresF()).commit();

        } else if (id == R.id.nav_slideshow) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new PeriodosF()).commit();

        } else if (id == R.id.nav_manage) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new CaracteristicasF()).commit();

        } else if (id == R.id.nav_share) {
            fragmentManager.beginTransaction().replace(R.id.contenedor,new PerfilF()).commit();

        } else if (id == R.id.nav_send) {


        } else if (id == R.id.nav_materia){
            fragmentManager.beginTransaction().replace(R.id.contenedor,new MateriaF()).commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


}
    
asked by ERny JOsé HIdalgo COrrea 18.01.2017 в 05:40
source

3 answers

3

If the validation turns out to you and you only want to pass the id of the user with the Intent that calls the next activity, you can modify the request as:

    fila=bd.rawQuery("select nombre, clave, id from usuarios where nombre='"+auxn+"'and clave='"+auxp+"'",null);

so the third value would be the id of your user and you can add it to Intent with

intent.putExtra("id", fila.getInt(2));

and in the new activity read it with getIntExtra("id")

Now the subject of the dynamic header. change

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="[email protected]" />

for

<TextView
    android:id="@+id/textViewCabeza"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/textViewCorreo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="[email protected]" />

now you can get TextField with

TextView mTextViewCabeza = findViewById(R.id.textViewCabeza);
TextView mTextViewCorreo = findViewById(R.id.textViewCorreo);

and replace your texts according to your data obtained from the BD.

    
answered by 18.01.2017 / 06:23
source
3

I understand that what you want to do is modify the fields of your navigation drawer according to the logged in user.

Login

In your login when you get the data of your logged in user, one of the ways is to use SharedPreference

 public void setPreferences(String nombre){
    SharedPreferences preferences = MainActivity .this.getSharedPreferences("login", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    //Agregar los datos que quieras almacenar
    editor.putString("nombre", nombre);
    editor.commit();
}

Doing this send the name of the method where you are logged in.

if(fila.moveToFirst()==true){

        //capturamos los valores del cursos y lo almacenamos en variable
        String usua=fila.getString(0);
        String pass=fila.getString(1);
        //mandas a llamar el método
        setPreferences(usua);
        //preguntamos si los datos ingresados son iguales
        if (auxn.equals(usua)&&auxp.equals(pass)){

            //si son iguales entonces vamos a otra ventana
            //Menu es una nueva actividad empty
            Intent ven=new Intent(this,MenuCentral.class);


            startActivity(ven);

            //limpiamos las las cajas de texto
            aetid.setText("");
            aetpass.setText("");

            finish();

        }
}

Then in your XML nav_header_menu_central you must assign identifiers to your text boxes so that you can assign values to them.

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:id="@+id/usuario"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="[email protected]" />

Now, in your menu activity called MenuCentral In the method you should initialize your TextView and add the text obtained

protected void onCreate(Bundle savedInstanceState) {
TextView nombre = (TextView) findViewById(R.id.usuario);
TextView email = (TextView) findViewById(R.id.email);
//aqui obtenemos los datos enviados
SharedPreferences preferences = getSharedPreferences("login", Context.MODE_PRIVATE);
//para obtener es "nombre de la variable" y "valor por default"
String nombre = preferences.getString("nombre","texto default en el caso que este null");
//agregar el texto
nombre.setText(nombre);
}
    
answered by 18.01.2017 в 20:46
1

To send information from one activity to another, the intent class is used as follows.

1.In the class of the activity you want to send the information.

Intent intent = new Intent(this, activity2.class);
intent.putExtra("mensaje1", "este es mi mensaje 1 en String");
startActivity(intent);

2.In the class of the activity you want to receive the information.

Bundle bundle = getIntent().getExtras();
String mensaje = bundle.getString("mensaje1");
    
answered by 20.01.2017 в 23:31