NullPointerException when insertData() called in android [duplicate] - sqlite

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();
}

Related

Toast message does not appear if the user click on sign up or login, also the favourite button on home fragment are always checked

i wrote a toast message that when the user click on sign up or log in a toast message pop up, but when i sign up the app continue without toast message, also when the user enters the app all the pictures favourite button are checked, how can i make them only checked if the user clicks on them?
Signup.class
public class Signup extends AppCompatActivity {
EditText username, password, repassword, email;
Button signup, login;
FavDB DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
repassword = (EditText) findViewById(R.id.repassword);
signup = (Button) findViewById(R.id.btnsignup);
login = (Button) findViewById(R.id.btn_login);
DB = new FavDB(this);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
String repass = repassword.getText().toString();
if (user.equals("")|| pass.equals("")|| repass.equals(""))
Toast.makeText(Signup.this,"Please Enter All Information", Toast.LENGTH_SHORT).show();
else {
if (pass.equals(repass)){
Boolean checkuser = DB.checkusername(user);
if (checkuser==false){
Boolean insert = DB.insertData(user, pass);
if (insert==true) {
Toast.makeText(Signup.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), HomeFragment.class);
startActivity(intent);
}else{
Toast.makeText(Signup.this,"Registered Failed", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(Signup.this, "User Already Exists, Please Login", Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(Signup.this, "Password Not Matching",Toast.LENGTH_SHORT).show();
}
} }});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),Login.class);
startActivity(intent);
}
}); }
login.class
public class Login extends AppCompatActivity {
EditText username, password;
Button btn_login;
FavDB DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//getActionBar().setDisplayHomeAsUpEnabled(true);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
btn_login = (Button) findViewById(R.id.btn_login);
DB = new FavDB(this);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
if (user.equals("") || pass.equals(""))
Toast.makeText(Login.this, "Please enter Username and Password", Toast.LENGTH_SHORT).show();
else {
Boolean checkuserpass = DB.checkusernamepassword(user, pass);
if (checkuserpass == true) {
Toast.makeText(Login.this, "Login successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), HomeFragment.class);
startActivity(intent);
//finish();
} else {
Toast.makeText(Login.this, "Invalid Entries", Toast.LENGTH_SHORT).show();
} } }
}); }}
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
}}
HomeFragment.class "where the signup and login should direct to"
public class HomeFragment extends Fragment{
private ArrayList<DrawingItem> drawingItems = new ArrayList<>();
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
RecyclerView recyclerView = root.findViewById(R.id.recycleView);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(new DrawingAdapter(drawingItems, getActivity()));
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
drawingItems.add(new DrawingItem(R.drawable.girl_with_a_pearl_earing, "Girls with a pearl Earring","0","0",getString(R.string.drawing1_desc)));
drawingItems.add(new DrawingItem(R.drawable.self_portait_ear, "Self Portrait Ear","1","0",getString(R.string.drawing2_desc)));
drawingItems.add(new DrawingItem(R.drawable.vase, "Vase with 12 Sunflowers","2","0",getString(R.string.drawing3_desc)));
drawingItems.add(new DrawingItem(R.drawable.night_cafe, "Coffee Terrace at Night","3","0",getString(R.string.drawing4_desc)));
drawingItems.add(new DrawingItem(R.drawable.gurnica, "Guernica","4","0",getString(R.string.drawing5_desc)));
drawingItems.add(new DrawingItem(R.drawable.the_scream, "The Scream","5","0",getString(R.string.drawing6_desc)));
drawingItems.add(new DrawingItem(R.drawable.the_falling_rocket, "Nocturne in Black and Gold, the Falling Rocket","6","0",getString(R.string.drawing7_desc)));
drawingItems.add(new DrawingItem(R.drawable.monalisa, "Monalisa","7","0",getString(R.string.drawing8_desc)));
drawingItems.add(new DrawingItem(R.drawable.impresstion_sunrise, "Impression, Sunrise","8","0",getString(R.string.drawing9_desc)));
drawingItems.add(new DrawingItem(R.drawable.the_last_supper,"The Last Supper", "9","0",getString(R.string.drawing9_desc)));
drawingItems.add(new DrawingItem(R.drawable.water_lilies, "Water Lilies","10","0",getString(R.string.drawing10_desc)));
drawingItems.add(new DrawingItem(R.drawable.the_magpie, "The Magpie","11","0",getString(R.string.drawing11_desc)));
return root;
}}
Manifest
<activity
android:name=".Signup"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Login"
android:exported="false">
</activity>
<activity
android:name=".MainActivity"
android:exported="false"
android:parentActivityName=".Signup"
android:label="#string/app_name">
</activity>
Database helper
public class FavDB extends SQLiteOpenHelper {
public static final String DBNAME = "Login";
private static int DB_VERSION = 1;
private static String DATABASE_NAME = "favouriteDB";
private static String TABLE_NAME = "favoriteTable";
public static String KEY_ID = "id";
public static String ITEM_TITLE = "itemTitle";
public static String ITEM_IMAGE = "itemImage";
public static String FAVORITE_STATUS = "fStatus";
public static String ITEM_DESC ="itemDesc";
private static String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " TEXT," + ITEM_TITLE+ " TEXT,"
+ ITEM_IMAGE + " TEXT," + FAVORITE_STATUS+" TEXT,"
+ ITEM_DESC + " TEXT)";
public FavDB(Context context) { super(context,"Login",null,DB_VERSION);}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create Table users(username TEXT primary key, password Text)");
sqLiteDatabase.execSQL(CREATE_TABLE);
}
public Boolean insertData(String username, String password){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", username);
contentValues.put("password", password);
long result = sqLiteDatabase.insert("users", null, contentValues);
if (result==1)return false;
else
return true;
}
public Boolean checkusername(String username){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("Select * from users where username = ?", new String[]{username});
if (cursor.getCount() > 0) return true;
else
return false;
}
public Boolean checkusernamepassword(String username, String password){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("Select * from users where username = ? and password = ?", new String[] {username,password});
if (cursor.getCount() > 0) return true;
else
return false;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop Table if exists users");
}
public void insertEmpty() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for (int x = 1; x < 13; x++) {
cv.put(KEY_ID, x);
cv.put(FAVORITE_STATUS, "0");
db.insert(TABLE_NAME,null, cv);
}
}
public void insertIntoTheDatabase(String item_title, int item_image, String id, String fav_status) {
SQLiteDatabase db;
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ITEM_TITLE, item_title);
cv.put(ITEM_IMAGE, item_image);
cv.put(KEY_ID, id);
cv.put(FAVORITE_STATUS, fav_status);
// cv.put(ITEM_DESC,item_desc);
db.insert(TABLE_NAME,null, cv);
Log.d("FavDB Status", item_title + ", favstatus - "+fav_status+" - . " + cv);
}
public Cursor read_all_data(String id) {
SQLiteDatabase db = this.getReadableDatabase();
String sql = "select * from " + TABLE_NAME + " where " + KEY_ID+"="+id+"";
return db.rawQuery(sql,null,null);
}
public void remove_fav(String id) {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET "+ FAVORITE_STATUS+" ='0' WHERE "+KEY_ID+"="+id+"";
db.execSQL(sql);
Log.d("remove", id.toString());
}
public Cursor select_all_favorite_list() {
SQLiteDatabase db = this.getReadableDatabase();
String sql = "SELECT * FROM "+TABLE_NAME+" WHERE "+FAVORITE_STATUS+" ='1'";
return db.rawQuery(sql,null,null);
}}

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

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);
}
});
}
}

Search in Fragments that hold Recyclerview

I have 3 Fragments and they all are holding a recyclerView. But I don't know how I should call adapter.getFilter().filter(newText); in onQueryTextChange. Any ideas?
MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
private BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDB = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----Start Bottom Navigation Bar
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(bottomNavMethod);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new PasswortFragment()).commit();
String id = getResources().getResourceEntryName(bottomNavigationView.getId());
//----End Bottom Navigation Bar
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return true;
}
private BottomNavigationView.OnNavigationItemSelectedListener bottomNavMethod =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch(item.getItemId()){
case R.id.passwoerter:
fragment = new PasswortFragment();
break;
case R.id.bankdaten:
fragment = new BankdatenFragment();
break;
case R.id.kreditkarten:
fragment = new KreditkartenFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
return true;
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment f = MainActivity.this.getSupportFragmentManager().findFragmentById(R.id.container);
if(f instanceof PasswortFragment)
recyclerView = findViewById(R.id.recyclerViewPasswoerter);
if(f instanceof KreditkartenFragment)
recyclerView = findViewById(R.id.recyclerViewKreditkarten);
if(f instanceof BankdatenFragment)
recyclerView = findViewById(R.id.recyclerViewBankdaten);
}
#Override
public boolean onCreateOptionsMenu(#NonNull Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recyclerView.getAdapter().getFilter().filter(newText); //<--This is not working
return false;
}
});
return true;
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements Filterable{
String type;
List<String> dataAll, data1;
Context context;
public Adapter(Context ct, List<String> s1, String typ){
context = ct;
data1 = s1;
type = typ;
dataAll = new ArrayList<>(data1);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.reihen, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.mytext1.setText(data1.get(position));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(type.equals("Passwoerter")){
Intent intent = new Intent(context, DetailsP.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Kreditkarten")){
Intent intent = new Intent(context, DetailsK.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
} else if(type.equals("Bankdaten")){
Intent intent = new Intent(context, DetailsB.class);
intent.putExtra("data1", data1.get(position));
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return data1.size();
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<String> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0){
filteredList.addAll(dataAll);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(String item: dataAll){
if(item.toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
data1.clear();
data1.addAll( (List) results.values);
notifyDataSetChanged();
}
};
;
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView mytext1;
ConstraintLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mytext1 = itemView.findViewById(R.id.title);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
PasswortFragment (the other two fragments are pretty much the same):
public class PasswortFragment extends Fragment {
public PasswortFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
String tabelle = "Passwort";
List<String> titel;
DatabaseHelper myDB;
Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_passwort, container, false);
myDB = new DatabaseHelper(getActivity());
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewPasswoerter);
titel = Arrays.asList(myDB.getItems(tabelle));
final LinearLayoutManager layoutManager = new LinearLayoutManager((getActivity()));
layoutManager.setOrientation((LinearLayoutManager.VERTICAL));
recyclerView.setLayoutManager(layoutManager);
adapter = new Adapter(getActivity(), titel, "Passwoerter");
recyclerView.setAdapter(adapter);
setHasOptionsMenu(true);
return view;
}

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
}`

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