I'm working with Firebase's realtime database in order to make a recipe application in android studio. The code runs fine and nothing crashes, but every time it's supposed to send information to the database, it does not. I attempted to create a shell for it to put data into, and instead, I saw it erase it once it got past the part where it was supposed to send the data. I've done all the required imports, implementations and dependencies according to their documentation, as well as wrote the code according to it too, but it doesn't seem to work.
Firebase Realtime Database before I send data, plus rules screenshot:
Firebase RD before
Firebase RD rules
After it runs the logic to send the data, I see it go red and disappear, like it was deleted, and nothing is left behind.
Here is my HomeScreen.java code:
package com.capteamfour.recipeappdatabase;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class HomeScreen extends AppCompatActivity {
final FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseUsers = mDatabase.getReference("USERS");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
newUser(FirebaseAuth.getInstance().getCurrentUser().getDisplayName(),
FirebaseAuth.getInstance().getCurrentUser().getEmail());
String username = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
TextView userWelcome = (TextView) findViewById(R.id.userWelcome);
FloatingActionButton addRecipe = (FloatingActionButton) findViewById(R.id.addRecipeButton);
ImageButton userProfile = (ImageButton) findViewById(R.id.userProfileButton);
// Welcomes the current user
userWelcome.setText("Welcome, " + username + "!");
// Creates a listener for the "add recipe" button; takes user to recipe form activity
addRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toRecipeForm = new Intent(HomeScreen.this, recipeForm.class);
startActivity(toRecipeForm);
}
});
// Creates a listener for the "user Profile Button" button; takes user to profile activity
userProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ToProfile = new Intent(HomeScreen.this, Profile.class);
startActivity(ToProfile);
}
});
}
public void newUser(String name, String email)
{
userProfile user = new userProfile(name, email);
System.out.println("This is what I need to send: " + mDatabaseUsers.setValue(user));
mDatabaseUsers.setValue(user);
}
}
I declare a database instance and create a reference to the USERS path as global variables, and then made a function newUser(String name, String email) that creates an instance of a userProfile() class for me and is supposed to then send it to the database using the next line (the Sys.out was me trying to see what it was attempting to send if anything at all).
userProfile class code:
package com.capteamfour.recipeappdatabase;
import com.google.firebase.database.IgnoreExtraProperties;
import java.util.ArrayList;
import java.util.List;
#IgnoreExtraProperties
public class userProfile {
private String username;
private String email;
private List<Recipe> subRecipes = new ArrayList<>();
// Not yet implemented
private List<Recipe> favRecipes = new ArrayList<>();
private List<Recipe> savedRecipes = new ArrayList<>();
// A user profile will include their name, the recipes they've submitted, as well as recipes they've
// favorited or saved to their profile. Saved recipes are private to the user.
public userProfile() {
// Default constructor for DataSnapshot.getValue(userProfile.class) calls
}
public userProfile(String usernameIn, String emailIn)
{
this.username = username;
this.email = email;
}
public String getUsername () {
return this.username;
}
public String getEmail() {
return this.email;
}
/*
Each of these add functions will check the length of the given array and either
add to the end of it if there's already results, or just adds it on the empty array.
Example: array empty, then array[0] = recipe
array has values, then array[length + 1] = recipe
*/
public void addSubRecipe (Recipe recipe) {
int size = this.subRecipes.size();
if (size == 0) {
subRecipes.add(recipe);
}
else {
subRecipes.add(size+1, recipe);
}
}
public List<Recipe> getSubRecipes() {
return subRecipes.subList(0, (subRecipes.size()));
}
/*
These are commented out to prevent additional bugs and confusion while they're not implemented
public void addSavedRecipe (Recipe recipe) {
int size = this.savedRecipes.size();
if (size == 0) {
savedRecipes.add(recipe);
}
else {
savedRecipes.add(size + 1, recipe);
}
}
public List<Recipe> getSavedRecipes() {
return this.savedRecipes.subList(0, (subRecipes.size() + 1));
}
/*public void addFavRecipe (Recipe recipe) {
int size = this.favRecipes.size();
if (size == 0) {
favRecipes.add(recipe);
}
else {
favRecipes.add(size + 1, recipe);
}
}
public List<Recipe> getFavRecipes() {
return this.favRecipes.subList(0, (subRecipes.size() + 1));
}*/
}
In this class, I made sure to have an empty constructor with additional constructors and the usual get/set functions so that the database could work with it.
I appreciate any and all pointers that anyone could provide on how to fix this issue. This is for my college capstone course, and it's holding us up quite drastically for what appears to be no good reason. Thanks everyone.
Related
I've been following a tutorial on how to save data to the Firebase Realtime Database in Android.
With the tutorial i have managed to get this data to save etc however it only shows the last submitted item.
MainActivity code:
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
// creating variables for
// EditText and buttons.
private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;
private Button sendDatabtn;
// creating a variable for our
// Firebase Database.
FirebaseDatabase firebaseDatabase;
// creating a variable for our Database
// Reference for Firebase.
DatabaseReference databaseReference;
// creating a variable for
// our object class
EmployeeInfo employeeInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our edittext and button
employeeNameEdt = findViewById(R.id.idEdtEmployeeName);
employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber);
employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress);
// below line is used to get the
// instance of our FIrebase database.
firebaseDatabase = FirebaseDatabase.getInstance();
// below line is used to get reference for our database.
databaseReference = firebaseDatabase.getReference("EmployeeInfo");
// initializing our object
// class variable.
employeeInfo = new EmployeeInfo();
sendDatabtn = findViewById(R.id.idBtnSendData);
// adding on click listener for our button.
sendDatabtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getting text from our edittext fields.
String name = employeeNameEdt.getText().toString();
String phone = employeePhoneEdt.getText().toString();
String address = employeeAddressEdt.getText().toString();
// below line is for checking weather the
// edittext fields are empty or not.
if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) && TextUtils.isEmpty(address)) {
// if the text fields are empty
// then show the below message.
Toast.makeText(MainActivity.this, "Please add some data.", Toast.LENGTH_SHORT).show();
} else {
// else call the method to add
// data to our database.
addDatatoFirebase(name, phone, address);
}
}
});
}
private void addDatatoFirebase(String name, String phone, String address) {
// below 3 lines of code is used to set
// data in our object class.
employeeInfo.setEmployeeName(name);
employeeInfo.setEmployeeContactNumber(phone);
employeeInfo.setEmployeeAddress(address);
// we are use add value event listener method
// which is called with database reference.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// inside the method of on Data change we are setting
// our object class to our database reference.
// data base reference will sends data to firebase.
databaseReference.setValue(employeeInfo);
// after adding this data we are showing toast message.
Toast.makeText(MainActivity.this, "data added", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// if the data is not added or it is cancelled then
// we are displaying a failure toast message.
Toast.makeText(MainActivity.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show();
}
});
}
}
EmployeeInfo code:
public class EmployeeInfo {
// string variable for
// storing employee name.
private String employeeName;
// string variable for storing
// employee contact number
private String employeeContactNumber;
// string variable for storing
// employee address.
private String employeeAddress;
// an empty constructor is
// required when using
// Firebase Realtime Database.
public EmployeeInfo() {
}
// created getter and setter methods
// for all our variables.
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeContactNumber() {
return employeeContactNumber;
}
public void setEmployeeContactNumber(String employeeContactNumber) {
this.employeeContactNumber = employeeContactNumber;
}
public String getEmployeeAddress() {
return employeeAddress;
}
public void setEmployeeAddress(String employeeAddress) {
this.employeeAddress = employeeAddress;
}
}
Has anyone ever encountered this in Firebase. I have been looking for other tutorials which had ended up exactly like this so I'm not sure whether it is something in the code that is wrong or with my Firebase database.
As firebase overwrites the previous data you have entered.
You can use a .push() function like this before your setValue.
DatabaseReference database = FirebaseDatabase.getInstance().getReference("EmployeeInfo");
Then,
database.push().setValue(employeeObject);
The .push() method creates a child with a unique key in your database.
Try checking firebase docs for more info
Save Data on Firebase
, Read and Write on firebase
The key is like this Firebase RTDB
While its in the Document Snapshot loop its adding the ratings to the ratingItemList. I know this for sure because I'm also printing the size of the list in the Log and it's increasing.
But after it comes out of that loop just to be sure I check whether it is empty or not and it prints Empty List in the log.
Can you guys help me out locating the error?
package com.example.ratingapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class YourRating extends AppCompatActivity {
private List<ratingItem> ratingItemList;
private FirebaseFirestore db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_rating);
ratingItemList=new ArrayList<>();
db = FirebaseFirestore.getInstance();
db.collection("userRatings").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if(!queryDocumentSnapshots.isEmpty()){
Log.d("Check1","Ratings Exist");
List<DocumentSnapshot> documentSnapshots = queryDocumentSnapshots.getDocuments();
for(DocumentSnapshot doc : documentSnapshots) {
String rating = doc.getString("Rating");
//Log.d("Rating",rating);
com.google.firebase.Timestamp date = doc.getTimestamp("Date");
//Log.d("Date",date.toString());
ratingItem newRatingItem = new ratingItem(rating, date);
Log.d("Rating", newRatingItem.getRating());
Log.d("Date", newRatingItem.getTimestamp().toString());
ratingItemList.add(newRatingItem);
Log.d("Size ",String.valueOf(ratingItemList.size()));
}
}
else{
Toast.makeText(YourRating.this,"No ratings available!",Toast.LENGTH_LONG).show();
}
}
});
if(ratingItemList.isEmpty()){
Log.d("Empty","Empty List");
}
for(ratingItem r: ratingItemList){
Log.d("Rating1",r.getRating());
Log.d("Date1",r.getTimestamp().toString());
}
}
}
if you call for background thread result in first line and print it on very next line, your callback method does not give guarantee to run before the very next line. It will start to execute thread of first line and without waiting for response run the next line. So you are getting it empty.
Check list size also in callback onSuccess() method, after for loop:
public class YourRating extends AppCompatActivity {
private List<ratingItem> ratingItemList;
private FirebaseFirestore db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_rating);
ratingItemList = new ArrayList<>();
db = FirebaseFirestore.getInstance();
db.collection("userRatings").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
Log.d("Check1", "Ratings Exist");
List<DocumentSnapshot> documentSnapshots = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot doc : documentSnapshots) {
String rating = doc.getString("Rating");
//Log.d("Rating",rating);
com.google.firebase.Timestamp date = doc.getTimestamp("Date");
//Log.d("Date",date.toString());
ratingItem newRatingItem = new ratingItem(rating, date);
Log.d("Rating", newRatingItem.getRating());
Log.d("Date", newRatingItem.getTimestamp().toString());
ratingItemList.add(newRatingItem);
Log.d("Size ", String.valueOf(ratingItemList.size()));
}
if (ratingItemList.isEmpty()) {
Log.d("Empty", "Empty List");
}
for (ratingItem r : ratingItemList) {
Log.d("Rating1", r.getRating());
Log.d("Date1", r.getTimestamp().toString());
}
} else {
Toast.makeText(YourRating.this, "No ratings available!", Toast.LENGTH_LONG).show();
}
}
});
}
}
you success listener runs on the background thread and it is a promise that will be run when the data will be obtained from the firebase.
on the other hand the piece of code where you check the array list is empty or not runs on the ui thread. It does not wait for the data to be fetched.
How I'm currently updating my lists in my project clearly isn't the standard for apps. How do would I refresh the list without clearing it?
This code writes just fine, without any interruptions; however, once the user has finished editing, the list is cleared and refreshed, returning the user to the top of the list. What is best practice when it comes to refreshing data, especially if the data is being edited by another user without interrupting the current user.
Writing:
protected void addStep() {
String stepID = Database.push().getKey();
step newStep = new step(recipeID, stepID, "stepImage", "","");
Database.child(stepID).setValue(newStep);
getData();
}
Adapter:
package asdasd.asd;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* This class is the class responsible for handling the lists of steps that the user will see during the creator phase.
* It works by setting an array adapter which uses the fragment_steps layout displaying it on a list within the StepActivity
* On text listeners are on each of the fields, when the user edits one of the fields, the program waits 600ms, and then uploads the
* data to the database;
* this refreshes the list TODO change the way the list refreshes in the instance of the creator; perhaps add a delay of 1 minuite before refresh, and or if a new step has been added
* A timer is responsible for this delay. The setting of data is to a specific path; being the recipe -> step -> long/shortText field.
*/
public class stepList extends ArrayAdapter<step>{
private Activity context;
private List<step> steps;
private DatabaseReference database;
private Timer timer1,timer2;
public stepList(Activity context, List<step> steps) {
super(context, R.layout.fragment_step, steps);
this.context = context;
this.steps = steps;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get database
database = FirebaseDatabase.getInstance().getReference("steps");
//init Layout inflater
LayoutInflater inflater = context.getLayoutInflater();
//step
View listViewItem = inflater.inflate(R.layout.fragment_step,null,true);
//step objects
final TextView descriptionText = (TextView) listViewItem.findViewById(R.id.stepRecipeShortText);
final TextView longDescriptionText = (TextView) listViewItem.findViewById(R.id.stepRecipeLongText);
ImageView stepImage = listViewItem.findViewById(R.id.stepImage);
//init step
final step step = steps.get(position);
//get stepID
final String stepID = step.getStepID();
//Set Data
descriptionText.setText(step.getStepDescription());
longDescriptionText.setText(step.getStepLongDescription());
//TODO If user has uploaded an image, then use that, else then use default
//Add listener to descriptionText so that when a user edits the fields, it is uploaded to the same step in the database
descriptionText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// user is typing: reset already started timer (if existing)
if (timer1 != null) {
timer1.cancel();
}
}
#Override
public void afterTextChanged(Editable s) {
timer1 = new Timer();
timer1.schedule(new TimerTask() {
#Override
public void run() {
String newDescriptionText = descriptionText.getText().toString();
addToDatabase(stepID,"stepDescription", newDescriptionText);
}
}, 600);
}
});
//Add listener to LongDescriptionText so that when a user edits the fields, it is uploaded to the same step in the database
longDescriptionText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// user is typing: reset already started timer (if existing)
if (timer2 != null) {
timer2.cancel();
}
}
#Override
public void afterTextChanged(Editable s) {
timer2 = new Timer();
timer2.schedule(new TimerTask() {
#Override
public void run() {
String newLongDescriptionText = longDescriptionText.getText().toString();
addToDatabase(stepID, "stepLongDescription", newLongDescriptionText);
}
}, 600);
}
});
return listViewItem;
}
//Add the data the user is entering to the database; there is a 600ms delay on the period between the user stopping typing and the data being updated.
private void addToDatabase(String id, String location, String text) {
database.child(id).child(location).setValue(text);
}
}
Getting:
public void getData() {
//receives all the recipes and adds them to the list
Database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Clear the list
listStepsList.clear();
//Iterate through the nodes
for(DataSnapshot stepSnapshot : dataSnapshot.getChildren()){
//get recipe
step step = stepSnapshot.getValue(step.class);
//add step to list, if it is apart of the same recipe.
if(step.getRecipeID().equals(recipeID)) {
listStepsList.add(step);
}
}
//create Adapter
stepList stepAdapter = new stepList(StepActivity.this, listStepsList);
//Attatch adapter to listview
viewStepsList.setAdapter(stepAdapter);
stepAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I assume you're seeing a "big bang"/flash whenever there's a change in the database. If so, that is because you're updating the entire list, even if only a single item in the data was changed.
To improve this, you'll want to more granularly update the adapter for changes. To do so, you can attach a ChildEventListener, which fires events at one level lower in your data structure. So say a new node is added to your list, instead of rebuilding the entire list to add the one node, you'd get a single onChildAdded call with just the one new node. You'd then update listStepsList instead of rebuilding it, and tell the adapter about the changes.
For an example of this, I recommend checking out FirebaseUI, as the adapters in there all use this pattern. They build from a common FirebaseArray class that observes the database, and then have adapter classes to glue to array to the UI. For example, here's how FirebaseRecyclerAdapter connects the changes in the database to minimal updates to the view.
I've done firebase authentication for login and sign up and now i want
to save user profile in local sqlite database. I've fetched the user
information from firebase and storing them in a string variable and
passing these variables to the Adduser function to save this data in
the local database.But data is not getting stored and showing "Error
with saving user" ,that is rowid is "-1" always. i'm new to android.
please help me to solve this issue. thanks in advance
java file
package com.example.mansi.busezon;
import android.app.Application;
import android.content.ContentValues;
mport android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mansi.busezon.data.dbContract;
import com.example.mansi.busezon.data.dbHelper;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
i
public class SELL_BUY extends AppCompatActivity {
// private dbHelper mDbHelper;
String name;
String email ;
String address ;
String phoneno ;
String password ;
//String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_sell__buy);
check();
TextView BUY= (TextView) findViewById(R.id.buy);
BUY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//create intent to open the activity
Intent BUYintent= new Intent(SELL_BUY.this,HomeActivity.class);
//start the new activity
startActivity(BUYintent);
}
});
TextView SELL= (TextView) findViewById(R.id.sell);
SELL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//create intent to open the activity
Intent SELLintent= new Intent(SELL_BUY.this,SellHomepage.class);
//start the new activity
startActivity(SELLintent);
}
});
}
public void sendMessage(View view)
{
Intent intent = new Intent(SELL_BUY.this, profile_page.class);
startActivity(intent);
}
private void check()
{
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
//database reference pointing to demo node
// DatabaseReference demoRef = rootRef.child("CI8hvEW0sfZ0oU1GziTpGYPJv2z2");
// String value = "User22";
// //push creates a unique id in database
// demoRef.push().setValue(value);
rootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
String userId=getIntent().getStringExtra("Id");
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren())
{
if(ds.getKey().equals(userId))
{
//name1="aakritijohar";
name = ds.child("name").getValue(String.class);
email = ds.child("email").getValue(String.class);
address = ds.child("addres").getValue(String.class);
phoneno = ds.child("phoneno").getValue(String.class);
TextView textView = (TextView) findViewById(R.id.test);
textView.setText(phoneno);
password = ds.child("password").getValue(String.class);
Toast.makeText(SELL_BUY.this, email + " " + ds.getKey(), Toast.LENGTH_SHORT).show();
insertUser(name,email,address,phoneno,password);
}
}
Bundle extras=getIntent().getExtras();
if(extras!=null) {
String name = extras.getString("name");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
private void insertUser(String nameString,String EMAILString,String addressString,String numbertString,String pass) {
// Create database helper
dbHelper mDbHelper = new dbHelper(this);
// Gets the database in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(dbContract.userEntry.COLUMN_USER_NAME, nameString);
values.put(dbContract.userEntry.COLUMN_EMAIL, EMAILString);
values.put(dbContract.userEntry.COLUMN_number, numbertString);
values.put(dbContract.userEntry.COLUMN_address, addressString);
values.put(dbContract.userEntry.COLUMN_password, pass);
// Insert a new row for user in the database, returning the ID of that new row.
long newRowId = db.insert(dbContract.userEntry.TABLE_NAME, null, values);
// Show a toast message depending on whether or not the insertion was successful
if (newRowId == -1) {
// If the row ID is -1, then there was an error with insertion.
Toast.makeText(this, "Error with saving user", Toast.LENGTH_SHORT).show();
} else {
// Otherwise, the insertion was successful and we can display a toast with the row ID.
Toast.makeText(this, "user saved " + newRowId, Toast.LENGTH_SHORT).show();
}
}
}
database helper class
package com.example.mansi.busezon.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Database helper for Pets app. Manages database creation and version management.
*/
public class dbHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = dbHelper.class.getSimpleName();
/** Name of the database file */
private static final String DATABASE_NAME = "user.db";
/**
* Database version. If you change the database schema, you must increment the database version.
*/
private static final int DATABASE_VERSION = 1;
/**
* Constructs a new instance of {#link dbHelper}.
*
* #param context of the app
*/
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* This is called when the database is created for the first time.
*/
#Override
public void onCreate(SQLiteDatabase db) {
// Create a String that contains the SQL statement to create the pets table
String SQL_CREATE_USER_TABLE = "CREATE TABLE " + dbContract.userEntry.TABLE_NAME + " ("
+ dbContract.userEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ dbContract.userEntry.COLUMN_USER_NAME + " TEXT NOT NULL, "
+ dbContract.userEntry.COLUMN_address + " VARCHAR, "
+ dbContract.userEntry.COLUMN_number + " VARCHAR NOT NULL, "
+ dbContract.userEntry.COLUMN_EMAIL + " VARCHAR NOT NULL, "
+ dbContract.userEntry.COLUMN_password + " VARCHAR NOT NULL );";
// Execute the SQL statement
db.execSQL(SQL_CREATE_USER_TABLE);
}
/**
* This is called when the database needs to be upgraded.
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// The database is still at version 1, so there's nothing to do be done here.
}
}
There doesn't appear to be anything wrong with the code as it is.
As such I suspect that your issue may be that you have changed the table structure since running the App.
e.g. by adding a new column and then changing the code accordingly
However, that you have then not taken into consideration that the onCreate method only gets automatically invoked when the database is created.
That is the 'onCreate' method does not run every time the App is started.
I'd suggest that deleting the App's data or uninstalling the App and then rerunning the App will resolve the issue.
If that doesn't resolve the issue then please check the log as that should contain a stack-trace for when the insert comes across the issue even though the App doesn't itself crash (you could use the insertOrThrow method instead of insert which would then result in an exception/crash).
If you then still have issues, please update the question to include the stack-trace.
This is my first question here on stack overflow, so please forgive me for any oversight or formatting errors. This issue seems simple enough, but I am not able to "put the pieces together" for some reason. I am also learning java and android studio as I go, so please forgive and educate on any bad code.
I need to gather data from my barcode scanning app, submit it to a variable, and then pass that variable through my database to fetch information based on the UPC code. I am using the ZXing library for the barcode scanner, with the handleResult method to capture the initial data.
I have the data collected within the SimpleScanner activity, but I can't figure out how to use that variable in a SQlite query. Below are the main classes I am using.
Any help would be appreciated. I can query the entire database just fine, but I need to look up the rows that match the actual item I am scanning. Thanks again!
SimpleScannerActivity.java
package com.example.android.dropr;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.google.zxing.Result;
import java.util.ArrayList;
import java.util.List;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class SimpleScannerActivity extends MainActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause () {
super.onPause();
mScannerView.stopCamera(); // Stop the camera on pause
}
#Override
public void handleResult(Result rawResult) {
String TAG = "Dropr";
/**
* Create Alert Dialog, so that user has time to read the information within.
*/
AlertDialog.Builder scanInfo = new AlertDialog.Builder(this);
String messageContent = "Content - " + rawResult.getText();
String messageFormat = "Format - " + rawResult.getBarcodeFormat().toString() + ".";
scanInfo.setTitle("Scan Information:");
scanInfo.setMessage(messageContent + "\n" + messageFormat);
scanInfo.setCancelable(true);
scanInfo.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
// IF you would like to resume scanning, call this method below:
// Handle the data
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mScannerView.resumeCameraPreview(SimpleScannerActivity.this);
}
}, 1000);
}
});
AlertDialog showInfo = scanInfo.create();
showInfo.show();
// Do something with the result here
Log.v(TAG, rawResult.getText());
Log.v(TAG, rawResult.getBarcodeFormat().toString());
}
}
DatabaseAccess.java
package com.example.android.dropr;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DatabaseAccess instance;
private SimpleScannerActivity scannerActivity = new SimpleScannerActivity();
/**
* Private constructor to avoid object creation from outside classes.
*
* #param context
*/
protected DatabaseAccess(Context context) {
this.openHelper = new DatabaseOpenHelper(context);
}
/**
* Return a singleton instance of DatabaseAccess.
*
* #param context
* #return the instance of DatabaseAccess
*/
public static DatabaseAccess getInstance(Context context) {
if (instance == null) {
instance = new DatabaseAccess(context);
}
return instance;
}
/**
* Open the database connection
*/
public void open() {
this.database = openHelper.getWritableDatabase();
}
/**
* Close the database connection
*/
public void close() {
if (database != null) {
this.database.close();
}
}
/**
* Read all quotes from the database.
*
* #return a list of quotes
*/
public List<String> getCodes() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT name, upc14 FROM Barcodes", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
list.add(cursor.getString(1));
cursor.moveToNext();
}
cursor.close();
return list;
}
}
I finally came up with a solution, thanks to #muratgu! I created another method that creates and stores a variable for the scanned data, and passes the variable through a query.
/**
* read a single record from the database the matches the UPC-A code scanned.
* if there is no match, do nothing.
* #param rawContent
* #return a brand name based on the matching UPC-A code that was scanned.
*/
public String getInfo(String rawContent) {
String TAG = "Getinfo():";
String content = "00" + rawContent;
String brandName = "";
Cursor cursor = database.rawQuery("SELECT name, upc12 from Barcodes WHERE '" + content + "' = upc12", null);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
brandName = cursor.getString(cursor.getColumnIndex("name"));
cursor.close();
} else {
Log.v(TAG, "uh oh, something went wrong in the if loop! ");
}
return brandName;
}
This method gets called in the SimpleScannerActivity.java file, where the scanned data can be passed through the variable. The method returns the name of the item, which is then placed in the dialog box. Exactly what I needed.
Thanks again, #muratgu! you gave me enough information that I could solve the problem myself. I just had to think on it for a bit!