Adding datas into an array to list in another activity - android

Below are the 3 java classes that I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array but I am quite confused on how the logic must be for the code to send the datas keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. Do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java - https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java - https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java - https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc

you can store them as public static variable or create AddActivity constructor and get functions.
String student name; /*add value to this variable #onCreate or wherever in your AddActivity*/
public class AddActivity(/*here to pass data to addactivity*/){
//
}
public String getName(){
return this.name;
}
in another activity
AddActivity ac = new AddActivity();
String someName = ac.getName();
you can use this logic to pass data.
Edit
but if you want to pass data with Intent then just check intenr content onCreate()
Intent i = getIntent();
if(i.hasExtra("intentKey")){//check if it s not null
String name = i.getExtraString("intentKay");
}

The best solution I could find is, declare that array list as static and you could access those wherever you want provided if the classes are in the same package. But if you want to store those values, used shared preferences. Hope this may helps out.

Related

Unable to update item in Firebase Database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to android i have made a project to store members information in one activity and in another activity i display members in listView and on onlong clicking listview i open another activity to update members information but when i click on update button it adds that record instead of Updating.
My Firebase Structure :
My activity for storing :
public class MainActivity extends AppCompatActivity {
EditText txtname,txtage,txtheight,txtphone;
Button btnsave,btnRead;
Member member;
DatabaseReference reff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtname = findViewById(R.id.txtname);
txtage =findViewById(R.id.txtage);
txtphone =findViewById(R.id.txtphone);
txtheight =findViewById(R.id.txtheight);
btnsave = (Button)findViewById(R.id.btnsave);
btnRead =(Button)findViewById(R.id.btnRead);
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
private void openActivity() {
Intent intent = new Intent(MainActivity.this, Retreivedata.class);
startActivity(intent);
}
});
member = new Member();
reff = FirebaseDatabase.getInstance().getReference().child("Member");
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddUsers();
}
});
}
private void AddUsers(){
String name = txtname.getText().toString().trim();
String age = txtage.getText().toString().trim();
String phone = txtphone.getText().toString().trim();
String ht = txtheight.getText().toString().trim();
if(!TextUtils.isEmpty(name)) {
String id = reff.push().getKey();
Member member = new Member(id, name, age, phone, ht);
reff.child(id).setValue(member);
Toast.makeText(this,"User Inserted Successfully",Toast.LENGTH_LONG).show();
txtheight.setText("");
txtphone.setText("");
txtage.setText("");
txtname.setText("");
}else {
txtname.setError("Enter Name");
}
}
}
My activity for displaying records in listview:
public class Retreivedata extends AppCompatActivity {
ListView listView;
FirebaseDatabase database;
DatabaseReference ref;
ArrayList<Member> list;
ArrayAdapter<Member> adapter;
Member member;
Button btnDlt;
Boolean a=false;
String val="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retreivedata);
member = new Member();
listView =(ListView)findViewById(R.id.listView);
btnDlt = (Button) findViewById(R.id.btnDlt);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Member");
list = new ArrayList<>();
adapter = new ArrayAdapter<Member>(this,R.layout.list_white_text,R.id.userInfo, list);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dts: dataSnapshot.getChildren())
{
member = dts.getValue(Member.class);
list.add(member);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnDlt.setEnabled(false);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Boolean a=true;
Member member=adapter.getItem(position);
Toast.makeText(Retreivedata.this,"Do u want to delete this record!!",Toast.LENGTH_LONG).show();
if (a==true)
{
btnDlt.setEnabled(true);
}else{
btnDlt.setEnabled(false);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Member member= adapter.getItem(position);
Intent intent = new Intent(Retreivedata.this, Update.class);
intent.putExtra("tem", member);
startActivity(intent);
return false;
}
});
btnDlt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ref.child(member.getMemberId()).removeValue();
Toast.makeText(Retreivedata.this, "Record deleted Successfully",
Toast.LENGTH_LONG).show();
adapter.remove(member);
adapter.clear();
}
});
}
}
My activity for updating record:
public class Update extends AppCompatActivity {
EditText EditTxtName,EditTxtAge,txtPhone,txtHeight;
Member member;
FirebaseDatabase db;
DatabaseReference reff;
Button btnUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
EditTxtName = (EditText)findViewById(R.id.EditTxtName);
EditTxtAge = (EditText)findViewById(R.id.EditTxtAge);
txtPhone = (EditText)findViewById(R.id.txtPhone);
txtHeight = (EditText)findViewById(R.id.txtHeight);
btnUpdate = (Button)findViewById(R.id.btnUpdate);
final Member member= (Member) getIntent().getSerializableExtra("tem");
EditTxtName.setText(member.getName());
EditTxtAge.setText(member.getAge());
txtPhone.setText(member.getPhone());
txtHeight.setText(member.getHeight());
reff = db.getInstance().getReference().child("Member");
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Update();
}
});
}
private void Update(){
final String mnam = EditTxtName.getText().toString().trim();
final String mage = EditTxtAge.getText().toString().trim();
final String mph = txtPhone.getText().toString().trim();
final String mhei = txtHeight.getText().toString().trim();
final String ID = reff.getKey();
if(TextUtils.isEmpty(mnam)) {
EditTxtName.setText("Plz enter name");}
if(TextUtils.isEmpty(mage)) {
EditTxtName.setText("Plz enter age");}
else{
final Member member = new Member(ID,mnam,mage,mph,mhei);
reff.child("Member").child(ID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
reff = FirebaseDatabase.getInstance().getReference();
reff.child("Member").child(ID).child("name").setValue(mnam);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Toast.makeText(Update.this,"Updated",Toast.LENGTH_LONG).show();
txtHeight.setText("");
txtPhone.setText("");
EditTxtName.setText("");
}
}
}
But after updating record it creates another record.Suggest me what changes has to be done on update button click.
Thnaks!!
First I assume that you implement Serializable for your Member class:
class Member implements Serializable{
.............
.............
.............
}
Since you are passing the member object to the update activity, why not use the ID in it to update the data:
//the update activity
public class Update extends AppCompatActivity {
//this is the member that you pass
Member member;
......
......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.........
.........
//this is how you retrieve it
member= (Member) getIntent().getSerializableExtra("tem");
//this is your ref
reff = db.getInstance().getReference().child("Member");
........
........
}
//when you update
private void Update(){
final String mnam = EditTxtName.getText().toString().trim();
final String mage = EditTxtAge.getText().toString().trim();
final String mph = txtPhone.getText().toString().trim();
final String mhei = txtHeight.getText().toString().trim();
//update the name field
reff.child(member.getMemberId()).child("name").setValue(mnam);
}
Your problem is this line of code final String ID = reff.getKey()
That call generates a new ID which you then use in your update of the db. You need to replace the call to getKey with the ID of the member you want to update.

Can't pass multi integers at the same time in intent

So I want to pass the data between the activities,so I've make that there's 3 separate integers should be send to the second activity,but i don't know why,the emulator keeps adding all of them. Basically,I making an app, at case of my course - i need to create an app that keeping score,in my case,app would keep the score,number of fouls,and number of corners during the football match. To set the data,we are clicking in special button (press score to increment score etc.) when we want to go to the second activity and see the detailed statistics we should see like 3 goals,6 fouls,and like 2 corners for team "A" during the match,but when i clicking in buttons (suppose that is 1 time for goal,2 times for fouls,and 3 times for corner the app should be like 1 goal,2 fouls,3 corner's but it keep adding all of integers,and it's like 6 goals,6 fouls,6 corners. What can be wrong?
Count activity (here program storage the value of integers)
public class CountActivity extends AppCompatActivity {
public int team_a_score;
public int team_a_foul;
public int team_a_corner;
public int team_b_score;
public int team_b_foul;
public int team_b_corner;
private Button goToDetailedStats;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count);
goToDetailedStats = (Button) findViewById(R.id.go_to_stats);
goToDetailedStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDetailedScore();
}
});
}
private void openDetailedScore() {
Intent intent = new Intent(this,DeatiledScoreActivity.class);
intent.putExtra("",team_a_score);
intent.putExtra("",team_a_foul);
intent.putExtra("",team_a_corner);
startActivity(intent);
}
public void resetScore(View view) {
team_a_score = 0;
display_a_score(team_a_score);
team_b_score = 0;
display_b_score(team_b_score);
}
private void display_a_score (int a_score){
TextView team_a_score_tv = (TextView) findViewById(R.id.team_a_score_tv);
team_a_score_tv.setText(String.valueOf(a_score));
}
private void display_b_score (int b_score){
TextView team_b_score_tv = (TextView) findViewById(R.id.team_b_score_tv);
team_b_score_tv.setText(String.valueOf(b_score));
}
public void increment_a_score(View view) {
team_a_score = team_a_score+1;
display_a_score(team_a_score);
}
public void increment_a_foul(View view) {
team_a_foul = team_a_foul+1;
}
public void increment_a_corner(View view) {
team_a_corner = team_a_corner+1;
}
public void increment_b_score(View view) {
team_b_score = team_b_score+1;
display_b_score(team_b_score);
}
public void increment_b_foul(View view) {
team_b_foul = team_b_foul+1;
}
public void increment_b_corner(View view) {
team_b_corner = team_b_corner+1;
}
}
Detailed activity have to receive data that we send as intent from Counting activity.
public class DeatiledScoreActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deatiled_score);
int team_a_score_detail_int = 0;
int team_a_foul_detail_int = 0;
int team_a_corner_detail_int = 0;
int team_b_score_detail_int = 0;
int team_b_foul_detail_int = 0;
int team_b_corner_detail_int = 0;
Intent goal_intent = getIntent();
int goal = goal_intent.getIntExtra("", team_a_score_detail_int);
display_a_goal(goal);
Intent foul_intent = getIntent();
int foul = foul_intent.getIntExtra("", team_a_foul_detail_int);
display_a_foul(foul);
Intent corner_intent = getIntent();
int corner = corner_intent.getIntExtra("", team_a_corner_detail_int);
display_a_corner(corner);
}
public void display_a_goal(int score) {
TextView a_score = (TextView) findViewById(R.id.team_a_goal_detail);
a_score.setText(String.valueOf(score));
}
public void display_a_foul(int foul){
TextView a_foul = (TextView) findViewById(R.id.team_a_foul_detail);
a_foul.setText(String.valueOf(foul));
They cannot have the same key:
intent.putExtra("",team_a_score);
intent.putExtra("",team_a_foul);
intent.putExtra("",team_a_corner);
So in order to make it work set:
intent.putExtra("some",team_a_score);
intent.putExtra("some2",team_a_foul);
intent.putExtra("some4",team_a_corner);
Intent putExtra method accepts two arguments key - value.

How to validate a input field and prevent Dialog dismissing

In my application I extend the Dialog class to get user input for each field and now I want to validate them.
public abstract class EditDialogHelper extends Dialog implements android.view.View.OnClickListener {
private Context context;
private String title;
private String field;
private String positive;
private String negative;
private EditText etField;
private TextView tvCount;
private int characterCount;
public EditDialogHelper(Context context, String title, String field, String positive, String negative, int characterCount) {
super(context);
this.context = context;
this.title = title;
this.field = field;
this.positive = positive;
this.negative = negative;
this.characterCount = characterCount;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_edit_view);
TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
etField = (EditText) findViewById(R.id.etField);
tvCount = (TextView) findViewById(R.id.tvInputCount);
Button btnConfirmationOk = (Button) findViewById(R.id.btnPositive);
Button btnConfirmationCancel = (Button) findViewById(R.id.btnNegative);
final TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tvCount.setText(String.valueOf(characterCount - s.length()));
}
#Override
public void afterTextChanged(Editable s) {
}
};
etField.addTextChangedListener(textWatcher);
tvTitle.setText(title);
etField.setText(field);
etField.setFilters(new InputFilter[]{new InputFilter.LengthFilter(characterCount)});
btnConfirmationOk.setOnClickListener(this);
btnConfirmationCancel.setOnClickListener(this);
}
public String getValue() {
return etField.getText().toString().trim();
}
private boolean validateInputs(String value) {
boolean valid = false;
if (value != null && !(value.equals(""))) {
valid = true;
} else {
etField.setError("This can't be left empty");
}
return valid;
}
}
Once the dialog opens up I want it to be validated once the btnConfirmationOk is clicked and if the field is empty, it should be prevented from dismissing the dialog while showing the error.
Where should I use this validateInputs method and in which way it should be modified.
Answer is quite simple i guess
#Override
void onClick(View view) {
if (view.getId == R.id.btnPositive) {
boolean valid = validate("my string");
if(valid) {
// do stuff
dissmis();
}
} else {
dissmis();
}
}
But in my oppinion you should set different listeners to your possitive and negative buttons, instead of tracking everything with EditDialogHelper class.
this could be done like this.
button.setOnClickListener(new OnClickListener {
#Override
void onClick(View v) {
}
});
p.s. I wrote everything from my head so this could contain compilation errors.

Android - Pass an intent from one activity to another that implements a callback class with Firebase

I have two activities: AddUser and ToDo. ToDo implements a class with callback. ToDo allows the user to create a to do list, and the to do items will be displayed instantly in a recyclerView. User can add, update, or delete to do items in ToDo.
AddUser.java
public class AddUser extends AppCompatActivity implements View.OnClickListener{
private DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
mUserRef = FirebaseDatabase.getInstance().getReference().child("users");
EditText etUserid = (EditText) findViewById(R.id.etUserid);
EditText etUsername = (EditText) findViewById(R.id.etUsername);
Button btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
}
public void addUser(UserDetails userDetails){
userPushKey = mUserRef.push().getKey();
mUserRef.child(userPushKey).setValue(userDetails);
}
#Override
public void onClick(View v){
if(v == btnNext){
String inputUserid = etUserid.getText().toString();
String inputUsername = etUsername.getText().toString();
addUser(new UserDetails(inputUserid, inputUsername));
Intent intent = new Intent(AddUser.this,ToDo.class);
intent.putExtra("userKeyRef", userPushKey);
startActivity(intent);
}
}
}
ToDo.java
public class ToDo extends AppCompatActivity implements UserTodoAdapter.Callback {
private UserTodoAdapter mAdapter;
#Override
protcted void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
mAdapter = new UserTodoAdapter(this);
RecyclerView view = (RecyclerView) findViewById(R.id.recycler_view);
view.setHasFixedSize(true);
view.setAdapter(mAdapter);
}
#Override
public void onEdit(final UserTodo userTodo){
// some functions here
}
}
UserTodoAdapter.java
public class UserTodoAdapter extends RecyclerView.Adapter<UserTodoAdapter.ViewHolder> {
private List<UserTodo> mUserTodo;
private Callback mCallback;
private DatabaseReference mUserTodoRef;
public UserTodoAdapter(Callback callback) {
mCallback = callback;
mUserTodo = new ArrayList<>();
// need to get the push key from AddUser activity
mUserTodoRef = FirebaseDatabase.getInstance.getReference().child(users).child("Need the push key here").child("todo");
mUserTodoRef.addChildEventListener(new TodoChildEventListener());
}
private class TodoChildEventListener implements ChildEventListener{
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s){
// action here
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s){
// action here
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot){
// action here
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s){
// action here
}
#Override
public void onCancelled(DatabaseError databaseError){
// action here
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.a_custom_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position){
final UserTodo userTodo = mUserTodo.get(position);
holder.mTodoTitle.setText(userTodo.getTodoTitle());
holder.mTodoDesc.setText(userTodo.gerTodoDesc());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onEdit(userTodo);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
removeTodo(mUserTodo.get(position));
return true;
}
});
}
#Override
public int getItemCount(){
return mUserTodo.size();
}
public interface Callback{
public void onEdit(UserTodo userTodo);
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView mTodoTitle;
private TextView mTodoDesc;
public ViewHolder(View itemView){
super(itemView);
mTodoTitle = (TextView) itemView.findViewById(R.id.tvTodoTitle);
mTodoDesc = (TextView) itemView.findViewById(R.id.tvTodoDesc);
}
}
public void addTodo(UserTodo userTodo){
mUserTodoRef.push().setValue(userTodo);
}
public void updateTodo(UserTodo userTodo, String newTodoTitle, String newTodoDesc){
userTodo.setTodoTitle(newTodoTitle);
userTodo.setTodoDesc(newTodoDesc);
mUserTodoRef.child(userTodo.getTodoKey()).setValue(userTodo);
}
public void removeTodo(UserTodo userTodo){
mUserTodoRef.child(userTodo.getTodoKey()).removeValue();
}
}
After the user clicked on Next button in AddUser activity, the user data is straightly added to Firebase, and the user will be redirected to ToDo page where the user can add to do items. How to pass the push key created in AddUser, so that when the user add the to do items, the items will be added under the user?
Is using intent the right way?
Please don't ask me why I need to let user add to do list right after the user is created. It's needed this way.
Thanks
Edit: I'm sorry I should mention that the intent should be passed to UserTodoAdapter class, so that in the Firebase database reference of UserTodoAdapter, I can point the reference to the key passed from AddUser.
I have classes UserDetails and UserTodo, for activities AddUser and ToDo respectively to handle data in Firebase.
Eventually the data will look like this:
{
"users":{
"push_id":{
"userid":"123456",
"username":"My User",
"todo_s":{
"push_id":{
"todo1":"Title1",
"todo_desc":"Description"
},
"push_id":{
"todo2":"Title2",
"todo_desc":"Description"
},
}
},
}
}
Passing via intent (from AddUser to ToDo) is fine. Or you can save it to local storage like SharedPreferences so your user doesn't have to create new user if the user has created a new user.
To pass the key value from your ToDo activity to the adapter, modify the adapter's constructor to accept a key parameter
public UserTodoAdapter(Callback callback, String key) {
mCallback = callback;
mUserTodo = new ArrayList<>();
mUserTodoRef = FirebaseDatabase.getInstance.getReference().child(users).child(key).child("todo");
}
And in the ToDo, instantiate the adapter by passing the string extra from the previous activity (AddUser).
mAdapter = new UserTodoAdapter(this, getIntent().getStringExtra("key"));

How to create a login page as always be logged in if once logged in?

I have a login page for my project.Here my requirement is,that login page always want to be logged-in,if once i log in.I have got some ideas through Google,ie., it recommended me to use shared-preference concept,right now i am following this concept and i have tried some code.
In my project the problem is after giving the proper username and password,it does not switch to another screen,at the same i am getting nothing on my log-cat too.How to achieve this concept?
Suggestions please..
please find my sources for reference
class SaveSharedPreferece
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, boolean userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}}
MainActivity.java
public class MainActivity extends Activity
{
Button btn;
EditText edt1,edt2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void loginpage()
{
edt1 = (EditText)findViewById(R.id.editText_username);
edt2 = (EditText)findViewById(R.id.editText_password);
btn = (Button)findViewById(R.id.button_login);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(edt1.getText().toString().length()!=0 && edt1.getText().toString().length()!=0)
{
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
else
{
Toast.makeText(getApplicationContext(), "oops! empty..", Toast.LENGTH_SHORT).show();
}
}
});
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
loginpage();
}
else
{
// Call Next Activity
}
if (getIntent().getBooleanExtra("EXIT", false))
{
finish();
}
}
}
ResultActivity.java
public class ResultActivity extends Activity
{
Button btn_exit;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
btn_exit = (Button)findViewById(R.id.button_exit);
btn_exit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
});
}}
thanks for your precious time!..
You are saving boolean to SharedPreferences and getting String. How that is possible.
Better to save and get either boolean or String.
Change your setUserName() code in SaveSharedPreference class as below and it works
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
First add another field in SharedPrefernce file as password. Do same whatever you have done foe username(make it string instead of boolean in setter method) like setter and getter methods.
Create one method which will fetch values from sharedPrefernce like this :
private void validateUser(){
String username = SaveSharedPreference.getUserName(MainActivity.this);
String password = SaveSharedPreference.getPassword(MainActivity.this);
if (check_for_any_condition){
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
}
Call this method in your oncreate method.
Hope it will help you.

Categories

Resources