How do you delete a specific table in sqlite in android studio? - sqlite

Ive got an app that im creating where i want to be able to type in the users username and click delete then it will delete all of the data for that specific user, Eg-address, phone, birthdate. But for some reason when on the manage user activity when i click the remove button which should take me to the remove activity it takes me back to the main activity instead! Can anyone see what ive done wrong please!!!
Remove class:
public class Remove extends AppCompatActivity {
DatabaseHelperUser myDb;
Button btRemove = findViewById(R.id.buttonRemove);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remove);
final EditText etUser = findViewById(R.id.editTextUser);
myDb = new DatabaseHelperUser(this);
btRemove.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Integer deletedRows = myDb.deleteData(etUser.getText().toString());
if(deletedRows > 0){
Toast.makeText(getApplicationContext(), "Data Deleted", Toast.LENGTH_LONG).show();}
else{
Toast.makeText(getApplicationContext(), "Data has not been Deleted", Toast.LENGTH_LONG).show();}
}
});
}
}
DatabaseHelperUser class:
public class DatabaseHelperUser extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "User.db";
public static final String TABLE_NAME = "User_table";
public static final String COL1 = "UserNum";
public static final String COL2 = "UserName";
public static final String COL3 = "Password";
public static final String COL4 = "BirthDate";
public static final String COL5 = "Phone";
public static final String COL6 = "Address";
public DatabaseHelperUser(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (UserNum TEXT,UserName Text,Password Text,BirthDate Text,Phone Text,Address Text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public Integer deleteData(String UserName){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName = ?", new String[] {UserName});
}
}
Manage user class:
public class ManagingUsers extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managing_users);
final Button btadd = findViewById(R.id.buttonAdd);
final Button btInventory = findViewById(R.id.buttonInventory2);
final Button btView = findViewById(R.id.buttonView);
final Button btRemove = findViewById(R.id.buttonRemove);
btadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Add.class);
startActivity(i);
}
});
btInventory.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Inventory.class);
startActivity(i);
}
});
btView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), com.example.assignment3.View.class);
startActivity(i);
}
});
btRemove.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), com.example.assignment3.Remove.class);
startActivity(i);
}
});
}
}

Related

Using FirestoreRecyclerAdapter but phone's screen looks separately

I'm using FirestoreRecyclerAdapter and faced with the problem.
My challenge is that I can add documents and retrieve them the recyclerview but for some reason, thw phone's screen looks separately as attached phone's schreenshot.
how can I do?
Thank You.
This is Adapter;
public MyFriendsAdapter(#NonNull FirestoreRecyclerOptions<ProfileModelClass> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MyFriendsViewholder holder, int position, #NonNull ProfileModelClass model)
{
holder.myNickname.setText(model.getNickname());
holder.myAge.setText(model.getAge());
holder.myGender.setText(model.getGender());
holder.myDistance.setText(model.getDistance());
holder.myUserDescription.setText(model.getUserDescription());
holder.myMarriage.setText(model.getMarriage());
holder.myAddress.setText(model.getAddress());
// String visit_user_id = getSnapshots().getSnapshot(position).getId();
// Intent chatIntent = new Intent(MainActivity.this, ChatActivity.class);
// chatIntent.putExtra("visit_user_id", visit_user_id);
// startActivity(chatIntent);
Glide.with(holder.myProfileImageView.getContext()).load(model.getProfileImage()).into(holder.myProfileImageView);
Glide.with(holder.myPictureOne.getContext()).load(model.getPictureOne()).into(holder.myPictureOne);
Glide.with(holder.myPictureTwo.getContext()).load(model.getPictureTwo()).into(holder.myPictureTwo);
}
#NonNull
#Override
public MyFriendsViewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_friends_list_layout,
parent, false);
return new MyFriendsViewholder(view);
}
class MyFriendsViewholder extends RecyclerView.ViewHolder
{
CircleImageView myProfileImageView;
TextView myNickname,myAge, myGender, myDistance, myUserDescription, myMarriage, myAddress,
myFriendsProfile, SendMessageButton;
ImageView myPictureOne, myPictureTwo;
public MyFriendsViewholder(#NonNull View itemView)
{
super(itemView);
myProfileImageView = itemView.findViewById(R.id.all_friends_profile_image_layout);
myNickname = itemView.findViewById(R.id.all_friends_nickname_layout);
myGender = itemView.findViewById(R.id.all_friends_gender_layout);
myAge = itemView.findViewById(R.id.all_friends_age_layout);
myDistance = itemView.findViewById(R.id.all_friends_distance_layout);
myUserDescription = itemView.findViewById(R.id.all_friends_description_layout);
myMarriage = itemView.findViewById(R.id.all_friends_marriage_layout);
myAddress = itemView.findViewById(R.id.all_friends_address_layout);
myPictureOne = itemView.findViewById(R.id.all_friends_post_image_first);
myPictureTwo = itemView.findViewById(R.id.all_friends_post_image_second);
myFriendsProfile = itemView.findViewById(R.id.all_friends_information_layout);
SendMessageButton = itemView.findViewById(R.id.all_friends_call_layout);
myFriendsProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
itemView.getContext().startActivity(new Intent(itemView.getContext(), ProfileActivity.class));
}
});
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
itemView.getContext().startActivity(new Intent(itemView.getContext(), ChatActivity.class));
}
});
}
This is MainActivity;
private DatabaseReference UsersRef;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference firstUsersProfilesColRef = db.collection("usersProfiles");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestoreList = findViewById(R.id.all_users_list);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("allUsers");
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("홈");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ToolbarProfileBtn = (ImageButton) findViewById(R.id.toolbar_profile_button);
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ToolbarProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SendUserToSetupActivity();
}
});
DisplayAllUsersList();
}
private void DisplayAllUsersList()
{
Query salaryQuery = firstUsersProfilesColRef;
FirestoreRecyclerOptions<ProfileModelClass> options = new FirestoreRecyclerOptions.Builder<ProfileModelClass>()
.setQuery(salaryQuery, ProfileModelClass.class)
.build();
adapter = new MyFriendsAdapter(options);
mFirestoreList.setHasFixedSize(true);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
}
#Override
protected void onStart()
{
super.onStart();
adapter.startListening();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
This is phone's screenshot;
enter image description here
In your layout file all_friends_list_layout. I think you have used android:layout_height="match_parent"
so there you need to use
android:layout_height="wrap_content"
Or instead of wrap_content you can also use any value like 150dp or whatever you feel appropriate for your need.

Stay login with using PhoneNumber [duplicate]

This question already has answers here:
One time login in app - FirebaseAuth
(3 answers)
Closed 4 years ago.
After I sign in with PhoneNumber Auth it's will take me into Profile activity, I want that stay log in into the application if I go out and close it from used apps and come back again to the application that I won't be still log in.
the following the Java Code of PhoneNumber Auth and the Profile
VerifyPhoneActivity.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
editText = findViewById(R.id.editTextCode);
String phonenumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phonenumber);
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length()<6){
editText.setError("enter Code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent intent = new Intent(VerifyPhoneActivity.this, List.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else{
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
private void sendVerificationCode(String phonenumber){
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonenumber,
10,
TimeUnit.SECONDS,
this,
mCallbacks
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null){
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
};
Child_Profile.Java
public class Child_Profile extends AppCompatActivity {
private TextView name;
private TextView gender;
private TextView birth;
private TextView bload;
private TextView Text_Dates;
private TextView Text_Time;
private Button Button_record;
private TextView Text_record;
private TextView Text_hospial;
private TextView Text_Plan;
private TextView Text_Satus;
private TextView Text_Price;
private ImageView ImageView_choose_image;
private Button button_choose_image;
private Uri mUri;
private static final int GALLERY_INTENT = 1;
private StorageReference mStorage;
private DatabaseReference mData;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_sign_out)
signOut();
return true;
}
private void signOut() {
AuthUI.getInstance().signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Child_Profile.this, User.class));
finish();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child__profile);
name = findViewById(R.id.text_view_Namee);
gender = findViewById(R.id.text_view_Gender);
birth = findViewById(R.id.text_view_Birth);
bload = findViewById(R.id.text_view_Blood);
Text_Dates = findViewById(R.id.Text_Dates);
Text_Time = findViewById(R.id.Text_Time);
Text_record = findViewById(R.id.Text_record);
Text_hospial = findViewById(R.id.Text_hospial);
Text_Plan = findViewById(R.id.Text_Plan);
Text_Satus = findViewById(R.id.Text_Satus);
Button_record = findViewById(R.id.Button_record);
Text_Price = findViewById(R.id.Text_Price);
button_choose_image = findViewById(R.id.button_choose_image);
ImageView_choose_image = findViewById(R.id.ImageView_choose_image);
mStorage = FirebaseStorage.getInstance().getReference("Photo");
mData = FirebaseDatabase.getInstance().getReference("Photo");
button_choose_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openFileChooser();
}
});
Intent in = getIntent();
final Bundle b = in.getExtras();
if (b != null) {
String n = (String) b.get("id");
db.collection("Child Profile").document(n).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String pName = documentSnapshot.getString("name");
String pgender = documentSnapshot.getString("gender");
String pbirth = documentSnapshot.getString("birth");
String pbload = documentSnapshot.getString("bload");
String pDates = documentSnapshot.getString("dates");
String pTime = documentSnapshot.getString("time");
String pHospital = documentSnapshot.getString("hospital");
String pPlan = documentSnapshot.getString("typeOfPlan");
String pSatus = documentSnapshot.getString("satus");
String pPrice = documentSnapshot.getString("price");
name.setText(pName);
gender.setText(pgender);
birth.setText(pbirth);
bload.setText(pbload);
Text_Dates.setText(pDates);
Text_Time.setText(pTime);
Text_hospial.setText(pHospital);
Text_Plan.setText(pPlan);
Text_Satus.setText(pSatus);
Text_Price.setText(pPrice);
}
});
}
}
List.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_List);
mAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
FloatingActionButton aaa = findViewById(R.id.button_add_profile);
aaa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), NewChild.class);
startActivity(i);
}
});
}
private void setUpRecyclerView() {
Query query = profileRef.whereEqualTo("user_id", FirebaseAuth.getInstance().getCurrentUser().getUid());
FirestoreRecyclerOptions<addp> options = new FirestoreRecyclerOptions.Builder<addp>()
.setQuery(query, addp.class)
.build();
adapter = new padapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_View);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new padapter.OnItemClickListener()
{
#Override
public void onItemClick (DocumentSnapshot documentSnapshot,int position){
String id = documentSnapshot.getId();
Toast.makeText(Profile.this, "Position: " + position + "ID" + id, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Child_Profile.class);
i.putExtra("id", id);
startActivity(i);
}
});
ProfileActivity set as launcher activity and
add line of code at onCreate of ProfileAtivity
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null){
Intent intent=new Intent(ProfileActivity,this,LoginActivity.class);
startActivity(intent);
finish()
}
else{
//stay here
}`

How to get data from RecyclerView item position

Good evening. I'm stuck on this problem. I'm populating a RecyclerView with data from Firebase Realtime Database. This part is ok, it's work well. My doubt is how I get the firebase id from the user on the click event. As the id not shows in the layout, I have no ideia how I can work with this data. Here the class:
Adapter
public class TecnicosAdapter extends RecyclerView.Adapter<TecnicosViewHolders>{
private List<TecnicosObject> tecnicosList;
private Context context;
public TecnicosAdapter (List<TecnicosObject> tecnicosList, Context context){
this.tecnicosList = tecnicosList;
this.context = context;
}
#NonNull
#Override
public TecnicosViewHolders onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tecnicos, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
TecnicosViewHolders rcv = new TecnicosViewHolders((layoutView));
return rcv;
}
#Override
public void onBindViewHolder(#NonNull TecnicosViewHolders holder, int position) {
// holder.mTecnicoId.setText(tecnicosList.get(position).getUsuarioId());
holder.mTecnicoNome.setText(tecnicosList.get(position).getNome());
holder.mTecnicoProfissao.setText(tecnicosList.get(position).getProfissao());
if (!tecnicosList.get(position).getImagemPerfilUrl().equals("default")){
Glide.with(context).load(tecnicosList.get(position).getImagemPerfilUrl()).into(holder.mTecnicoImagem);
}
}
public TecnicosObject getItem(int position){
return tecnicosList.get(position);
}
#Override
public int getItemCount() {
return this.tecnicosList.size();
}
}
Model
public class TecnicosObject {
private String usuarioId;
private String nome;
private String profissao;
private String imagemPerfilUrl;
public TecnicosObject(String usuarioId, String nome, String profissao, String imagemPerfilUrl) {
this.usuarioId = usuarioId;
this.nome = nome;
this.profissao = profissao;
this.imagemPerfilUrl = imagemPerfilUrl;
}
public String getUsuarioId() {
return usuarioId;
}
public void setUsuarioId(String usuarioId) {
this.usuarioId = usuarioId;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getImagemPerfilUrl() {
return imagemPerfilUrl;
}
public void setImagemPerfilUrl(String imagemPerfilUrl) {
this.imagemPerfilUrl = imagemPerfilUrl;
}
}
ViewHolder
public class TecnicosViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mTecnicoNome, mTecnicoProfissao;
public ImageView mTecnicoImagem;
private Context context;
String clienteId;
private Bundle extras;
public TecnicosViewHolders(View itemView) {
super(itemView);
this.context = context;
mTecnicoNome = (TextView) itemView.findViewById(R.id.TecnicoNome);
mTecnicoProfissao = (TextView) itemView.findViewById(R.id.TecnicoProfissao);
mTecnicoImagem = (ImageView) itemView.findViewById(R.id.TecnicoImagem);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos!=RecyclerView.NO_POSITION){
}
}
}
Main Activity
public class TelaTecnicos extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mTecnicosAdapter;
private RecyclerView.LayoutManager mTecnicosLayoutManager;
private String usuarioAtualID;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tela_tecnicos);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
usuarioAtualID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerView.setHasFixedSize(true);
mTecnicosLayoutManager = new LinearLayoutManager(TelaTecnicos.this);
mRecyclerView.setLayoutManager(mTecnicosLayoutManager);
mTecnicosAdapter = new TecnicosAdapter(getDataSetTecnicos(), TelaTecnicos.this);
mRecyclerView.setAdapter(mTecnicosAdapter);
getUsuarioTecnicoId();
}
private void getUsuarioTecnicoId() {
DatabaseReference tecnicoDb = FirebaseDatabase.getInstance().getReference().child("Usuarios").child("Clientes").child(usuarioAtualID).child("conexoes").child("tecnicos");
tecnicoDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot tecnico: dataSnapshot.getChildren()){
FetchtecnicoInformation(tecnico.getKey());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void FetchtecnicoInformation(final String key) {
DatabaseReference usuarioDb = FirebaseDatabase.getInstance().getReference().child("Usuarios").child("Tecnicos").child(key);
usuarioDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String usuarioId = dataSnapshot.getKey();
String nome = "";
String profissao = "";
String imagemPerfilUrl = "";
if (dataSnapshot.child("nome").getValue()!=null){
nome = dataSnapshot.child("nome").getValue().toString();
}
if (dataSnapshot.child("profissao").getValue()!=null){
profissao = dataSnapshot.child("profissao").getValue().toString();
}
if (dataSnapshot.child("imagemPerfilUrl").getValue()!=null){
imagemPerfilUrl = dataSnapshot.child("imagemPerfilUrl").getValue().toString();
}
TecnicosObject obj = new TecnicosObject(usuarioId, nome, profissao, imagemPerfilUrl);
resultmTecnicos.add(obj);
mTecnicosAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private ArrayList<TecnicosObject> resultmTecnicos = new ArrayList<TecnicosObject>();
private List<TecnicosObject> getDataSetTecnicos() {
return resultmTecnicos;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
Someone have a tip? Thanks.
Put this in your ViewHolder onclick() method technicoId = technicolist.get(pos.getId())
The implementation should look like this ->>
`
String technicoId = "";
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos!=RecyclerView.NO_POSITION){
technicoId = technicolist.get(pos).getId();
}
}
`
Edit:
if your view holder is in a separate file it is better you implement viewholder class in the adapter class(that's what I do) so you can easily reference technicolist in viewholder. it will look like this
`
public class TecnicosAdapter extends RecyclerView.Adapter<TecnicosViewHolders>{
private List<TecnicosObject> tecnicosList;
....other methods
class TecnicosViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
//you can use tecnicolist here
#Override
public void onClick(View v){
....
}
}
}
`

NullPointerException when insertData() called in android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am currently working on android stenography project,
but at registration time the error was occur
"java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.devd.stangnograpyonimage.DBHelper.insertData(java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference"
DataBaseHelper.java
public static final String DATABASE_NAME = "STAGNODB";
public static final String TABLE_NAME = "Satgno_Table";
//public static final String COLUUMN_ID = "ID";
public static final String COLUUMN_USERNAME = "UserName";
public static final String COLUUMN_PASSWORD = "Password";
public static final String COLUUMN_NAME = "Name";
public static final String COLUUMN_EMAIL = "Email";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + COLUUMN_USERNAME + " VARCHAR(50),"
+ COLUUMN_PASSWORD + " VARCHAR(50),"
+ COLUUMN_NAME + " VARCHAR(50),"
+ COLUUMN_EMAIL + " VARCHAR(50));", null);
}catch (Exception e){
Log.e("SQL Table Creation ", "Table Not Created");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public boolean insertData(String userName, String password, String name, String email){
SQLiteDatabase mydb = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUUMN_USERNAME, userName);
cv.put(COLUUMN_PASSWORD, password);
cv.put(COLUUMN_NAME, name);
cv.put(COLUUMN_EMAIL, email);
long result = mydb.insert(TABLE_NAME, null, cv);
if(result == -1){
return false;
}
else {
return true;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DBHelper myDB;
EditText etUserName, etPassword, etName, etEmail;
Button btnRegister, btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.etUserName);
etPassword = (EditText) findViewById(R.id.etPassword);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLogin = (Button) findViewById(R.id.btnLogin);
register();
}
public void register() {
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDB.insertData(etUserName.getText().toString(), etPassword.getText().toString(), etName.getText().toString(), etEmail.getText().toString());
if(isInserted==true){
Toast.makeText(MainActivity.this,"Data Inserted", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,"Data not Inserted", Toast.LENGTH_LONG).show();
}
}
});
}
}
In your activity class, you have not initialized the variable DBHelper myDB. Thus when your activity calls
myDB.insertData(etUserName.getText().toString(), ...
You get a NullPointerException because myDB is null. To fix this, create the object in the onCreate method of your activity
myDB = new DBHelper(this);
You are declaring but not instantiating myDB so it is null.
i.e.
DBHelper myDB;
Just declares myDB so it is null at this point as nothing has been assigned to the variable.
You need to add something like :-
myDB = new DBHelper(this);
In the onCreate method of the MainActivity.
e.g. :-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.etUserName);
etPassword = (EditText) findViewById(R.id.etPassword);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLogin = (Button) findViewById(R.id.btnLogin);
myDB = new DBHelper(this); //<<<< ADDED
register();
}

overwriting my strings on item click and i can not delete from database

When i press "Lägg till(Add)" i put textin my three edittext boxes, then i'll press OK and it should save it in database and display it in my listview with the first editbox text as tite. When i press on a item in my listview i want to be abel to show inputed text and if i press "RADERA(delete)" i want to be able to delete it from databas and listview.
my database adapter
package com.projekt;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
static final String KEY_ROWID = "id";
static final String KEY_PASS = "pass";
static final String KEY_USERNAME = "user";
static final String KEY_TITLE = "title";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "DBPASS";
static final String DATABASE_TABLE = "information";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table information (id integer primary key autoincrement, "
+ "user text not null, pass text not null, title text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
// ---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public long insertInfo(String title, String user, String pass) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASS, pass);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteInfo(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public void delete_byID(int id){
db.delete(DATABASE_TABLE, KEY_ROWID+"="+id, null);
}
public Cursor getAllInfo() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_USERNAME,
KEY_PASS, KEY_TITLE }, null, null, null, null, null);
}
public Cursor getInfo(String title) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_USERNAME, KEY_PASS, KEY_TITLE }, KEY_PASS + "= '" + title + "'",
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateInfo(long rowId, String title, String user, String pass) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_USERNAME, user);
args.put(KEY_PASS, pass);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
my program
package com.projekt;
import java.util.ArrayList;
//import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
//import android.text.Editable;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
public class layout2 extends Activity implements OnClickListener, OnItemClickListener {
Button btn3;
ListView lv;
private ArrayAdapter<String> listAdapter;
String titleInfo;
ArrayList<String> nameList;
EditText anvNamn;
EditText pass;
EditText title;
DBAdapter db = new DBAdapter(this);
String passInfo = "";
String anv = "";
String titleInfo2 = "";
String visa;
int del;
Cursor c;
Button btn5;
public void onCreate(Bundle savedInstanceState) {
//Start
super.onCreate(savedInstanceState);
setContentView(R.layout.program_layout);
btn3 = (Button) findViewById(R.id.button3);
btn3.setOnClickListener(this);
btn5 = (Button) findViewById(R.id.button5);
btn5.setOnClickListener(this);
lv = (ListView) findViewById(R.id.listView1);
nameList = new ArrayList<String>();
listAdapter = new ArrayAdapter<String>(this, R.layout.row, nameList);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(this);
getAllData();
//Stop
}
private ArrayList<String> getAllData() {
// ---get all contacts---
db.open();
c = db.getAllInfo();
if (c.moveToFirst()) {
do {
anv = c.getString(1);
passInfo = c.getString(2);
titleInfo2 = c.getString(3);
//in = new String (anv, passInfo, titleInfo2);
//nameList.add(in);
listAdapter.add(titleInfo2);
//updateList();
} while (c.moveToNext());
//listAdapter.add(titleInfo2);
//del = c.getInt(c.getColumnIndex(db.KEY_ROWID));
}
db.close();
//listAdapter.add(titleInfo2);
return nameList;
}
public void inputDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout lila1 = new LinearLayout(this);
lila1.setOrientation(1);
anvNamn = new EditText(this);
pass = new EditText(this);
title = new EditText(this);
lila1.addView(title);
lila1.addView(anvNamn);
lila1.addView(pass);
title.setText("Titel");
anvNamn.setText("Användarnamn");
pass.setText("Lösenord");
alert.setView(lila1);
title.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
title.setText("");
}
});
anvNamn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
anvNamn.setText("");
}
});
pass.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
pass.setText("");
}
});
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String titleDB = title.getText().toString();
String userDB = anvNamn.getText().toString();
String passDB = pass.getText().toString();
listAdapter.add(titleDB);
db.open();
db.insertInfo(titleDB, userDB, passDB);
db.close();
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button3:
inputDialog();
break;
case R.id.button5:
Intent nextActivity = new Intent(this, MainActivity.class);
startActivity(nextActivity);
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
// TODO Auto-generated method stub
String text = nameList.get(arg2);
//final int ar = arg2;
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(titleInfo2);
alert.setMessage("Användarnamn: " + anv + "\nLösenord: "+ passInfo);
final String radera = listAdapter.getItem(arg2).toString();
final long raderaPos = listAdapter.getItemId(arg2);
alert.setNegativeButton("RADERA",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//String s = (String) arg0.getItemAtPosition(arg2);
db.open();
//db.updateInfo(arg2, anv, passInfo, titleInfo);
db.deleteInfo(arg2);
db.updateInfo(arg2, anv, passInfo, titleInfo);
db.close();
listAdapter.remove(radera);
}
});
alert.show();
}
}
im from sweden my string names may be confusing.
Never ever use parameter names like arg0,1,...
It is impossible to understand code that uses such names.
Apparently, in some places, the code uses arg2 (the position of the view in the adapter) where it should use arg3 (the item's row id).

Resources