I have an application that supposed to take the text that the user enters from 4 EditTexts and a Spinner, and create a new item in the database when a button is clicked. (Image Below)
I have created a method in my database helper class that adds a new item, so in this activity I create a new item, and then pass that item to the method that should create it in the database. But for some reason weird text appear on the screen instead of a new item in the RecyclerView.
I don't know why I get the strings from the editTexts and the int (Which is the Arrival Time) and the string from the spinner and I pass it to a new item (Train) but this error keeps happening.
Here are my DatabaseHelper Class:
public class TrainDatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "train.db";
public static final String TABLE_NAME = "train";
public static final String COLUMN_ID ="_id";
public static final String COLUMN_PLATFORM = "platform";
public static final String COLUMN_ARRIVAL_TIME = "arrival_time";
public static final String COLUMN_STATUS = "status";
public static final String COLUMN_DESTINATION = "destination";
public static final String COLUMN_DESTINATION_TIME = "destination_time";
public static final String[] COLUMNS = {COLUMN_ID, COLUMN_PLATFORM, COLUMN_ARRIVAL_TIME
, COLUMN_STATUS,COLUMN_DESTINATION,COLUMN_DESTINATION_TIME};
private static TrainDatabaseHelper sInstance;
public synchronized static TrainDatabaseHelper getInstance(Context context) {
if (sInstance == null){
sInstance = new TrainDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
private TrainDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_PLATFORM + " TEXT, "
+ COLUMN_ARRIVAL_TIME + " INTEGER, "
+ COLUMN_STATUS+ " TEXT, "
+ COLUMN_DESTINATION + " TEXT, "
+ COLUMN_DESTINATION_TIME + " TEXT"
+ ")"
);
addTrain(db, new Train(0, "Albion Park Platform 1", 3,"On Time",
"Allawah", "14:11"));
addTrain(db, new Train(1, "Arncliffe Platform 2", 4, "Late",
"Central", "14:34"));
addTrain(db, new Train(2, "Artarmion Platform 3", 7, "On Time",
"Ashfield", "15:01"));
addTrain(db, new Train(3, "Berowra Platform 4", 12, "Late",
"Beverly", "15:18"));
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion){
case 1:
db.execSQL("alter table " + TABLE_NAME + " add column description TEXT");
case 2:
db.execSQL("alter table " + TABLE_NAME + " add column air_conditioned TEXT");
}
}
public void addTrain(Train train){
addTrain(getWritableDatabase(), train);
}
private void addTrain(SQLiteDatabase db, Train train){
ContentValues values = new ContentValues();
values.put(COLUMN_PLATFORM, train.getPlatform());
values.put(COLUMN_ARRIVAL_TIME, train.getArrivalTime());
values.put(COLUMN_STATUS, train.getStatus());
values.put(COLUMN_DESTINATION, train.getDestination());
values.put(COLUMN_DESTINATION_TIME, train.getDestinationTime());
db.insert(TABLE_NAME,null,values);
}
public void deleteTrains (){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME,null,null);
}
public Train getTrain(int position){
return getTrains().get(position);
}
public List<Train> getTrains(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null, null, null);
List<Train> trains = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
Train train = new Train(cursor.getInt(0),cursor.getString(1),cursor.getInt(2),
cursor.getString(3),cursor.getString(4),cursor.getString(5));
trains.add(train);
} while (cursor.moveToNext());
}
cursor.close();
return trains;
}
Here is the activity where we add a new item (Train):
public class AddTrainActivity extends AppCompatActivity {
private Spinner mSpinner;
private EditText mPlatformEt, mArrivalEt, mDestinationEt, mDestinationTimeEt;
private String mStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_train_activity);
mPlatformEt = findViewById(R.id.platform_entry);
mArrivalEt = findViewById(R.id.arrival_time_entry);
mDestinationEt = findViewById(R.id.destination_entry);
mDestinationTimeEt = findViewById(R.id.destination_time_entry);
mSpinner = findViewById(R.id.status_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> mAdapter = ArrayAdapter.createFromResource(this,
R.array.status_array, android.R.layout.simple_spinner_item);
// Apply the adapter to the spinner
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
mSpinner.setAdapter(mAdapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
mStatus = getString(R.string.status_on_time);
break;
case 1:
mStatus = getString(R.string.status_late);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(AddTrainActivity.this, R.string.status_toast, Toast.LENGTH_LONG).show();
}
});
}
public void addTrainButton (View view) {
int arrivalTime = Integer.valueOf(mArrivalEt.toString());
String platform = mPlatformEt.toString();
String destination = mDestinationEt.toString();
String destinationTime = mDestinationTimeEt.toString();
Train train = new Train(4,platform,arrivalTime, mStatus,
destination ,destinationTime);
TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
helper.addTrain(train);
Toast.makeText(this, R.string.add_train_toast, Toast.LENGTH_SHORT).show();
goBackHome();
}
public void cancelButton(View view) {
goBackHome();
}
public void goBackHome(){
startActivity(new Intent(AddTrainActivity.this, MainActivity.class));
}
And this is the MainActivity Class:
public class MainActivity extends AppCompatActivity {
private RecyclerView mTrainsRv;
private TrainAdapter mTrainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTrainsRv = findViewById(R.id.train_rv);
mTrainsRv.setLayoutManager(new LinearLayoutManager(this));
mTrainAdapter = new TrainAdapter(this);
mTrainsRv.setAdapter(mTrainAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
/** a FAB onClick Listener that starts a new activity to add a train */
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,AddTrainActivity.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/* Inflate the menu; this adds items to the action bar if it is present. */
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/* Handle action bar item clicks here */
switch (item.getItemId()) {
case R.id.action_delete:
// TODO deleting all trains from database
mTrainAdapter.notifyDataSetChanged();
return true;
case R.id.action_refresh:
return true;
case R.id.action_quit:
Toast.makeText(this, R.string.quit_menu,
Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
}
Thanks in advance and if you need more code let me know.
The problem was I forgot to do .getText() before doing .toString()
example:
mPlatformEt.getText().toString();
instead of
mPlatformEt.toString();
Related
I do not understand why my note taking application keeps crashing. I click on a button to insert a note that shows in a listView using a SQLite database.
The error given is:
(1) no such column: TITLE
FATAL EXCEPTION: main
Unable to resume activity: android.database.sqlite.SQLiteException: no such column: TITLE (code 1 SQLITE_ERROR): , while compiling: SELECT ID, TITLE FROM note_table
located here in mainactivity.java:
cursor = database.query(table_name, columns, where, where_args, group_by, having, order_by);
Database:
public class DBOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "notes.db";
public static final String TABLE_NAME = "note_table";
public static final String ID_COLUMN = "ID";
public static final String TITLE_COLUMN = "TITLE";
public static final String TEXT_COLUMN = "ITEM2";
public static final String DATE_COLUMN = "DATE";
SQLiteDatabase db = this.getWritableDatabase();
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" TITLE TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table notes_table");
onCreate(db);
}
Mainactivity.java:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayList<String> notes_list;
private ArrayAdapter adapter;
private DBOpenHelper helper;
private SQLiteDatabase database;
private TextView noNotesView;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Edit_notes.class);
startActivity(intent);
}
});
noNotesView = findViewById(R.id.empty_notes);
listView = (ListView) findViewById(R.id.listView);
notes_list = new ArrayList<>();
helper = new DBOpenHelper(this);
database = helper.getWritableDatabase();
}
private void ViewData(){
String table_name = "note_table";
String[] columns = {"ID", "TITLE"};
String where = null;
String where_args[] = null;
String group_by = null;
String having = null;
String order_by = null;
cursor = database.query(table_name, columns, where, where_args, group_by, having, order_by); // the error is here
String total_text = "total number of rows: " + cursor.getCount() + "\n";
cursor.moveToLast();
notes_list = new ArrayList<>();
adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,notes_list);
for(int i = 0; i < cursor.getCount(); i++) {
// total_text += c.getInt(0) + " " + c.getString(1) + "\n";
notes_list.add(cursor.getString(1));
listView.setAdapter(adapter);
cursor.moveToPrevious();
}
// noNotesView.setText(total_text);
}
private void hide_or_show() {
if (cursor.getCount() == 0) {
noNotesView.setVisibility(View.VISIBLE);
} else {
noNotesView.setVisibility(View.GONE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.delete_all) {
Delete_all();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume()
{
super.onResume();
ViewData();
hide_or_show();
}
public void Delete_all() {
database.execSQL("delete from " + "note_table");
adapter.clear();
}
I don't understand why I get this error message since my column name is right. I have tried deleting and recompiling my application without success.
Your problem is with your database class's constructor:
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
Specifically the 1 in the final argument of super(). That's your database version, and is key to introducing changes to your database structure. You mentioned in your comments that TITLE was previously called ITEM1, on your device it is still called ITEM1 as your app is unaware that the database structure has changed.
You can fix this by introducing a version constant in your class like so:
private static final int DB_VERSION = 2;
And using this variable in your constructor:
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
Whenever you make any structural changes to your database, increment DB_VERSION and this will cause SQLiteOpenHelper to call its onUpgrade() method.
I was working on an app where the user will input text through an editText, and it will be stored into listView and DataBase.
But when I ran the code, the Item refused to delete.
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
init();
mHelper = new InputDbHelper(this);
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
setupListViewListener();
}
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{"Name of entry you want deleted"});
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void init(){
ActionBar ab = getSupportActionBar();
assert ab != null;
ab.hide();
list = (ListView)findViewById(R.id.list);
displayText = (TextView)findViewById(R.id.displayText);
amt = (TextView)findViewById(R.id.amt);
itms = (TextView)findViewById(R.id.itms);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
l1 = (ConstraintLayout)findViewById(R.id.one);
l2 = (ConstraintLayout)findViewById(R.id.two);
Typeface regular = Typeface.createFromAsset(getAssets(), "fonts/regular.ttf");
Typeface bold = Typeface.createFromAsset(getAssets(), "fonts/bold.ttf");
amt.setTypeface(bold);
itms.setTypeface(regular);
displayText.setTypeface(regular);
}
public void add(View v){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add Item");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String txt = edt.getText().toString();
items.add(txt);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, txt);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
public void play(View v){
Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);
l1.startAnimation(fadeOut);
l1.setVisibility(View.GONE);
l2.setVisibility(View.VISIBLE);
l2.startAnimation(fadeIn);
String[] array = new String[items.size()];
final String[] mStringArray = items.toArray(array);
final android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
int i = 0;
#Override
public void run() {
displayText.setText(mStringArray[i]);
i++;
if (i == mStringArray.length) {
handler.removeCallbacks(this);
} else {
handler.postDelayed(this, TIME);
}
}
});
}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (itemsAdapter== null) {
itemsAdapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
taskList);
list.setAdapter(itemsAdapter);
} else {
itemsAdapter.clear();
itemsAdapter.addAll(taskList);
itemsAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
}
In MainActivity.java, specifically in setupListViewListener(), when the listView is held, it is supposed to delete the item that is being held. But the list only vibrates and remains the same. How can I fix this?
I suspect that your issue is that you have hard coded the TASK_TITLE to be deleted as "Name of entry you want deleted" as opposed to getting the TASK_TITLE from the item that was long clicked.
So try using :-
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{title_of_row_to_delete}); //<<<<<<<<
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
This will extract the TASK_TITLE from the list and then use that as the argument to find the row to be deleted.
//<<<<<<<< indicates changed lines.
I have already created a SQLite database for my BMI application in a new project.
Right now the problem is that I don't know how to connect to the database.
Is the private string file = "mydata"; to be changed to something else or is it correct?
CalculatorActivity. java
public class CalculatorActivity extends AppCompatActivity {
private EditText etWeight, etHeight;
private TextView tvDisplayResult, tvResultStatus;
Button bSave, bRead;
TextView tvStored;
String data;
private String file = "mydata";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
etWeight = (EditText) findViewById(R.id.weight);
etHeight = (EditText) findViewById(R.id.height);
tvDisplayResult = (TextView) findViewById(R.id.display_result);
tvResultStatus = (TextView) findViewById(R.id.result_status);
tvResultStatus = (TextView) findViewById(R.id.result_status);
bSave = (Button) findViewById(R.id.savebutton);
bRead = (Button) findViewById(R.id.readbutton);
tvStored = (TextView) findViewById(R.id.displaysaveditem);
bSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data = tvDisplayResult.getText().toString() + "\n";
try {
FileOutputStream fOut = openFileOutput(file, Context.MODE_APPEND);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//Read
bRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CalculatorActivity.this, RecordActivity.class));
finish();
}
});
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_calculate:
Log.d("check", "Button Clicked!");
calculate();
break;
case R.id.button_reset:
reset();
break;
}
}
private void calculate() {
String weight = etWeight.getText().toString();
String height = etHeight.getText().toString();
double bmiResult = Double.parseDouble(weight) / (Double.parseDouble(height) * Double.parseDouble(height));
tvDisplayResult.setText(String.valueOf(bmiResult));
if (bmiResult < 18.5) {
tvResultStatus.setText(R.string.under);
tvResultStatus.setBackgroundColor(Color.parseColor("#F1C40F"));
tvResultStatus.setTextColor(Color.parseColor("#FFFFFF"));
} else if (bmiResult >= 18.5 && bmiResult <= 24.9) {
tvResultStatus.setText(R.string.normal);
tvResultStatus.setBackgroundColor(Color.parseColor("#2ECC71"));
tvResultStatus.setTextColor(Color.parseColor("#FFFFFF"));
} else if (bmiResult >= 24.9 && bmiResult <= 29.9) {
tvResultStatus.setText(R.string.over);
tvResultStatus.setBackgroundColor(Color.parseColor("#E57E22"));
tvResultStatus.setTextColor(Color.parseColor("#FFFFFF"));
} else if (bmiResult >= 30) {
tvResultStatus.setText(R.string.obes);
tvResultStatus.setBackgroundColor(Color.parseColor("#C0392B"));
tvResultStatus.setTextColor(Color.parseColor("#FFFFFF"));
}
}
private void reset() {
etWeight.setText("");
etHeight.setText("");
tvDisplayResult.setText(R.string.default_result);
tvResultStatus.setText(R.string.na);
tvResultStatus.setBackgroundColor(0);
tvResultStatus.setTextColor(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_options, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_home:
startActivity(new Intent(CalculatorActivity.this, CalculatorActivity.class));
finish();
break;
case R.id.menu_info:
startActivity(new Intent(CalculatorActivity.this, InformationActivity.class));
finish();
break;
}
return true;
}
}
DBHandler. java
import android.content.ContentValues;
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 DBHandler extends SQLiteOpenHelper {
// Database Version
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "RecordDB";
// Record table name
public static final String TABLE_RECORD = "recordtable";
// Record Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_BMI = "bmi";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_RECORD_TABLE = "CREATE TABLE " + TABLE_RECORD + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_BMI + " TEXT " + ")";
db.execSQL(CREATE_RECORD_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECORD);
// Creating tables again
onCreate(db);
}
public void addBmi(Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_BMI, record.getBmi()); // BMI value
// Inserting Row
db.insert(TABLE_RECORD, null, values);
db.close(); // Closing database connection
}
public List<Record> getAllRecords() {
List<Record> recordList = new ArrayList<Record>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_RECORD;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Record record = new Record();
record.setId(Integer.parseInt(cursor.getString(0)));
record.setBmi(cursor.getString(1));
// Adding record to list
recordList.add(record);
} while (cursor.moveToNext());
}
// return record list
return recordList;
}
}
I don't know how to connect the database in my BMI application
Well, you need to declare it and initialize it.
public class CalculatorActivity extends AppCompatActivity {
private DBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
dbHandler = new DBHandler(this);
// Use it...
Is the private string file = "mydata"; need to be change to something else or its correct?
You are able to keep it, and it is correct, but it is not related to the database.
As my first Android project I'm trying to make an RSS reader app in which Listview items can be saved to SQLite, allowing them to be read offline. However, when trying to return news titles in a listView using a query with SimpleCursorAdapter, the listview displays the text "title", rather than the actual title of the news.
This seems to suggest that the items are not being stored to the database, or that the content values are not being properly assigned.
Can anybody see where i might be going wrong?
Thanks in advance!
RssItem.java
public class RssItem {
protected String _id;
public String title;
protected String link;
protected String page;
protected String completeTextLink;
protected String mainBody;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
//Title get/set
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
//Link get/set
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
//CompleteTextLink get/set
public String getCompleteTextLink() {
return completeTextLink;
}
public void setCompleteTextLink(String completeTextLink) {
this.completeTextLink = completeTextLink;
}
//MainBody get/set
public String getMainBody() {
return mainBody;
}
public void setMainBody(String mainBody) {
this.mainBody = mainBody;
}
//Page get/set
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
#Override
public String toString() {
return title;
}}
MainActivity.java
public class MainActivity extends Activity {
private MainActivity local;
private DatabaseHandler db;
//Method to create main application view
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//**************************create a button to move to the user's saved feeds screen*****************************
Button myFeedsButton = (Button) findViewById(R.id.myFeedsButton);
myFeedsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this, MyFeedsScreen.class));
}
});
//***************************************************************************************************************
//Create new instance of database handler
db = new DatabaseHandler(this);
//set local ref to this activity
local = this;
GetRSSDataTask task = new GetRSSDataTask();
//start download Rss task - execute method calls the
task.execute("http://feeds.bbci.co.uk/news/rss.xml?edition=uk");
//debug thread name
Log.d("RssReaderApp", Thread.currentThread().getName());
}
//*******************************************************************************************************************
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem>>
{
#Override
protected List<RssItem> doInBackground(String... urls) {
//debug task thread name
Log.d("RssReaderApp", Thread.currentThread().getName());
try {
//create a new reader
RssReader rssReader = new RssReader(urls[0]);
//Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("RssReaderApp", e.getMessage());
}
return null;
}//doInBackground
//is invoked on UI thread after background tasks are complete.
// Results of background task are passed here as a parameter
#Override
protected void onPostExecute(List<RssItem> result)
{
//Gets listview from main.xml
final ListView listItems = (ListView) findViewById(R.id.listMainView);
//Creates a new list adapter - displays an array of strings in listview
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local, android.R.layout.simple_list_item_1, result);
//Set list adapter for listView
listItems.setAdapter(adapter);
//OnItemClick listener set to allow user to access content from title
listItems.setOnItemClickListener(new ListListener(result, local));
//*******************************LONG CLICK FUNCTIONALITY******************************************
//Set new long click listener which should allow item to be stored to db
listItems.setLongClickable(true);
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
try {
db.open();
RssItem item = new RssItem();
item.title = "title";
item.link = "link";
item.completeTextLink ="completeTextLink";
item.page = "page";
db.insertRssItem(item);
db.close();
} catch (SQLException e)
{
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "Item saved in My Feeds!", Toast.LENGTH_SHORT).show();
return true;
}
});
}//onPostExecute
}}//class
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "news_db";
public static SQLiteDatabase db;
private static final int DATABASE_VERSION = 32;
protected static final String TABLE_NEWS = "news";
private static final String TAG = "TAG";
private static final String TAG1 = "TAG1";
static String columnTitle = "title";
protected static final String _id = "_id";
//Methods for tables
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_NEWS = "CREATE TABLE " + TABLE_NEWS + "(_id VARCHAR, title TEXT, link TEXT, completeTextLink TEXT, mainBody Text, page TEXT)";
db.execSQL(CREATE_TABLE_NEWS);
Log.w(TAG, "Database has been created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWS);
onCreate(db);
}
public void open() throws SQLException {
db = this.getWritableDatabase();
}
//Method to insert new rssItem object to the database
public void insertRssItem(RssItem rssItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("_id", rssItem._id);
contentValues.put("title", rssItem.title);
contentValues.put("link", rssItem.link);
contentValues.put("mainBody", rssItem.mainBody);
contentValues.put("completeTextLink", rssItem.completeTextLink);
contentValues.put("page", rssItem.page);
db.insert(TABLE_NEWS, "title", contentValues);
Log.d(TAG1, "ITEM SAVED IN DATABASE!!!");
}//insert item method
//Method to return all news for a given item
public List<RssItem> getAllNewsForItem(String page) {
List<RssItem> SavedNewsList = new ArrayList<RssItem>();
Cursor cursor = db.rawQuery("select _id, completeTextLink, title, link, mainBody, page" +
" FROM " + TABLE_NEWS + " where page = ?", new String[]{page});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
RssItem rssItem = new RssItem();
rssItem._id = cursor.getString(0);
rssItem.completeTextLink = cursor.getString(1);
rssItem.title = cursor.getString(2);
rssItem.link = cursor.getString(3);
rssItem.mainBody = cursor.getString(4);
rssItem.page = page;
SavedNewsList.add(rssItem);
cursor.moveToNext();
}
cursor.close();
return SavedNewsList;
}
//get data from database for listview
public Cursor getData() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NEWS, null);
return cursor;
}}
MyFeedsScreen.java
public class MyFeedsScreen extends ListActivity {
DatabaseHandler dbHandler;
SimpleCursorAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_feeds_screen);
dbHandler = new DatabaseHandler(MyFeedsScreen.this);
displayList();
}
public void displayList() {
dbHandler.getWritableDatabase();
dbHandler = new DatabaseHandler(this);
Cursor cursor = dbHandler.getData();
String from[] = new String[]{dbHandler.columnTitle};
int to[] = new int[]{R.id.textView1};
dataAdapter = new SimpleCursorAdapter(this, R.layout.row_item, cursor, from, to, 0);
ListView lv = getListView();
lv.setAdapter(dataAdapter);
}}
You should call getItemAtPosition(int position) from within your long-press listener. That will get you the Object from the collection that backs the ListView, in this case, the article from your RssReader that the user long-pressed upon. Sorta like:
...
db.open();
RssArticleThing fromList = (RssArticleThing) listItems.getItemAtPosition(position);
RssItem item = new RssItem();
item.title = fromList.title;
...
http://developer.android.com/reference/android/widget/AdapterView.html#getItemAtPosition(int)
iam a very dumb newbie android programmer,
here i have some problem in my case i want to run my android programs that i make on Android Studio IDE.
But when i run the program, the error field said
"Process: com.example.ever_ncn.cashflow, PID: 6317
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference"
I still dont understand with explanation on another question.
I am very confuse cuz of this error, i have googling for it but it still unsolved.
Please master, answer my question with simple and easy understanding explanation.
Thank you.
NB. My main activity is to show an activity that contain a spinner which is the spinner value is taken from database.
This is my source code for Main_Activity.java :
public class MainActivity extends ActionBarActivity {
private static Button BtnINewTrans;
private static Button BtnIViewCash;
private static Button BtnIAddCateg;
DatabaseHelper dbHelper = new DatabaseHelper(this);
Spinner selectCategory;
ArrayAdapter<String> adapterCategory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onButtonClickButtonListener();
select_spinner_Category();
}
public void select_spinner_Category (){
ArrayList<String> AllCategoryListing= dbHelper.getAllCategory();
selectCategory = (Spinner) findViewById(R.id.spnCategSelect);
adapterCategory = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, R.id.spnCategSelect, AllCategoryListing);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCategory.setAdapter(adapterCategory);
selectCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
String currencyValue = String.valueOf(parent.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
BtnINewTrans.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentNewTrans = new Intent ("com.example.ever_ncn.cashflow.NewTransaction");
startActivity(intentNewTrans);
}
}
);
BtnIViewCash = (Button)findViewById(R.id.btnViewCashflow);
BtnIViewCash.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentViewCash = new Intent ("com.example.ever_ncn.cashflow.ViewCashflow");
startActivity(intentViewCash);
}
}
);
BtnIAddCateg = (Button)findViewById(R.id.btnAddCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
startActivity(intentAddCateg);
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and this one for database_helper.java :
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String MyVillageSoftware = "MyVillageSoftware";
public static final String DATABASE_NAME = "Cashflow.db";
public static final String TABLE_Categ_NAME = "category_table";
public static final String COL1 = "CategId";
public static final String COL2 = "CategName";
public static final String COL3 = "Note";
public static final String COL4 = "Currency";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TABLE_Categ_NAME +
" (CategID Integer PRIMARY KEY AUTOINCREMENT, " +
"CategName Text," +
" Note Text," +
" Currency Text)");
}
public boolean insertCategData(String categname, String note, String currency){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, categname);
contentValues.put(COL3, note);
contentValues.put(COL4, currency);
long result = db.insert(TABLE_Categ_NAME, null, contentValues);
if (result == -1)
return true;
else
return false;
}
public ArrayList<String>getAllCategory(){
ArrayList<String> AllCategoryList = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String selectCateg="Select * FROM " +TABLE_Categ_NAME;
Cursor cursor = db.rawQuery(selectCateg, null);
if(cursor.getCount()>0){
while (cursor.moveToNext()){
String categname=cursor.getString(cursor.getColumnIndex(COL2));
AllCategoryList.add(COL2);
}return AllCategoryList;
}
return AllCategoryList;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_Categ_NAME);
onCreate(db);
}
}
Basically the the error is explained in the error message. Learning to program included learning to read error messages.
You are calling a setText() method on a TextView object, except that your TextView you're calling it on doesn't exist (in memory, as in it's not allocated). Without know what line it reports the error comes from I have no way of helping beyond that. I would suggest debugging it and check objects that turn up being null when they shouldn't be.