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 I can replace the title generated by android studio in the menu by the user's name (looking for the id in the database, id previously supplied in the entry of the login
), I know that it can be done .putextra
but I don't 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 captures and validates the user, what I want is for it to take the id of the user in question and be able to 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;
}
}
If the validation works for you and you only want to pass the one
id
of the user withIntent
whom the next activity calls, you can modify the request as:so the third value would be the id of your user and you can add it to the
Intent
conand in the new activity read it with
getIntExtra("id")
Now the matter of the dynamic header. change
by
now you can get the
TextField
withand replace their texts according to your data obtained from the BD.
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
Haciendo esto mandas a llamar el metodo en donde esta tu logueo.
Después en tu XML nav_header_menu_central deberas asignarle identificadores a tus cajas de texto para que puedas asignarle valores.
Ahora bien, en tu actividad de menu llamado MenuCentral En el metodo Debera inicializar tus
TextView
y agregarle el texto obtenidoPara enviar informacion desde una actividad a otra se utiliza la clase intent de la siguiente manera.
1.En la clase de la actividad que quieres enviar la informacion.
2.En la clase de la actividad que se deseas recibir la informacion.