I am trying to send an ID as an int and get it from an intent in another activity but it returns zero.
This is the intent in the first activity:
public class Main_page extends AppCompatActivity {
ListView PatientList;
Button BTaddPatient;
DBpatients db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
PatientList = findViewById(R.id.PateintList);
BTaddPatient = findViewById(R.id.ADDpateint);
db = new DBpatients(this);
BTaddPatient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main_page.this, Add_patient_Activity.class);
startActivity(intent);
}
});
PatientList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Patient selected_patient = (Patient) parent.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), Update_patient.class);
intent.putExtra("ID", selected_patient.getId());
intent.putExtra("name", selected_patient.getName());
intent.putExtra("diagnose", selected_patient.getDiagnose());
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
ArrayList<Patient> patients = db.getAllPatients();
PatientAdapter patientAdapter = new PatientAdapter(this, R.layout.item_pateint, patients);
PatientList.setAdapter(patientAdapter);
}
}
And trying to get the ID in the other activity:
public class Update_patient extends AppCompatActivity {
DBpatients db;
EditText editName, editDiagnose;
Button UpdateBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_patient);
final int id = getIntent().getExtras().getInt("ID");
db = new DBpatients(this);
editName = findViewById(R.id.EDname);
editDiagnose = findViewById(R.id.EDdiagnose);
UpdateBTN = findViewById(R.id.BTupdate);
Patient patient = db.getPatientByID2(id);
editDiagnose.setText(patient.getDiagnose());
editName.setText(patient.getName());
UpdateBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editName.getText().toString();
String diagnose = editDiagnose.getText().toString();
Patient newPatient = new Patient( id, name, diagnose);
db.UpdatePatient(newPatient);
Toast.makeText(Update_patient.this, "successfuly UPDATED", Toast.LENGTH_SHORT).show();
}
});
}
This is Patient class :
public class Patient {
private String name;
private int id;
private String diagnose;
public Patient(String name, String diagnose) {
this.name = name;
this.diagnose = diagnose;
}
public Patient(int id, String name, String diagnose) {
this.name = name;
this.diagnose = diagnose;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDiagnose() {
return diagnose;
}
public void setDiagnose(String diagnose) {
this.diagnose = diagnose;
}
}
The app crashes, and, by using the debugger, it shows that ID = 0 when receiving it.
Please help.
You just have to send extras while calling your intent.
Like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this.
If the value you sent was in int:
int value = getIntent().getIntExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
Example:
int value = getIntent().getIntExtra("ID", 0);
Related
Update
I found the issue within my program, the values are actually being saved as seen within the database inspector
The activity for adding the values never displays the current values which is what I thought they should, from this activity I can only enter new values and save
I have a user object which is already created in a separate activity via recyclerview, I want to then click into each recycler view created and update the users data within that but my update user method is not updating or storing any data at all when I enter the new data in the fields.
I know this is due to my app not being able to identify which user I'm actually trying to update but I'm unsure how to assign the id to my user object and then search for the clicked on user's id within my updateUser method in the UserDetails activity?
See below my user object created within User entity
#Entity
public class User {
#PrimaryKey(autoGenerate = true)
public int uid = 0;
#ColumnInfo(name = "Username")
public String UserName;
#ColumnInfo(name = "Field1")
public String Value1;
#ColumnInfo(name = "Field2")
public String Value2;
#ColumnInfo(name = "Field3")
public String Value3;
#ColumnInfo(name = "Field4")
public String Value4;
#ColumnInfo(name = "Field5")
public String Value5;
#ColumnInfo(name = "Field6")
public String Value6;
#ColumnInfo(name = "Field7")
public String Value7;
#ColumnInfo(name = "Field8")
public String Value8;
#ColumnInfo(name = "Field9")
public String Value9;
#ColumnInfo(name = "Field10")
public String Value10;
public User() { this("", "", "", "", "", "", "", "", "", "", ""); }
public User(String UserName, String value1, String value2, String value3, String value4, String value5, String value6, String value7, String value8, String value9, String value10 ) {
setUserName(UserName);
setValue1(Value1);
setValue1(Value2);
setValue1(Value3);
setValue1(Value4);
setValue1(Value5);
setValue1(Value6);
setValue1(Value7);
setValue1(Value8);
setValue1(Value9);
setValue1(Value10);
}
public int getId() {
return uid;
}
public void setId(int id) {
this.uid = id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
// Field 1 value
public String getValue1() {
return Value1;
}
public void setValue1(String value1) {
Value1 = value1;
}
// Field 2 value
public String getValue2() {
return Value2;
}
public void setValue2(String value2) {
Value2 = value2;
}
// Field 3 value
public String getValue3() {
return Value3;
}
public void setValue3(String value3) {
Value3 = value3;
}
// Field 4 value
public String getValue4() {
return Value4;
}
public void setValue4(String value4) {
Value4 = value4;
}
// Field 5 value
public String getValue5() {
return Value5;
}
public void setValue5(String value5) {
Value5 = value5;
}
// Field 6 value
public String getValue6() {
return Value6;
}
public void setValue6(String value6) {
Value6 = value6;
}
// Field 7 value
public String getValue7() {
return Value7;
}
public void setValue7(String value7) {
Value7 = value7;
}
// Field 8 value
public String getValue8() {
return Value8;
}
public void setValue8(String value8) {
Value8 = value8;
}
// Field 9 value
public String getValue9() {
return Value9;
}
public void setValue9(String value9) {
Value9 = value9;
}
// Field 10 value
public String getValue10() {
return Value10;
}
public void setValue10(String value10) {
Value10 = value10;
}
}
See below my UserDao with my methods for inserting and updating a user
#Dao
public interface UserDao {
#Query("SELECT * FROM User")
List<User> getAllUsers();
#Query("SELECT * FROM User WHERE uid =:userID")
User getUser(int userID);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertUser(User users);
#Query("UPDATE User SET Field1 =:Value1, Field2 =:Value2, Field3 =:Value3, Field4 =:Value4, Field5 =:Value5, Field6 =:Value6, " +
"Field7 =:Value7, Field8 =:Value8, Field6 =:Value9, Field6 =:Value9, Field10 =:Value10 WHERE uid = uid ")
void updateUser(String Value1, String Value2, String Value3, String Value4, String Value5, String Value6, String Value7,
String Value8, String Value9, String Value10);
#Update
void updateUser(User...users);
#Delete
void delete(User user);
}
See below my addnewuseractivity where a user is initially created
public class AddNewUserActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_user);
final EditText firstNameInput = findViewById(R.id.firstNameInput);
/* final EditText txtField1Value = findViewById(R.id.txtField1Value);
final EditText txtField2Value = findViewById(R.id.txtField2Value);
final EditText txtField3Value = findViewById(R.id.txtField3Value);
final EditText txtField4Value = findViewById(R.id.txtField4Value);
final EditText txtField5Value = findViewById(R.id.txtField5Value);
final EditText txtField6Value = findViewById(R.id.txtField6Value);
final EditText txtField7Value = findViewById(R.id.txtField7Value);
final EditText txtField8Value = findViewById(R.id.txtField8Value);
final EditText txtField9Value = findViewById(R.id.txtField9Value);
final EditText txtField10Value = findViewById(R.id.txtField10Value);
*/
Button saveButton = findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveNewUser(firstNameInput.getText().toString()); /*, txtField1Value.getText().toString(), txtField2Value.getText().toString(),
txtField3Value.getText().toString(), txtField4Value.getText().toString(), txtField5Value.getText().toString(),
txtField6Value.getText().toString(), txtField7Value.getText().toString(), txtField8Value.getText().toString(),
txtField9Value.getText().toString(), txtField10Value.getText().toString());*/
}
});
}
public void saveNewUser(String firstName) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = new User();
user.UserName = firstName;
/*user.Value1 = value1;
user.Value2 = value2;
user.Value3 = value3;
user.Value4 = value4;
user.Value5 = value5;
user.Value6 = value6;
user.Value7 = value7;
user.Value8 = value8;
user.Value9 = value9;
user.Value10 = value10;*/
db.userDao().insertUser(user);
finish();
}
}
See below my userdetails activity where the created user's data is supposed to be updated on press
public class UserDetails extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_details);
final EditText txtField1Value = findViewById(R.id.txtField1Value);
final EditText txtField2Value = findViewById(R.id.txtField2Value);
final EditText txtField3Value = findViewById(R.id.txtField3Value);
final EditText txtField4Value = findViewById(R.id.txtField4Value);
final EditText txtField5Value = findViewById(R.id.txtField5Value);
final EditText txtField6Value = findViewById(R.id.txtField6Value);
final EditText txtField7Value = findViewById(R.id.txtField7Value);
final EditText txtField8Value = findViewById(R.id.txtField8Value);
final EditText txtField9Value = findViewById(R.id.txtField9Value);
final EditText txtField10Value = findViewById(R.id.txtField10Value);
Intent detailIntent = getIntent();
if (detailIntent != null) {
final int userId = detailIntent.getIntExtra("userId", -1);
if (userId != -1) {
Button saveButton = findViewById(R.id.saveButton2);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUser(userId, txtField1Value.getText().toString(), txtField2Value.getText().toString(),
txtField3Value.getText().toString(), txtField4Value.getText().toString(), txtField5Value.getText().toString(),
txtField6Value.getText().toString(), txtField7Value.getText().toString(), txtField8Value.getText().toString(),
txtField9Value.getText().toString(), txtField10Value.getText().toString());
}
});
}
}
}
/* public User getUser(int userID)
{
return AppDatabase.getDbInstance(this.getApplicationContext()).userDao().getUser(userID);
}*/
public void updateUser( int userId, String value1, String value2, String value3, String value4, String value5, String value6, String value7,
String value8, String value9, String value10) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = db.userDao().getUser(userId);
user.Value1 = value1;
user.Value2 = value2;
user.Value3 = value3;
user.Value4 = value4;
user.Value5 = value5;
user.Value6 = value6;
user.Value7 = value7;
user.Value8 = value8;
user.Value9 = value9;
user.Value10 = value10;
db.userDao().updateUser(user);
finish();
}
}
See below my UserListAdapter and MainActivity for reference
public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.MyViewHolder> {
private Context context;
private List<User> userList;
private ItemClickListener clickListener;
public UserListAdapter(Context context) {
this.context = context;
}
public void setUserList(List<User> userList) {
this.userList = userList;
notifyDataSetChanged();
}
#NonNull
#Override
public UserListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserListAdapter.MyViewHolder holder, #SuppressLint("RecyclerView") final int position) {
final User user = userList.get(position);
holder.tvFirstName.setText(this.userList.get(position).UserName);
/* holder.tvValue1.setText(this.userList.get(position).Value1);
holder.tvValue2.setText(this.userList.get(position).Value2);
holder.tvValue3.setText(this.userList.get(position).Value3);
holder.tvValue4.setText(this.userList.get(position).Value4);
holder.tvValue5.setText(this.userList.get(position).Value5);
holder.tvValue6.setText(this.userList.get(position).Value6);
holder.tvValue7.setText(this.userList.get(position).Value7);
holder.tvValue8.setText(this.userList.get(position).Value8);
holder.tvValue9.setText(this.userList.get(position).Value9);
holder.tvValue10.setText(this.userList.get(position).Value10);*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , UserDetails.class);
context.startActivity(intent);
}
});
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppDatabase.getDbInstance(context).userDao().delete(user);
userList.remove(user);
notifyItemRemoved(position);
}
});
}
#Override
public int getItemCount() {
return this.userList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView tvFirstName;
/* TextView tvValue1;
TextView tvValue2;
TextView tvValue3;
TextView tvValue4;
TextView tvValue5;
TextView tvValue6;
TextView tvValue7;
TextView tvValue8;
TextView tvValue9;
TextView tvValue10;*/
Button deleteBtn;
public MyViewHolder(View view) {
super(view);
tvFirstName = view.findViewById(R.id.tvFirstName);
/* tvValue1 = view.findViewById(R.id.tvField1Value);
tvValue2 = view.findViewById(R.id.tvField2Value);
tvValue3 = view.findViewById(R.id.tvField3Value);
tvValue4 = view.findViewById(R.id.tvField4Value);
tvValue5 = view.findViewById(R.id.tvField5Value);
tvValue6 = view.findViewById(R.id.tvField6Value);
tvValue7 = view.findViewById(R.id.tvField7Value);
tvValue8 = view.findViewById(R.id.tvField8Value);
tvValue9 = view.findViewById(R.id.tvField9Value);
tvValue10 = view.findViewById(R.id.tvField10Value);*/
deleteBtn = view.findViewById(R.id.deleteBtn);
}
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView userName;
public ViewHolder(View itemView) {
super(itemView);
userName = (TextView) itemView.findViewById(R.id.tvFirstName);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
public class MainActivity extends AppCompatActivity implements ItemClickListener{
private UserListAdapter userListAdapter;
private List<User> users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addNewUserButton = findViewById(R.id.addNewUserButton);
addNewUserButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(MainActivity.this, AddNewUserActivity.class), 100);
}
});
initRecyclerView();
loadUserList();
}
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(dividerItemDecoration);
userListAdapter = new UserListAdapter(this);
recyclerView.setAdapter(userListAdapter);
}
private void loadUserList() {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
List<User> userList =db.userDao().getAllUsers();
userListAdapter.setUserList(userList);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 100) {
loadUserList();
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onClick(View view, int position) {
final User user = users.get(position);
}
}
When creating the User, Room auto-generates the primary key for you - uid.
When trying to update the User, it is you, who need to provide the uid.
public void updateUser(int usertID, String value1...value10) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = new User();
user.uid = userUID // <------------
user.Value1 = value1;
...
user.Value10 = value10;
db.userDao().updateUser(user);
finish();
}
I think you are missing passing the user ID to the detail activity as well.
UserListAdapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , UserDetails.class);
intent.putExtra("userId", user.uid)
context.startActivity(intent);
}
});
UserDetails activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_details);
final EditText txtField1Value = findViewById(R.id.txtField1Value);
...
final EditText txtField10Value = findViewById(R.id.txtField10Value);
Intent detailIntent = getIntent();
if (detailIntent != null) {
int userId = detailIntent.getIntExtra("userId", -1);
if (userId != -1) {
Button saveButton = findViewById(R.id.saveButton2);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUser(
userId
txtField1Value.getText().toString(),
...
txtField10Value.getText().toString());
}
});
}
}
}
This is my small project, I can put name, address, and phone to SQLite and display it. And then I want to fill link image to the box and display an image in recyclerView. Please help!
Here's my app and code:
RecyclerView display, no img
And I want to fill the link image to this box... and img'll appear!
MainActivity:
public class MainActivity extends AppCompatActivity {
private StudentAdapter studentAdapter;
private ArrayList<Student> studentList;
private StudentDatabase studentDatabase;
private FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton = findViewById(R.id.floatingActionButton);
final RecyclerView recyclerView = findViewById(R.id.recycle);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
studentAdapter = new StudentAdapter();
studentDatabase = new StudentDatabase(this);
studentList = new ArrayList<>();
studentList = studentDatabase.getAll();
recyclerView.setAdapter(studentAdapter);
studentAdapter.setData(studentList);
Student student = new Student();
recyclerView.smoothScrollToPosition(studentList.size());
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateStudent.class);
Student student = new Student();
intent.putExtra("data", student);
startActivityForResult(intent, 800);
}
});
studentAdapter.setOnClickEvent(new StudentAdapter.OnClickEvent() {
#Override
public void OnItemClick(int position) {
Student student = studentList.get(position);
Intent intent = new Intent(MainActivity.this, ModifyStudent.class);
intent.putExtra("data", student);
startActivityForResult(intent, 70);
}
#Override
public void OnDelete(int position) {
Student student = studentList.get(position);
studentDatabase.delete(student.getId());
studentList.remove(position);
studentList = studentDatabase.getAll();
studentAdapter.setData(studentList);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 70 && resultCode == RESULT_OK) {
Student student = (Student) data.getSerializableExtra("returnData");
studentDatabase.update(student);
studentList = studentDatabase.getAll();
studentAdapter.setData(studentList);
}
if (requestCode == 800 && resultCode == RESULT_OK) {
studentList = studentDatabase.getAll();
studentAdapter.setData(studentList);
}
}
}
Student.java:
public class Student implements Serializable {
private String img;
private int id;
private String name;
private String address;
private String phone;
public Student(String img, int id, String name, String address, String phone) {
this.img = img;
this.id = id;
this.name = name;
this.address = address;
this.phone = phone;
}
public Student(){
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
CreateStudent.java:
public class CreateStudent extends AppCompatActivity {
private EditText createName, createAddress, creatPhone, createImage;
private StudentDatabase studentDatabase;
private Button btnCreate;
private Button btnCancle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_student2);
createName = findViewById(R.id.create_name);
createAddress = findViewById(R.id.create_address);
creatPhone = findViewById(R.id.create_phone);
btnCreate = findViewById(R.id.btn_create);
btnCancle = findViewById(R.id.btn_cancle);
createImage = findViewById(R.id.create_img);
final Student student = new Student();
if (student != null) {
createName.setText(student.getName());
createAddress.setText(student.getAddress());
creatPhone.setText(student.getPhone());
}
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cname = createName.getText().toString();
String caddress = createAddress.getText().toString();
String cphone = creatPhone.getText().toString();
String cimage = createImage.getText().toString();
if (cname.trim().equals("") || caddress.trim().equals("") || cphone.trim().equals("")) {
btnCreate.setEnabled(false);
} else {
student.setName(cname);
student.setAddress(caddress);
student.setPhone(cphone);
student.setImg(cimage);
studentDatabase = new StudentDatabase(CreateStudent.this);
studentDatabase.addStudent(student);
Intent intent = new Intent();
intent.putExtra("createData", student);
setResult(RESULT_OK, intent);
finish();
}
}
});
btnCancle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
StudentDatabase.java:
public class StudentDatabase extends SQLiteOpenHelper {
public StudentDatabase(#Nullable Context context) {
super(context, "STUDENT_DATABASE", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE STUDENT(ID INTEGER PRIMARY KEY, NAME TEXT, ADDRESS TEXT, PHONE INTEGER)";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENT");
onCreate(db);
}
public void addStudent(Student student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", student.getName());
cv.put("ADDRESS", student.getAddress());
cv.put("PHONE", student.getPhone());
db.insert("STUDENT", null, cv);
db.close();
}
public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("STUDENT", " ID = " + id, null);
db.close();
}
public ArrayList<Student> getAll() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM STUDENT";
Cursor cursor = db.rawQuery(query, null);
ArrayList<Student> studentList = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
String phone = cursor.getString(3);
Student student = new Student();
student.setName(name);
student.setId(id);
student.setAddress(address);
student.setPhone(phone);
studentList.add(student);
} while (cursor.moveToNext());
}
db.close();
return studentList;
}
public void update(Student student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", student.getName());
cv.put("ADDRESS", student.getAddress());
cv.put("PHONE", student.getPhone());
db.update("STUDENT", cv, "ID = " + student.getId(), null);
}
}
StudentAdapter.java:
public class StudentAdapter<extend> extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {
private ArrayList<Student> studentList;
private OnClickEvent onClickEvent;
public void setOnClickEvent(OnClickEvent onClickEvent) {
this.onClickEvent = onClickEvent;
}
public StudentAdapter() {
}
public void setData(ArrayList<Student> listData) {
if (studentList == null) {
studentList = new ArrayList<>();
}
studentList.clear();
studentList.addAll(listData);
notifyDataSetChanged();
}
#NonNull
#Override
public StudentAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull StudentAdapter.MyViewHolder holder, final int position) {
Student student = studentList.get(position);
Glide.with(holder.imageView.getContext()).load(studentList.get(position).getImg()).into(holder.imageView);
holder.name.setText(student.getName());
holder.address.setText(student.getAddress());
holder.phone.setText(student.getPhone());
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onClickEvent != null) {
onClickEvent.OnDelete(position);
}
}
});
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onClickEvent != null) {
onClickEvent.OnItemClick(position);
}
}
});
}
#Override
public int getItemCount() {
return studentList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView name, address, phone;
private Button btn_delete, btn_edit;
private ImageView imageView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.img);
name = itemView.findViewById(R.id.name);
address = itemView.findViewById(R.id.address);
phone = itemView.findViewById(R.id.phone);
btn_delete = itemView.findViewById(R.id.btn_delete);
btn_edit = itemView.findViewById(R.id.btn_edit);
}
}
public interface OnClickEvent {
void OnItemClick(int position);
void OnDelete(int position);
}
}
Though you have correctly defined your recyclerView with Glide library to show the picture but you are not storing(saving) picture information in your database.
public void addStudent(Student student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", student.getName());
cv.put("ADDRESS", student.getAddress());
cv.put("PHONE", student.getPhone());
db.insert("STUDENT", null, cv);
db.close();
}
you should have something like
cv.put("PICTURE", student.getImg());
you should also do the same for your public void update(Student student) method for storing(saving) user picture. And also with your public void addStudent(Student student) method definition. And also you should retrieve your picture information inside your `
public ArrayList<Student> getAll() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM STUDENT";
Cursor cursor = db.rawQuery(query, null);
ArrayList<Student> studentList = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
String phone = cursor.getString(3);
Student student = new Student();
student.setName(name);
student.setId(id);
student.setAddress(address);
student.setPhone(phone);
studentList.add(student);
} while (cursor.moveToNext());
}
db.close();
return studentList;
}
something like this:
String picture = cursor.getString(4);
student.setImg(picture);
The picture information should be the path of the picture location which might be a URL or a file location in your phone's disk.
...............
updates:
String query = "CREATE TABLE STUDENT(ID INTEGER PRIMARY KEY, NAME TEXT, ADDRESS TEXT, PHONE INTEGER, PICTURE TEXT)";
I am building an app where the user can store his/her usernames and passwords. The app has a simple UI. The Main thread has a list of entries, a FAB and a delete all icon on the action bar. My issue is that I am not able to edit and update existing entries.
I have the following code in the onCreate() of my MainActivity.java. When the user holds an entry, it launches the AddEditEntry.java activity. What happens here is that the launched activity does not have the existing entry data in its EditText fields:
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
In my AddEditEntry.java activity, I have the following code in the onClick of the save button. I am adding the new data as extras to the intent:
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
and back in my MainActivity.jav, this is my onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
Entries entry = new Entries(username, hint, password);
viewModel.insert(entry);
Toast.makeText(this, "Entry added!", Toast.LENGTH_SHORT).show();
}else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK){
int id = Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
if (id == -1){Toast.makeText(addEditEntry, "Something went wrong", Toast.LENGTH_SHORT).show();}
Entries entry = new Entries(username, hint, password);
entry.setId(id);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();}
}
When I run the app and try to edit an entry, the Toast message reads "Entry updated!" so it does run that code but the changes do not exist. I tried stopping the app and restarting it to refresh it but it still doesn't exist.
ViewModel.java:
public class EntryViewModel extends AndroidViewModel {
private EntryRepository repository;
private LiveData<List<Entries>> allEntries;
public EntryViewModel(#NonNull Application application) {
super(application);
repository = new EntryRepository(application);
allEntries = repository.getAllEntries();
}
public void insert(Entries entries){repository.insert(entries);}
public void update(Entries entries){repository.update(entries);}
public void delete(Entries entries){repository.delete(entries);}
public void deleteAll(){repository.deleteAllEntries();}
public LiveData<List<Entries>> getAllEntries() {return allEntries;}
}
EntryRepository.java:
public class EntryRepository {
private EntryDAO entryDAO;
private LiveData<List<Entries>> allEntries;
public EntryRepository(Application application){
EntryDatabase database = EntryDatabase.getInstance(application);
entryDAO = database.generateDao();
allEntries = entryDAO.getAllEntries();
}
public void insert(Entries entries){new InsertEntryAsyncTask(entryDAO).execute(entries);}
public void update(Entries entries){new UpdateEntryAsyncTask(entryDAO).execute(entries);}
public void delete(Entries entries){new DeleteEntryAsyncTask(entryDAO).execute(entries);}
public void deleteAllEntries(){new DeleteAllEntriesAsyncTask(entryDAO).execute();}
public LiveData<List<Entries>> getAllEntries(){return allEntries;}
public static class InsertEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private InsertEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.insert(entries[0]);
return null;
}
}
public static class UpdateEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private UpdateEntryAsyncTask(EntryDAO entryDAO){
this.entryDAO = entryDAO;
}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.update(entries[0]);
return null;
}
}
public static class DeleteEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private DeleteEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.delete(entries[0]);
return null;
}
}
public static class DeleteAllEntriesAsyncTask extends AsyncTask<Void, Void, Void>{
private EntryDAO entryDAO;
private DeleteAllEntriesAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Void... voids) {
entryDAO.deleteAllEntries();
return null;
}
}
}
EntryDAO.java:
#Dao
public interface EntryDAO {
#Insert
void insert(Entries entries);
#Update
void update(Entries entries);
#Delete
void delete(Entries entries);
#Query("DELETE FROM entries_table")
void deleteAllEntries();
#Query("SELECT * FROM entries_table")
LiveData<List<Entries>> getAllEntries();
}
Entries.java:
#Entity(tableName = "entries_table")
public class Entries {
#PrimaryKey(autoGenerate = true)
private int id;
private String username, hint, password;
public Entries(String username, String hint, String password){
this.username = username;
this.hint = hint;
this.password = password;
}
public Entries(){}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getHint() {return hint;}
public void setHint(String hint) {this.hint = hint;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
}
This is the onCreate() of my AddEditEntry.java class. I've added the following Toast messages to see if it was receiving the data at all and turns out it doesn't. The Toast messages were empty:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addedit_entry);
usernameEditText = findViewById(R.id.username_field);
passwordEditText = findViewById(R.id.password_field);
hintEditText = findViewById(R.id.hint_field);
passwordABCD = findViewById(R.id.upp_checkbox);
passwordabcd = findViewById(R.id.low_checkbox);
password0123 = findViewById(R.id.num_checkbox);
passwordSymbols = findViewById(R.id.sym_checkbox);
radio4 = findViewById(R.id.four);
radio8 = findViewById(R.id.eight);
radio12 = findViewById(R.id.twelve);
radio16 = findViewById(R.id.sixteen);
Button generatePassword = findViewById(R.id.btn_password_generate);
Button saveEntry = findViewById(R.id.btn_save);
Intent intent = getIntent();
if(intent.hasExtra(EXTRA_ID)){
setTitle("Edit Entry");
usernameEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME));
passwordEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD));
hintEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT));
Toast.makeText(this, "Info Received!!!", Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT), Toast.LENGTH_SHORT).show();
}
else{setTitle("Add Entry");}
generatePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {passwordEditText.setText(generatedPassword());}});
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
}
Do it like this
In your MainActivity.java
....
....
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
entry = entries; // this is very important, entry holds the current edited item
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
// no need to pass the id, it's a autogenerated field
// intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
....
...
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
...
...
} else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK) {
// in an Edit operation, id should not be modified, so, no need to pass this parameter
// int id =
// Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
// entry already exists, so, no need to create a new one
//Entries entry = new Entries(username, hint, password);
//entry.setId(id);
entry.setUsername(username);
entry.setPassword(password);
entry.setHint(hint);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Other remarks...
In your RecyclerViewAdapter.java
// This is not needed. Your list is already created in your Room query
//private List<Entries> entries = new ArrayList<>();
private List<Entries> entries;
In your MainActivity.java
// This is not needed
// AddEditEntry addEditEntry;
....
....
// addEditEntry = new AddEditEntry();
I am starting to learn java and android developement and got stuck with passing a custom array from my MainMenu activity to another activity used to print out the values. Can anybody point out where I went wrong?
MainMenu Class:
public class MainMenu extends AppCompatActivity{
SharedPreferences sharedVar;
Controller controller = new Controller();
int size = 100;
Sati[] sati = new Sati[size];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
sharedVar = this.getSharedPreferences("Var", MODE_WORLD_READABLE);
}
#Override
public void onResume(){
super.onResume();
for(int i = 0;i<size;i++) {
if (sati[i] != null){
controller.upisiSmjenu(sati[i],sharedVar.getLong("Datum dolaska",0),sharedVar.getLong("Datum odlaska",0),sharedVar.getLong("Razlika",0));
}
}
}
public void otvoriUnosLayout(View view) {
Intent intent = new Intent(this, UnosSati.class);
startActivity(intent);
}
public void otvoriPregledLayout(View view) {
Intent intent = new Intent(this, PregledSati.class);
intent.putExtra("Sati",sati);
startActivity(intent);
}
}
UnosSati Class(used for data entry):
public class UnosSati extends FragmentActivity {
SharedPreferences sharedVar;
TextView txtRazlika;
Sati sati;
Long razlika;
Date dateD,dateO;
int danD,mjD,godD,SD,MD,danO,mjO,godO,SO,MO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unos_sati);
sharedVar = this.getSharedPreferences("Var",MODE_WORLD_READABLE);
sati = (Sati)getIntent().getParcelableExtra("Sati");
dateD = new Date();
dateO = new Date();
txtRazlika = (TextView) findViewById(R. id. txtRazlika);
razlika = 0L;
txtRazlika.setText(String.valueOf(razlika));
danD = sharedVar.getInt("DanD",0);
mjD = sharedVar.getInt("MjD",0);
godD = sharedVar.getInt("GodD",0)-1900;
SD = sharedVar.getInt("SD",0);
MD = sharedVar.getInt("MD",0);
danO = sharedVar.getInt("DanO",0);
mjO = sharedVar.getInt("MjO",0);
godO = sharedVar.getInt("GodO",0)-1900;
SO = sharedVar.getInt("SO",0);
MO = sharedVar.getInt("MO",0);
dateD.setDate(danD);
dateD.setMonth(mjD);
dateD.setYear(godD);
dateD.setHours(SD);
dateD.setMinutes(MD);
dateO.setDate(danO);
dateO.setMonth(mjO);
dateO.setYear(godO);
dateO.setHours(SO);
dateO.setMinutes(MO);
razlika =((dateO.getTime() - dateD.getTime())/60000)/60;
txtRazlika.setText(String.valueOf(razlika));
}
public void vratiNaGlavni(View view){
sharedVar.edit().putLong("Datum dolaska", dateD.getTime()).commit();
sharedVar.edit().putLong("Datum odlaska", dateO.getTime()).commit();
sharedVar.edit().putLong("Razlika",razlika).commit();
Intent intent = new Intent(this,MainMenu.class);
startActivity(intent);
}
public void otvoriKalendarDolaskaLayout(View view) {
Intent intent = new Intent(this, Datum_dolaska.class);
startActivity(intent);
}
public void otvoriSatDolaskaLayout(View view) {
Intent intent = new Intent(this, Sat_dolaska.class);
startActivity(intent);
}
public void otvoriKalendarOdlaskaLayout(View view) {
Intent intent = new Intent(this, Datum_odlaska.class);
startActivity(intent);
}
public void otvoriSatOdlaskaLayout(View view) {
Intent intent = new Intent(this, Sat_odlaska.class);
startActivity(intent);
}
}
PregledSati Class used for viewing the data:
public class PregledSati extends AppCompatActivity {
TextView textView1,textView2,textView3,textView4,textView5,textView6;
Date dateD,dateO;
String printD,printO,printR;
Sati[] sati;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pregled_sati);
dateD = new Date();
dateO = new Date();
printD = printO = printR = "";
textView1 = (TextView) findViewById(R. id. txtIspis1);
textView2 = (TextView) findViewById(R. id. txtispis2);
textView3 = (TextView) findViewById(R. id. txtispis3);
Bundle extras = getIntent().getExtras();
Sati[] sati = getIntent().getParcelableExtra("Sati");
for(int i = 0;i<100;i++){
textView1.append(String.valueOf(sati[i].getDateDolaska()));
textView1.append("\n");
}
}
}
Sati class:
public class Sati implements Parcelable{
public long dateDolaska, dateOdlaska,ukupnoVrijeme;
public Sati() {
super();
}
public Sati(Parcel dest) {
this.dateDolaska=dest.readLong();
this.dateOdlaska=dest.readLong();
this.ukupnoVrijeme=dest.readLong();
}
public long getDateDolaska() { return dateDolaska; }
public void setDateDolaska(long dateDolaska) {
this.dateDolaska = dateDolaska;
}
public long getDateOdlaska() {
return dateOdlaska;
}
public void setDateOdlaska(long dateOdlaska) {
this.dateOdlaska = dateOdlaska;
}
public long getUkupnoVrijeme() {
return ukupnoVrijeme;
}
public void setUkupnoVrijeme(long ukupnoVrijeme) {
this.ukupnoVrijeme = ukupnoVrijeme;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.dateDolaska);
dest.writeLong(this.dateOdlaska);
dest.writeLong(this.ukupnoVrijeme);
}
public static final Creator<Sati> CREATOR=new Creator<Sati>() {
#Override
public Sati createFromParcel(Parcel dest) {
return new Sati(dest);
}
#Override
public Sati[] newArray(int size) {
return new Sati[size];
}
};
}
I think is because you have to get an array of Parcelables and be sure that class Sati is Parcelable.
Sati[] sati = getIntent().getParcelableArrayExtra("Sati");
I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}