Tengo un Login en el cual hay un acceso a un archivo php y hago las consultas para ingresar usando JSON.
Al ingresar se carga otro Activity en donde también uso otro JSON para consultar otra tabla y muestro los datos en un ListView.
Quisiera que al momento de hacer LOGIN también enviar el Campo del EditText "usuario" a otro archivo php para filtrar los datos que muestro en el ListView.
Este es mi código Login.java
public class Login extends AppCompatActivity {
TextView tvsesion;
private EditText email,password;
private Button sign_in_register;
private RequestQueue requestQueue;
private static final String URL = "http://xxxxxxxxxx/WebService/user_control.php";
private StringRequest request;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ctx=this;
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tvsesion = (TextView)findViewById(R.id.tvsesion);
email = (EditText)findViewById(R.id.txusuario);
password = (EditText)findViewById(R.id.txpass);
sign_in_register = (Button) findViewById(R.id.login);
comprobarPreferencias();
String font_path = "font/Harabara Mais Demo.otf";
Typeface TF = Typeface.createFromAsset(getAssets(),font_path);
tvsesion.setTypeface(TF);
requestQueue = Volley.newRequestQueue(this);
sign_in_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String nombre = email.getText().toString();
String contraseña = password.getText().toString();
PreferenciasFragment.setString(ctx, PreferenciasFragment.getKeyNombreEd(), nombre);
PreferenciasFragment.setString(ctx, PreferenciasFragment.getKeyContraseñaEd(), contraseña);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),"CORRECTO!"+jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Drawer.class));
}
else {
Toast.makeText(getApplicationContext(), "Error:" +jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> hashMap = new HashMap<String, String>();
hashMap.put("email",email.getText().toString());
hashMap.put("password",password.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
});
}
Este es mi código php para el Login
<?php
include_once 'connection.php';
class User {
private $db;
private $connection;
function __construct() {
$this -> db = new DB_Connection();
$this -> connection = $this->db->getConnection();
}
public function does_user_exist($email,$password)
{
$query = "Select * from usuarios where usuario='$email' and contrasena = '$password' ";
$result = mysqli_query($this->connection, $query);
if(mysqli_num_rows($result)>0){
$json['success'] = ' Bienvenido '.$email;
echo json_encode($json);
mysqli_close($this -> connection);
}
else{
$query = "insert into USERS (email, password) values ( '$email','$password')";
$inserted = mysqli_query($this -> connection, $query);
if($inserted == 1 ){
$json['success'] = 'Acount created';
}else{
$json['error'] = ' Usuaio o Contraseña incorrectos';
}
echo json_encode($json);
mysqli_close($this->connection);
}
}
}
$user = new User();
if(isset($_POST['email'],$_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($email) && !empty($password)){
$encrypted_password = md5($password);
$user-> does_user_exist($email,$password);
}else{
echo json_encode("you must type both inputs");
}
}
Este es el código del Fragment en donde Cargo el ListView FragmentNuevas.java
public class FragmentNuevas extends Fragment {
private OnFragmentInteractionListener mListener;
ArrayList<Product> arrayList;
ListView lv;
ProgressDialog pdialog = null;
Context context = null;
public FragmentNuevas() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_nuevas, container, false);
lv = (ListView)view.findViewById(R.id.listView);
arrayList = new ArrayList<>();
context = getActivity();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
pdialog = ProgressDialog.show(context, "", "Buscando Noticias...", true);
new ReadJSON().execute("http://xxxxxxxxxx/WebService/consultanuevas.php");
}
});
/*lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Product selectedProduct = arrayList.get(position);
Intent intent = new Intent(getActivity().getApplicationContext(), Nuevas.class);
intent.putExtra("nombre", selectedProduct.getName());
intent.putExtra("fecha", selectedProduct.getFecha());
intent.putExtra("observaciones", selectedProduct.getPrice());
intent.putExtra("folio", selectedProduct.getImage());
startActivity(intent);
}
});*/
// Inflate the layout for this fragment
return view;
}
class ReadJSON extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
@Override
protected void onPostExecute(String content) {
pdialog.dismiss();
try {
JSONArray jsonarray = new JSONArray(content);
for(int i =0;i<jsonarray.length(); i++){
JSONObject productObject = jsonarray.getJSONObject(i);
arrayList.add(new Product(
productObject.getString("nombre"),
productObject.getString("observaciones"),
productObject.getString("fecha"),
productObject.getString("folio"),
productObject.getString("lugar"),
productObject.getString("estado"),
productObject.getString("asunto")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapter adapter = new CustomListAdapter(
getActivity(), R.layout.custom_list_layout, arrayList
);
lv.setAdapter(adapter);
}
}
private static String readURL(String theUrl) {
StringBuilder content = new StringBuilder();
try {
// create a url object
URL url = new URL(theUrl);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
y este es mi código en donde obtengo el JSON de la consulta para cargar el ListView
<?php
link=mysqli_connect("localhost","xxxxxx","xxxxx","xxxxxxxx") or die("Error en la conexion" . mysqli_error($link));
$resultado = mysqli_query($link,"SELECT * FROM solicitudes WHERE estado = 'Pendiente' ORDER BY folio DESC");
while ($row = mysqli_fetch_assoc($resultado)) {
$arr[] = $row;
}
echo json_encode($arr);
?>