I need to pass the content of the object that has the username between different classes ... I tried it with an intent but it does not work for me
User login class.
public class Login extends AppCompatActivity implements View.OnClickListener{
//URL hace referencia al fichero PHP subido en el servidor
public static final String REGISTER_URL = "http://appjerez.es/futpad/LoginUsuario.php";
public static final String KEY_NOMBRE = "nombre";
public static final String KEY_CONTRASEÑA = "password";
public EditText edLogin;
private EditText edPassword;
private Button btnLogin;
private Button btnCancelar;
private Button btnSalir;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
edLogin= (EditText) findViewById(R.id.edLogin);
edPassword = (EditText) findViewById(R.id.edPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnCancelar = (Button) findViewById(R.id.btnCancelar);
btnSalir = (Button) findViewById(R.id.btnSalir);
btnLogin.setOnClickListener(this);
//El botón Salir nos lleva al inicio de la aplicación.
btnSalir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Cuando pulsemos click en el botón realizara lo siguiente
Intent cancelar = new Intent(Login.this, MainActivity.class);
startActivity(cancelar);
//Cuando pulsemos Cancelar me mostrara un mensaje.
Toast.makeText(getApplicationContext(),
"Has pulsado Salir", Toast.LENGTH_SHORT).show();
}
});
}
private void Login(){
final String nombre = edLogin.getText().toString().trim();
final String password = edPassword.getText().toString().trim();
//Conexion con la base de datos mediante el fichero PHP alojado en el Hosting
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//La respuesta de este metodo onResponse si es cierto es "success"
if(response.trim().equals("success")){
Toast.makeText(Login.this, "Bienvenido " + nombre, Toast.LENGTH_SHORT).show();
Intent cancelar = new Intent(Login.this, MainDrawer.class);
startActivity(cancelar);
//Aqui pasamos el nombre de usuario a otra clase.
Intent login = new Intent(Login.this,MainDrawer.class);
// para enviar informacion entre Activity usamos
// el metodo putextra de las Intenciones
login.putExtra("Nombre",edLogin.getText().toString());
startActivity(login);
//Si la respuesta del método no es succes pues el usuario no existe.
//Entonces nos muestra mensaje de usuario no registrado.
}else{
Toast.makeText(Login.this, "Usuario no registrado", Toast.LENGTH_SHORT).show();
edLogin.getText().clear();
edPassword.getText().clear();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_NOMBRE,nombre);
params.put(KEY_CONTRASEÑA,password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//Metodo click en login
@Override
public void onClick(View v) {
Login();
}
}
Class where I want to bring the username:
public class MainDrawer extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, PartidosFragment.OnFragmentInteractionListener,
RssFragment.OnFragmentInteractionListener, ContactoFragment.OnFragmentInteractionListener,
InfoFragment.OnFragmentInteractionListener, DesconectarFragment.OnFragmentInteractionListener,
InicioFragment.OnFragmentInteractionListener{
private TextView txtBienvenido;
private ImageButton imageButtonAñadir;
private ImageButton imageButtonBuscar;
private ImageButton imageButtonSalir;
private ImageButton imgBtnMisPartidos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Muestra la bienvenida al usuario registrado
txtBienvenido = (TextView) findViewById(R.id.txtLogear2);
imageButtonAñadir = (ImageButton) findViewById(R.id.imageButtonAñadir);
imageButtonSalir = (ImageButton) findViewById(R.id.imageButtonSalir);
imageButtonBuscar = (ImageButton) findViewById(R.id.imageButtonBuscar);
imgBtnMisPartidos = (ImageButton) findViewById(R.id.imgBtnMisPartidos);
//Muestra la bienvenida al usuario registrado
txtBienvenido = (TextView) findViewById(R.id.txtLogear2);
//Se extrae el nombre de usuario
Intent intent = getIntent();
Bundle extraEntreActividades = intent.getExtras();
if (extraEntreActividades != null){
String texto = extraEntreActividades.getString("Nombre");
txtBienvenido.setText("Bienvenido: " + texto);
}
//Icono de menu despegable
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);
//Boton para organizar partidos
imageButtonAñadir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent añadir = new Intent(MainDrawer.this, OrganizarPartidos.class);
startActivity(añadir);
}
});
//Boton para salir de la aplicacion
imageButtonSalir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainDrawer.this);
builder.setMessage("¿Seguro que quieres salir de la aplicación?")
.setTitle("Atención!!")
.setCancelable(false)
.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setPositiveButton("Aceptar",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent salir = new Intent(MainDrawer.this, MainActivity.class);
startActivity(salir);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
//Boton para buscar partidos
imageButtonBuscar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent buscar = new Intent(MainDrawer.this, BusquedaPartidos.class);
startActivity(buscar);
}
});
//Boton para ver mis partidos
imgBtnMisPartidos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent buscar = new Intent(MainDrawer.this, MisPartidos.class);
startActivity(buscar);
}
});
}
//Lo crea automicamente main drawer
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//Lo crea automicamente main drawer
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_drawer, menu);
return true;
}
//Lo crea automicamente main drawer
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Lo crea automicamente main drawer
@SuppressWarnings("StatementWithEmptyBody")
@Override
//Menu para navegar por el menu despegable
public boolean onNavigationItemSelected(MenuItem item) {
//Declaramos id para interacion de los fragment
int id = item.getItemId();
Fragment fragment = null;
//Creamos una variable para comprobar si hemos seleccionado el fragment.
boolean FragmentSeleccionado = false;
//En cada condicional IF, indicamos los ID que modificamos en "activity_main_drawer.xml"
//Dentro de cada if indicamos lo que quiere hacer cuando pulsemos en la opcion del menú despegable
if (id == R.id.nav_inicio) {
fragment = new InicioFragment();
FragmentSeleccionado = true;
} else if (id == R.id.nav_partidos) {
fragment = new PartidosFragment();
FragmentSeleccionado = true;
} else if (id == R.id.nav_rss) {
fragment = new RssFragment();
FragmentSeleccionado = true;
} else if (id == R.id.nav_contacto) {
fragment = new ContactoFragment();
FragmentSeleccionado = true;
} else if (id == R.id.nav_info) {
fragment = new InfoFragment();
FragmentSeleccionado = true;
} else if (id == R.id.nav_desconectar) {
fragment = new DesconectarFragment();
FragmentSeleccionado = true;
}
//Con esta condicion IF indicamos que muestre el fragment seleccionado en el "content_main" pantalla inicial
if(FragmentSeleccionado){
getSupportFragmentManager().beginTransaction().replace(R.id.content_main, fragment).commit();
}
//Lo crea por defecto
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Método obligatorio para los fragment, se deja vacio
@Override
public void onFragmentInteraction(Uri uri) {
}
}