I'm trying to pass an ID from one class to another using intent after watching a youtube tutorial. However, it always passes over the default value of -1 rather than the value I want.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String homeTeam = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + homeTeam);
Cursor data = myDB.getMatch(homeTeam); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
//Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ViewMatchesActivity.this, UpdateMatchActivity.class);
editScreenIntent.putExtra("MatchId", itemID);
editScreenIntent.putExtra("homeTeam",homeTeam);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
The class it goes to:
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("matchId", -1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("homeTeam");
//set the text to show the current selected name
editable_item.setText(selectedName);
In his tutorial, it works fine but when I try it after I edit a match, in my log it comes up with MatchId = -1 when it shouldn't be.
I'll include the method in the database also:
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + MATCH_TABLE + " SET " + MATCH_HOME_TEAM_COL +
" = '" + newName + "' WHERE " + MATCH_ID_COL + " = '" + id + "'" +
" AND " + MATCH_HOME_TEAM_COL + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
In the Recieving Activity Change the code
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("homeTeam");
//set the text to show the current selected name
editable_item.setText(selectedName);
You should use MatchId instaed of matchID. Java is Case Sensitive.
The key which you have passing is MatchId and you are fetching data from matchId, Which are not same.
Replace your code to
selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value
Related
I m trying to delete the row from input for GoalWeight, Goal Date and Current Weight. It is not erroring but the row is not getting delete.
DeleteLayout
Button deleteB;
DatabaseHelper myDB;
EditText goalD;
EditText goalW;
EditText currentW;
Intent j;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.deletelayout);
deleteB = findViewById(R.id.buttonDelete);
myDB = new DatabaseHelper(this);
deleteB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goalD = findViewById(R.id.goaldinput2);
goalW = findViewById(R.id.goalwinput3);
currentW = findViewById(R.id.currentWinput2);
if(goalD.length() !=0 && goalW.length() !=0 && currentW.length() !=0){
Toast.makeText(DeleteLayout.this,"Goal Date: " +goalD.getText().toString()+ "Goal Weight: " + goalW.getText().toString()+
"Current Weight: " +currentW.getText().toString()+ " entered.",
Toast.LENGTH_LONG).show();
myDB.deleteContent(goalD.getText().toString(), goalW.getText().toString(), currentW.getText().toString());
j = new Intent(DeleteLayout.this, historyActivity.class);
startActivity(j);
}
else{
Toast.makeText(DeleteLayout.this,"All data not entered.", Toast.LENGTH_LONG).show();
}
}
});
Delete method in DatabaseHelper
public void deleteContent(String goalDate, String goalWeight,String currentWeight){
SQLiteDatabase db = this.getWritableDatabase();
String query = " DELETE FROM " + TABLE_NAME + "WHERE GDATE = "+
goalDate + " AND " + "GWEIGHT = " + goalWeight + " AND " + "CWEIGHT = " + currentWeight ;
}
The main problem (not the only one) is that inside deleteContent(), although you create the SQL statement, you never execute it by say execSQL().
So no attempt is made to delete any row.
However you should change so to use the delete() method, like this:
public int deleteContent(String goalDate, String goalWeight, String currentWeight){
SQLiteDatabase db = this.getWritableDatabase();
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
int rows = db.delete(TABLE_NAME, where, new String[] {goalDate, goalWeight, currentWeight});
db.close();
return rows;
}
This is the recommended way, because it is safe and it also returns the number of rows affected/deleted (which you can examine to check if the deletion was successful).
So you can use it like this:
int rows = myDB.deleteContent(
goalD.getText().toString(),
goalW.getText().toString(),
currentW.getText().toString()
);
and in the variable rows you will have the number of the deleted rows.
I have this code:
{
String SQL_CREATE_BOOKS_TABLE = "CREATE TABLE " + BooksContract.BooksEntry.TABLE_NAME + " ("
+ BooksContract.BooksEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT + " TEXT NOT NULL, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_PRICE + " DECIMAL NOT NULL DEFAULT 0, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY + " INTEGER NOT NULL, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_SUPPLIER + " TEXT, "
+ BooksContract.BooksEntry.COLUMN_BOOKS_PHONE + " INTEGER );";
db.execSQL(SQL_CREATE_BOOKS_TABLE);
}
Even though I didn't set the supplier to be not null, if I don't type it in my editText when I click the save button my app crashes. Also even though quantity is set to default 0, if I don't type any quantity it still crashes. why?
EditorActivity:
private void insertBooks() {
String productString = productName.getText().toString().trim();
String priceString = price.getText().toString().trim();
int price = Integer.parseInt(priceString);
String quantityString = quantity.getText().toString().trim();
int quantity = Integer.parseInt(quantityString);
String supplierString = supplier.getText().toString().trim();
String phoneString = supplierPhone.getText().toString().trim();
int phone = Integer.parseInt(phoneString);
BooksDbHelper dbHelper = new BooksDbHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT, productString);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PRICE, priceString);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY, quantityString);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_SUPPLIER, supplierString);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PHONE, phoneString);
long newRowId = db.insert(BooksContract.BooksEntry.TABLE_NAME, null, values);
if (newRowId == -1) {
// If the row ID is -1, then there was an error with insertion.
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved with row id: " + newRowId, Toast.LENGTH_SHORT).show();
}
}
CatalogActivity:
private void insertBooks() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT, "Walks with men");
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PRICE, 10.00);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY, 2);
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_SUPPLIER, "Amazon");
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_PHONE, 727213658);
long newRowId = db.insert(BooksContract.BooksEntry.TABLE_NAME, null, values);
}
Use this code in your insertBooks() method to avoid NumberFormatException:
String productString = productName.getText().toString().trim();
String priceString = price.getText().toString().trim();
double price = 0.0;
try {
price = Double.parseDouble(priceString);
} catch (NumberFormatException e) {
e.printStackTrace();
}
String quantityString = quantity.getText().toString().trim();
int quantity = 0;
try {
quantity = Integer.parseInt(quantityString);
} catch (NumberFormatException e) {
e.printStackTrace();
}
String supplierString = supplier.getText().toString().trim();
String phoneString = supplierPhone.getText().toString().trim();
Why is phone INTEGER?
Note:
The create table code you posted is probably part of the onCreate() method in your class that extends SQLiteOpenHelper.
The onCreate() method was executed the 1st time you ran the app and created the table. Since then you may have altered the columns either by type or name, or even inserted or deleted columns, but all these changes were made only in your code and not in the table. The onCreate() method has never again been triggered.
So if any of the above applies to you:
Uninstall the app from the emulator/device so that the database is deleted and run again your app to recreate it as it should be.
I made SQL database and populated it with values. In TextView I need to show multiply result of specific rows.
I made SQL statement and I hope that is correct.
public List<Food> multiplyFat(){
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " FROM " + FoodEntry.TABLE_NAME + " WHERE ( "
+FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
SQLiteDatabase db = this.getWritableDatabase();
List<Food> storeTotalFat = new ArrayList<>();
Cursor cursor = db.rawQuery(totalFat, null);
if (cursor.moveToFirst()){
do {
double fat = Double.parseDouble(cursor.getString(0));
storeTotalFat.add(new Food(fat));
} while (cursor.moveToNext());
}
cursor.close();
return storeTotalFat;
}
To be more clear I need to multiply values from row COLUMN_FAT_TOTAL with row COLUMN_GRAM and display result into the TextView. Or should I put these SQL statement:
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " * " +FoodEntry.COLUMN_GRAM + " FROM " +FoodEntry.TABLE_NAME;
That is simplier way but I am not sure that it is correct way.
Anyhow I need to display this multiplyFat() function (result) into TextView. Any help or advice would be really helpfull.
public List multiplyFat(){
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " FROM " + FoodEntry.TABLE_NAME + " WHERE ( "
+FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
The above works perfectly in MySQL, I just tried it.
SQLiteDatabase db = this.getWritableDatabase(); --> db = this.getReadableDatabase();
Since you are not changing anything in the SQLite database you want a '.getReadableDatbase();' not '.getWritableDatabase();'
List<Food> storeTotalFat = new ArrayList<>();
Cursor cursor = db.rawQuery(totalFat, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
do {
double fat = Double.parseDouble(cursor.getString(0));
storeTotalFat.add(new Food(fat));
} cursor.moveToNext();
}
cursor.close();
return storeTotalFat;
}
See how I first moved to the first index, then I ask it to continue in a while loop until it has reached the final element in the SQL results. Your way was not actually incrementing the cursor, it would have only been able to add the first result to the storeTotalFat ArrayList.
-------- part 2 ---------
Now let's pretend we are back in the activity, woo!
Let's say there is a class variable reference to the database helper and add a new ArrayList to house the results from the query result we just gained.
DBHelper myDBhelper = DBHelper.getInstance(MainActivity.this)
ArrayList<String> sqlResultArray = new ArrayList<>();
If you want a Recyclerview you make a separate RviewAdapter class, in your case FoodFatRecyclerViewAdapter and add the following
RecyclerView rv = (RecyclerView) findViewById(R.id.foodFatRecView);
LinearLayoutManager llm = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(llm);
FoodFatRecyclerViewAdapter foodFatAdapter = new FoodFatRecyclerViewAdapter(MainActivity.this, sqlResultArray);
rv.setAdapter(foodFatAdapter);
Now as for the adding of the result to the textview create a new class called FoodFatRecyclerViewAdapter
public class FoodFatRecyclerViewAdapter extends RecyclerView.Adapter<FoodFatViewHolder> {
ArrayList<String> mFoodFatItems;
Context mContext;
public FoodFatRecyclerViewAdapter(Context context, ArrayList<String> array) {
mContext = context;
mFoodFatItems = array;
}
#Override
public FoodFatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.this_xml_layout_will_describe_the_arrangement_of_the_indi_item_in_the_list_not_the_master_view, parent, false);
FoodFatViewHolder recyclerView = new FoodFatViewHolder(view);
return recyclerView;
}
#Override
public void onBindViewHolder(FoodFatViewHolder holder, final int position) {
holder.mFatTotalTextView.setText(mFoodFatItems.get(position));
}
#Override
public int getItemCount() {
return mFoodFatItems.size();
}
}
Now the final piece to the puzzle, the View Holder so create a class called FoodFatViewHolder
public class FoodFatViewHolder extends RecyclerView.ViewHolder{
TextView mFatTotalTextView;
public FoodFatViewHolder(View itemView) {
super(itemView);
mFatTotalTextView = (TextView) itemView.findViewById(R.id.the_textview_id_within_the_individ_item_in_rv_xml_layout);
}
}
Voila! It should work
You need to show the multiplication total then you shouldn't do a select on COLUMN_FAT_TOTAL. Instead you should do the computation in your select query and store that computation in an alias. You can then use that alias as a result.
Modify your query as below
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + "AS Result FROM " + FoodEntry.TABLE_NAME";
You are on the right track. Do the math in the database if it is easy and straight forward, which this example is.
Might I suggest the following (similar to kapsym answer) for your sql statement:
String totalFat = "SELECT " + FoodEntry.COLUMN_FAT_TOTAL + ", " + FoodEntry.COLUMN_GRAM + "," FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + "AS TotalFat FROM " + FoodEntry.TABLE_NAME + " WHERE ( " + FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
You should study the basics of MySQL : https://www.tutorialspoint.com/mysql/mysql-select-query.htm
After the SELECT, you add column names that you want to retrieve and not expressions.
For your case, Use this Query to get all fat_total & gram entries :
String totalFat = "SELECT " + FoodEntry.COLUMN_FAT_TOTAL + "," + FoodEntry.COLUMN_GRAM + " FROM " + FoodEntry.TABLE_NAME;
Then you retrieve fatTotal * gram for each cursor, multiply it and feed it into your storeTotalFat array based on (!= 0) condition.
Cursor cursor = db.rawQuery(totalFat, null);
if (cursor.moveToFirst()){
do {
double fat = Double.parseDouble(cursor.getString(0));
double gram= Double.parseDouble(cursor.getString(1));
if (fat * gram != 0)
storeTotalFat.add(new Food(fat * gram));
} while (cursor.moveToNext());
}
I'm new to android, and I don't know why I am getting CursorIndexOutOfBoundsException: Index 0 requested with a size of 0. I'm trying to display it on another class using listview. Here are my codes:
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
position = position + 1;
Cursor a = MainActivity.sqldb
.rawQuery("Select name from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
String aa = a.getString(a.getColumnIndex("name"));
Cursor b = MainActivity.sqldb
.rawQuery("Select phone from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
String bb = b.getString(b.getColumnIndex("phone"));
Intent next = new Intent (this, ThirdActivity.class);
startActivity(next);
}
I know that there's something really wrong here. And I wonder what it is.
Create Table:
sqldb = this.openOrCreateDatabase(dbpb, MODE_PRIVATE, null);
sqldb.execSQL("CREATE TABLE IF NOT EXISTS "
+ tblpb
+ " (_pid INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, phone INTEGER);");
Insert Table:
sqldb.execSQL("Insert into " + tblpb
+ " (name, phone) Values ('" + x + "' , '"
+ y + "' );");
Try doing this:
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
String aa = null;
String bb = null;
// do not alter the position, DB starts the same position as ItemClick for
// adapter view
// position = position + 1;
Cursor a = MainActivity.sqldb
.rawQuery("Select name from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
if(a != null){
// Force cursor to position 0
if(a.moveToFirst()){
// make sure the column actually exists
aa = a.getString(a.getColumnIndexOrThrow("name"));
Log.d("Cursor A - Name", "name column val: "+ aa);
}else{
Log.d("Cursor A", "cursor A failed to move to first");
}
}else{
Log.d("Cursor A null", "cannot access cursor A");
}
Cursor b = MainActivity.sqldb.rawQuery("Select phone from " + MainActivity.tblpb + " where _pid = " + position + ";", null);
if(b != null){
// Force cursor to position 0
if(b.moveToFirst()){
// make sure the column actually exists
bb = b.getString(b.getColumnIndexOrThrow("phone"));
Log.d("Cursor B - Phone", "phone column val: "+ bb);
}else{
Log.d("Cursor B", "cursor B failed to move to first");
}
}else{
Log.d("Cursor B null", "cannot access cursor B");
}
Intent next = new Intent (this, ThirdActivity.class);
next.putExtra("NAME", aa);
next.putExtra("PHONE", bb);
startActivity(next);
}
Then in your second Activity do:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.content_file);
Bundle extras = getIntent().getExtras();
if(extras != null){
String aa = extras.getString("NAME");
String bb = extras.getString("PHONE");
// Since you cannot tell if these are null check them
if(aa != null){
// ... Use on your TextView
}
// Since you cannot tell if these are null check them
if(bb != null){
// ... Use on your TextView
}
}
}
The error indicates that you are trying to access the first element (index 0) of an empty list (size 0) meaning your queries are returning no results. Make sure your queries are correct.
EDIT:
It's also a good idea to call cursor.moveToFirst() and check its result before doing any operations on the data from a query.
http://developer.android.com/reference/android/database/Cursor.html#moveToFirst%28%29
I am getting values from the column "threadid" in the database.Problem is that it gets the value from the previous record/row. and when I try to get the first record my app crashes,, How to tackle this problem and whats the issue?
long id;
long threadid = datasource.getthreadid(id);
Toast.makeText(getActivity(), String.valueOf(threadid), Toast.LENGTH_SHORT).show();
public long getthreadid(long id)
{
String ide=String.valueOf(id);
String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID
+ " FROM " + MySQLiteHelper.TABLE_NAME
+ " WHERE " + MySQLiteHelper.COLUMN_ID + "=" + ide;
Cursor cursor = database.rawQuery(queryz, null);
cursor.moveToFirst();
// cursor.moveToPosition(Integer.parseInt(String.valueOf(id)));
long threadid= cursor.getLong(cursor.getColumnIndex("threadid"));
cursor.close();
return threadid;
}
If you are only expecting one row. Then it might be useful to do something like this.
long threadid;
if (cursor.moveToFirst())
{
threadid = cursor.getLong(cursor.getColumnIndex("threadid"));
}
else
{
// ah oh, we do not have this id!
// do something here if you need to
}
Also, if you are going to use strings, I recommend you bind the parameters. I know you had a long beforehand, but for strings you can do this.
String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID
+ " FROM " + MySQLiteHelper.TABLE_NAME
+ " WHERE " + MySQLiteHelper.COLUMN_ID + " = ?";
Cursor cursor = database.rawQuery(queryz, new String[]{ide});
To get all the records, you first need to move to the first one, then you iterate through the rest.
if (cursor.moveToFirst()) {
do {
// get row values
} while (cursor.moveToNext());
}
cursor.close();