Hello, how are your colleagues? My question is how do I keep the session and the data of a recycler view within an activity? I have tried with sharedprefrences and it brings me the data that I store, but not the necessary data for the recycler view and does not return anything this happens when leaving and re-entering the app the shared preferences returns me the data I want but in the recycler view loses the data and does not return anything as I do so that it also maintains the reclyver view data ie that by the time I leave and open the app again I keep the data from the recycler view, it should be noted that the main idea is to have created a button to keep session in the class to log in to recover the data in the other classes and keep the session of a user open in all the application when it leaves and returns to enter the app the truth would be thank you very many friends I hope you can help me.
Login.java
public class Login extends AppCompatActivity {
// Creating EditText.
EditText Email, Password;
// Creating button;
Button LoginButton;
// Creating Volley RequestQueue.
RequestQueue requestQueue;
// Create string variable to hold the EditText Value.
String EmailHolder, PasswordHolder,md1,md2;
// Creating Progress dialog.
ProgressDialog progressDialog;
// Storing server url into String variable.
String HttpUrl = "xxxxxxxxxxxxxx";
Boolean CheckEditText;
TextView tv_register;
private RadioButton RBsesion;
private boolean isActivateRadioButton;
String ServerResponse = null ;
String TempServerResponseMatchedValue = "returnState" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initialize(); //Initialize all the widgets present in the layout
if(Preferences.obtenerPreferenceBoolean(this,Preferences.PREFERENCE_ESTADO_BUTTON_SESION)){
Intent i = new Intent(Login.this,Principal.class);
startActivity(i);
finish();
}
Email = (EditText) findViewById(R.id.editText_Email);
Password = (EditText) findViewById(R.id.editText_Password);
LoginButton = (Button) findViewById(R.id.bt_login);
RBsesion = (RadioButton) findViewById(R.id.RBSecion);
requestQueue = Volley.newRequestQueue(Login.this);
progressDialog = new ProgressDialog(Login.this);
isActivateRadioButton = RBsesion.isChecked(); //DESACTIVADO
RBsesion.setOnClickListener(new View.OnClickListener() {
//ACTIVADO
@Override
public void onClick(View v) {
if(isActivateRadioButton){
RBsesion.setChecked(false);
}
isActivateRadioButton = RBsesion.isChecked();
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CheckEditTextIsEmptyOrNot();
if (CheckEditText) {
UserLogin();
} else {
Toast.makeText(Login.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();
}
}
});
}
private void initialize() {
tv_register = (TextView) findViewById(R.id.tv_register);
}
public void UserLogin() {
progressDialog.setMessage("Please Wait");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String ServerResponse) {
progressDialog.dismiss();
try{
JSONObject jsonObject = new JSONObject(ServerResponse);
String returnState= jsonObject.getString("returnState");
String returnData= jsonObject.getString("returnData");
if(returnData=="null"){
Toast.makeText(Login.this, "Incorrect user or password", Toast.LENGTH_LONG).show();
}else{
JSONObject jsonObjecto= new JSONObject(returnData);
String gys= jsonObjecto.getString("gys");
JSONObject jsonObjectogys= new JSONObject(gys);
String seller_id=jsonObjectogys.getString("seller_id");
String shop_id=jsonObjectogys.getString("shop_id");
JSONObject jsonObjectData= new JSONObject(returnData);
Preferences.savePreferenceBoolean(Login.this,RBsesion.isChecked(),Preferences.PREFERENCE_ESTADO_BUTTON_SESION);
Preferences.savePreferendceString(Login.this,EmailHolder, PREFERENCE_USUARIO_LOGIN);
Preferences.savePreferendceString(Login.this,seller_id, PREFERENCE_SELLER_ID);
Preferences.savePreferendceString(Login.this,shop_id, PREFERENCE_SHOP_ID);
Intent intent = new Intent(Login.this, Principal.class);
Toast.makeText(getBaseContext(),"Successful session start", Toast.LENGTH_LONG).show();
intent.putExtra("UserEmailTAG",EmailHolder);
intent.putExtra("password",md1);
intent.putExtra("seller_id",seller_id);
intent.putExtra("shop_id",shop_id);
Toast.makeText(getBaseContext(),"Successful session start", Toast.LENGTH_LONG).show();
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
,
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
Toast.makeText(Login.this,"Need internet access", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
// The firs argument should be same sa your MySQL database table columns.
params.put("username", EmailHolder);
params.put("password", md1);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(Login.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
}
Principal.java (Main menu)
public class Principal extends AppCompatActivity {
TextView pedido,fecha2,fecha1;
Button logout;
NetworkImageView networkImageView;
ImageLoader imageLoader;
RequestQueue requestQueue;
String xnombre,fech1,fech2;
Calendar calendario= Calendar.getInstance();
Spinner sexo;
private Button cerrarSesion;
private String EMISOR = "";
private String EMISOR2 = "";
private String EMISOR3 = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
EMISOR = Preferences.obtenerPreferenceString(this,Preferences.PREFERENCE_USUARIO_LOGIN);
EMISOR2 = Preferences.obtenerPreferenceString(this,Preferences.PREFERENCE_SELLER_ID);
EMISOR3 = Preferences.obtenerPreferenceString(this,Preferences.PREFERENCE_SHOP_ID);
Toast.makeText(this, EMISOR, Toast.LENGTH_SHORT).show();
Toast.makeText(this, EMISOR2, Toast.LENGTH_SHORT).show();
Toast.makeText(this, EMISOR3, Toast.LENGTH_SHORT).show();
showDatePickerDialog();
showDatePickerDialog2();
showDatePickerDialog3();
showDatePickerDialog4();
cerrarSesion = (Button) findViewById(R.id.cerrarSesion);
cerrarSesion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Preferences.savePreferenceBoolean(Principal.this,false,Preferences.PREFERENCE_ESTADO_BUTTON_SESION);
Toast.makeText(Principal.this, "Logged Out Successfully", Toast.LENGTH_LONG).show();
// finish();
Intent i = new Intent(Principal.this,Login.class);
startActivity(i);
finish();
}
});
}
private void actualizarInput() {
String formatoDeFecha = "yyyy.MM.dd";
SimpleDateFormat sdf = new SimpleDateFormat(formatoDeFecha, Locale.US);
fecha1.setText(sdf.format(calendario.getTime()));
}
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
calendario.set(Calendar.YEAR, year);
calendario.set(Calendar.MONTH, monthOfYear);
calendario.set(Calendar.DAY_OF_MONTH, dayOfMonth);
actualizarInput();
}
};
private void showDatePickerDialog2()
{
// Get open DatePickerDialog button.
TextView datePickerDialogButton =(TextView) findViewById(R.id.fecha2);
datePickerDialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Create a new OnDateSetListener instance. This listener will be invoked when user click ok button in DatePickerDialog.
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
StringBuffer strBuf = new StringBuffer();
// strBuf.append("");
strBuf.append(year);
strBuf.append(".");
strBuf.append(month+1);
strBuf.append(".");
strBuf.append(dayOfMonth);
TextView datePickerValueTextView = (TextView)findViewById(R.id.fecha2);
datePickerValueTextView.setText(strBuf.toString());
}
};
// Get current year, month and day.
Calendar now = Calendar.getInstance();
int year = now.get(java.util.Calendar.YEAR);
int month = now.get(java.util.Calendar.MONTH);
int day = now.get(java.util.Calendar.DAY_OF_MONTH);
// Create the new DatePickerDialog instance.
DatePickerDialog datePickerDialog = new DatePickerDialog(Principal.this, android.R.style.Theme_Holo_Light_Dialog, onDateSetListener, year, month, day);
datePickerDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
datePickerDialog.setButton(DatePickerDialog.BUTTON_POSITIVE, "确定", datePickerDialog);
datePickerDialog.setButton(DatePickerDialog.BUTTON_NEGATIVE, "取消", (DialogInterface.OnClickListener)null);
// datePickerDialog.setIcon(R.drawable.ic_001_busqueda);
datePickerDialog.setTitle("月 日 年");
// Popup the dialog.
datePickerDialog.show();
}
});
}
private void showDatePickerDialog()
{
// Get open DatePickerDialog button.
TextView datePickerDialogButton =(TextView) findViewById(R.id.fecha1);
datePickerDialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Create a new OnDateSetListener instance. This listener will be invoked when user click ok button in DatePickerDialog.
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
StringBuffer strBuf = new StringBuffer();
// strBuf.append("");
strBuf.append(year);
strBuf.append(".");
strBuf.append(month+1);
strBuf.append(".");
strBuf.append(dayOfMonth);
TextView datePickerValueTextView = (TextView)findViewById(R.id.fecha1);
datePickerValueTextView.setText(strBuf.toString());
}
};
// Get current year, month and day.
Calendar now = Calendar.getInstance();
int year = now.get(java.util.Calendar.YEAR);
int month = now.get(java.util.Calendar.MONTH);
int day = now.get(java.util.Calendar.DAY_OF_MONTH);
// Create the new DatePickerDialog instance.
DatePickerDialog datePickerDialog = new DatePickerDialog(Principal.this, android.R.style.Theme_Holo_Light_Dialog, onDateSetListener, year, month, day);
datePickerDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
datePickerDialog.setButton(DatePickerDialog.BUTTON_POSITIVE, "确定", datePickerDialog);
datePickerDialog.setButton(DatePickerDialog.BUTTON_NEGATIVE, "取消", (DialogInterface.OnClickListener)null);
// datePickerDialog.setIcon(R.drawable.ic_001_busqueda);
datePickerDialog.setTitle("月 日 年");
// Popup the dialog.
datePickerDialog.show();
}
});
}
private void showDatePickerDialog3()
{
// Get open DatePickerDialog button.
TextView datePickerDialogButton =(TextView) findViewById(R.id.tx2);
datePickerDialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Create a new OnDateSetListener instance. This listener will be invoked when user click ok button in DatePickerDialog.
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
StringBuffer strBuf = new StringBuffer();
// strBuf.append("");
strBuf.append(year);
strBuf.append(".");
strBuf.append(month+1);
strBuf.append(".");
strBuf.append(dayOfMonth);
TextView datePickerValueTextView = (TextView)findViewById(R.id.tx2);
datePickerValueTextView.setText(strBuf.toString());
}
};
// Get current year, month and day.
Calendar now = Calendar.getInstance();
int year = now.get(java.util.Calendar.YEAR);
int month = now.get(java.util.Calendar.MONTH);
int day = now.get(java.util.Calendar.DAY_OF_MONTH);
// Create the new DatePickerDialog instance.
DatePickerDialog datePickerDialog = new DatePickerDialog(Principal.this, android.R.style.Theme_Holo_Light_Dialog, onDateSetListener, year, month, day);
datePickerDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
datePickerDialog.setButton(DatePickerDialog.BUTTON_POSITIVE, "确定", datePickerDialog);
datePickerDialog.setButton(DatePickerDialog.BUTTON_NEGATIVE, "取消", (DialogInterface.OnClickListener)null);
// datePickerDialog.setIcon(R.drawable.ic_001_busqueda);
datePickerDialog.setTitle("月 日 年");
// Popup the dialog.
datePickerDialog.show();
}
});
}
private void showDatePickerDialog4()
{
// Get open DatePickerDialog button.
TextView datePickerDialogButton =(TextView) findViewById(R.id.tx3);
datePickerDialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Create a new OnDateSetListener instance. This listener will be invoked when user click ok button in DatePickerDialog.
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
StringBuffer strBuf = new StringBuffer();
// strBuf.append("");
strBuf.append(year);
strBuf.append(".");
strBuf.append(month+1);
strBuf.append(".");
strBuf.append(dayOfMonth);
TextView datePickerValueTextView = (TextView)findViewById(R.id.tx3);
datePickerValueTextView.setText(strBuf.toString());
}
};
// Get current year, month and day.
Calendar now = Calendar.getInstance();
int year = now.get(java.util.Calendar.YEAR);
int month = now.get(java.util.Calendar.MONTH);
int day = now.get(java.util.Calendar.DAY_OF_MONTH);
// Create the new DatePickerDialog instance.
DatePickerDialog datePickerDialog = new DatePickerDialog(Principal.this, android.R.style.Theme_Holo_Light_Dialog, onDateSetListener, year, month, day);
datePickerDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
datePickerDialog.setButton(DatePickerDialog.BUTTON_POSITIVE, "确定", datePickerDialog);
datePickerDialog.setButton(DatePickerDialog.BUTTON_NEGATIVE, "取消", (DialogInterface.OnClickListener)null);
// datePickerDialog.setIcon(R.drawable.ic_001_busqueda);
datePickerDialog.setTitle("月 日 年");
// Popup the dialog.
datePickerDialog.show();
}
});
}
// Create and show a TimePickerDialog when click button.
public void lanzarProduct (View view){
Intent i = new Intent(getApplicationContext(),Registrar_Producto.class);
i.putExtra("UserEmailTAG", getIntent().getStringExtra("UserEmailTAG"));
i.putExtra("seller_id", getIntent().getStringExtra("seller_id"));
i.putExtra("shop_id", getIntent().getStringExtra("shop_id"));
startActivity(i);
finish();
}
public void lanzarLogout (View view){
Toast.makeText(Principal.this, "Logged Out Successfully", Toast.LENGTH_LONG).show();
finish();
Intent intent = new Intent(Principal.this, Login.class);
startActivity(intent);
}
@Override
public void onBackPressed(){
AlertDialog.Builder mensaje=new AlertDialog.Builder(Principal.this);
mensaje.setTitle("¿Are you sure you want to exit?");
mensaje.setCancelable(false);
mensaje.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
mensaje.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
mensaje.show();} }
Register_Product.java (here is the problem where the recycler view is located)
public class Registrar_Producto extends AppCompatActivity implements DevelopersAdapter.ContactsAdapterListener {
private static final String TAG = Registrar_Producto.class.getSimpleName();
private static final String URL_DATA = "xxxxxxxxxxxx";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private DevelopersAdapter mAdapter;
private List<DevelopersList> developersLists;
private SearchView searchView;
private String EMISOR = "";
private String EMISOR2 = "";
private String EMISOR3 = "";
TextView count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar__producto);
count=(TextView)findViewById(R.id.count) ;
recyclerView =(RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
developersLists = new ArrayList<>();
EMISOR = Preferences.obtenerPreferenceString(this,Preferences.PREFERENCE_USUARIO_LOGIN);
EMISOR2 = Preferences.obtenerPreferenceString(this,Preferences.PREFERENCE_SELLER_ID);
EMISOR3 = Preferences.obtenerPreferenceString(this,Preferences.PREFERENCE_SHOP_ID);
Toast.makeText(this, EMISOR, Toast.LENGTH_SHORT).show();
Toast.makeText(this, EMISOR2, Toast.LENGTH_SHORT).show();
Toast.makeText(this, EMISOR3, Toast.LENGTH_SHORT).show();
mAdapter = new DevelopersAdapter(this , developersLists , this );
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
loadUrlData();
}
private void loadUrlData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_DATA, new Response.Listener<String>() {
@Override
public void onResponse(String ServerResponse) {
progressDialog.dismiss();
try {
String valor = getIntent().getStringExtra("UserEmailTAG");
String valor2 = getIntent().getStringExtra("seller_id");
String valor3 = getIntent().getStringExtra("shop_id");
JSONObject jsonObject = new JSONObject(ServerResponse);
String returnState= jsonObject.getString("returnState");
String returnData= jsonObject.getString("returnData");
JSONObject jsonObjectData= new JSONObject(returnData);
String recordcount= jsonObjectData.getString("recordcount");
count.setText(recordcount);
JSONArray contacts = jsonObjectData.getJSONArray("data");
for (int i = 0; i < contacts.length(); i++){
JSONObject jo = contacts.getJSONObject(i);
int position=i;
DevelopersList developers = new DevelopersList
(jo.getString("goods_name"),
jo.getString("goods_no"),
jo.getString("image_url"),
jo.getString("min_price").substring(0,5),
jo.getString("max_price").substring(0,5),
jo.getString("sales_unit"));
developersLists.add(developers);
mAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Registrar_Producto.this, "Need internet access", Toast.LENGTH_SHORT).show();
}
}) {
@Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
// The firs argument should be same sa your MySQL database table columns.
params.put("seller_id", getIntent().getStringExtra("seller_id"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
@Override
public void onContactSelected(DevelopersList developersList) {
Toast.makeText(getApplicationContext(), "Selected: " + developersList.getGoods_name() + ", " + developersList.getGoods_no(), Toast.LENGTH_LONG).show();
}
public void lanzarhome (View view) {
Intent i = new Intent(this, Principal.class);
i.putExtra("UserEmailTAG", getIntent().getStringExtra("UserEmailTAG"));
i.putExtra("seller_id", getIntent().getStringExtra("seller_id"));
i.putExtra("shop_id", getIntent().getStringExtra("shop_id"));
startActivity(i);
}
public void lanzarRegistrarProducto(View view) {
Intent i = new Intent(this, prueba.class);
i.putExtra("UserEmailTAG", getIntent().getStringExtra("UserEmailTAG"));
i.putExtra("seller_id", getIntent().getStringExtra("seller_id"));
i.putExtra("shop_id", getIntent().getStringExtra("shop_id"));
startActivity(i);
}
public void lanzarRegresar(View view) {
Intent i = new Intent(this, Principal.class);
i.putExtra("UserEmailTAG", getIntent().getStringExtra("UserEmailTAG"));
i.putExtra("seller_id", getIntent().getStringExtra("seller_id"));
i.putExtra("shop_id", getIntent().getStringExtra("shop_id"));
startActivity(i);
}
public void lanzarSearchP(View view) {
Intent i = new Intent(this, Search_products.class);
i.putExtra("UserEmailTAG", getIntent().getStringExtra("UserEmailTAG"));
i.putExtra("seller_id", getIntent().getStringExtra("seller_id"));
i.putExtra("shop_id", getIntent().getStringExtra("shop_id"));
startActivity(i);
} }
Preferences.java (class for sharedpreferences)
public class Preferences {
public static final String STRING_PREFERENCES = "datos.usuario.corpoasia_android";
public static final String PREFERENCE_ESTADO_BUTTON_SESION = "estado.button.sesion";
public static final String PREFERENCE_USUARIO_LOGIN = "usuario.login";
public static final String PREFERENCE_SHOP_ID = "shop.id";
public static final String PREFERENCE_SELLER_ID = "seller.id";
public static void savePreferenceBoolean(Context c, boolean b,String key){
SharedPreferences preferences = c.getSharedPreferences(STRING_PREFERENCES,c.MODE_PRIVATE);
preferences.edit().putBoolean(key,b).apply();
}
public static void savePreferendceString(Context c, String b,String key){
SharedPreferences preferences = c.getSharedPreferences(STRING_PREFERENCES,c.MODE_PRIVATE);
preferences.edit().putString(key,b).apply();
}
public static boolean obtenerPreferenceBoolean(Context c,String key){
SharedPreferences preferences = c.getSharedPreferences(STRING_PREFERENCES,c.MODE_PRIVATE);
return preferences.getBoolean(key,false);//Si es que nunca se ha guardado nada en esta key pues retornara false
}
public static String obtenerPreferenceString(Context c,String key){
SharedPreferences preferences = c.getSharedPreferences(STRING_PREFERENCES,c.MODE_PRIVATE);
return preferences.getString(key,"");//Si es que nunca se ha guardado nada en esta key pues retornara una cadena vacia
} }