java


Adding more stuff to SQLite Database


Lets begin.
DatabaseHelper.java
package com.example.soultaker.overtimesregistrator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mylogs.db";
public static final String TABLE_NAME = "mylogs_table";
public static final String COL0 = "ID";
public static final String COL1 = "DATE";
public static final String COL2 = "HOURS";
public static final String COL3 = "SHIFT";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME
+ "("
+ COL0 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL1 + " TEXT, "
+ COL2 + " TEXT, "
+ COL3 + " TEXT, "
+ ")"
);
}
#Override
public void onUpgrade (SQLiteDatabase db,int oldVersion, int newVersion){
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String date, String hours, String shift){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1,date);
contentValues.put(COL2,hours);
contentValues.put(COL3, shift);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
public Cursor showData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
public boolean updateData(String id, String date, String hours, String shift){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL0,id);
contentValues.put(COL1,date);
contentValues.put(COL2,hours);
contentValues.put(COL3,shift);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] {id});
return true;
}
}
AddActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
DatabaseHelper mylogsDB;
Button btn_save;
EditText etHours;
Spinner etShift;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
etHours = (EditText) findViewById(R.id.editText);
etShift = (Spinner) findViewById(R.id.spinner);
btn_save = (Button) findViewById(R.id.btn_save);
mylogsDB = new DatabaseHelper(this);
AddData();
// Spinner click listener
etShift.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add("Πρωί");
categories.add("Μεσημέρι");
categories.add("Νύχτα");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
etShift.setAdapter(dataAdapter);
}
public void onItemSelected (AdapterView <?> parent, View view,int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Έχετε επιλέξει: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void AddData() {
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String hours = etHours.getText().toString();
String shift = etShift.getSelectedItem().toString();
boolean insertData = mylogsDB.addData(hours, shift);
if (insertData == true) {
Toast.makeText(AddActivity.this, "Η αποθήκευση ολοκληρώθηκε επιτυχώς.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddActivity.this, "Ώχ,Κάτι πήγε στραβά.", Toast.LENGTH_LONG).show();
}
}
});
}
}
MainActivity.java
package com.example.soultaker.overtimesregistrator;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper mylogsDB;
Button btn_add, btn_view, btn_edit;
EditText hours, etID;
DatePicker date;
Spinner shift;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_add = (Button) findViewById(R.id.btn_add);
btn_edit = (Button) findViewById(R.id.btn_edit);
btn_view = (Button) findViewById(R.id.btn_view);
date = (DatePicker) findViewById(R.id.datePicker);
hours = (EditText) findViewById(R.id.editText);
shift = (Spinner) findViewById(R.id.spinner);
mylogsDB = new DatabaseHelper(this);
UpdateData();
btn_add.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
btn_view.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, LogsView.class);
startActivity(intent);
}
});
}
public void UpdateData(){
btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int temp = etID.getText().toString().length();
if (temp > 0) {
boolean update = mylogsDB.updateData(etID.getText().toString(), date.getText().toString(),
hours.getText().toString(), shift.getText().toString());
if (update == true) {
Toast.makeText(MainActivity.this, "Successfully Updated Data!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something Went Wrong :(.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this, "You Must Enter An ID to Update :(.", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
In MainActivity I get errors in these lines
boolean update = mylogsDB.updateData(etID.getText().toString(), date.getText().toString(),
hours.getText().toString(), shift.getText().toString());
Says
only in date,shift that method getText cannot be resolved.
LogsView.java
package com.example.soultaker.overtimesregistrator;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class LogsView extends AppCompatActivity {
DatabaseHelper mylogsDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logs_view);
ListView listView = (ListView) findViewById(R.id.list_view);
mylogsDB = new DatabaseHelper(this);
//populate an ArrayList<String> from the database and then view it
ArrayList<String> theList = new ArrayList<>();
Cursor data = mylogsDB.showData();
if(data.getCount() == 0){
Toast.makeText(this, "There are no contents in this list!",Toast.LENGTH_LONG).show();
}else{
while(data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
}
Any idea why those errors appear? I'm too confused right now and can't find where I'm wrong.
I'm trying to add DatePicker and Spinner.I haven't finished with the DatePicker though.
In AddActivity I'm getting errors in these lines
String date = date.getText().toString();
String hours = hours.getText().toString();
String shift = shift.getText().toString();
It says that
Variables date,hours,shift might not have been initialized.
I see many errors here:
date.getText().toString(); there is not such filed variable date and thus it is an error of date can not be resolved!
Also if you missed to create this variable date and you will create then you have to change the name of String variable date in this String date because you can't create two variables with the same name.
The same is for String hours and Edittext hours, again you can't create two variables with the same name!
Also String shift and Spinner shift, again you can't create two variables with the same name!
shift , the Spinner, you truing to get it current selection as String but this statement:
shift.getText().toString();
which is wrong, instead use:
shift.getSelectedItem().toString();
====
In MainActivity I get errors in these lines
boolean update = mylogsDB.updateData(etID.getText().toString(), date.getText().toString(),hours.getText().toString(),shift.getText().toString());
Says
only in date,shift that method getText cannot be resolved.
I see more errors here!, lets extract them all:
The variable etID is defined but never assigned ! I expect this to give a null pointer exception.
Also again shift is a Spinner.
Also date is a DatePicker, to get it's value as String you do the following:
Date dateObj = (Date) new Date (date.getYear(), date.getMonth(), date.getDayOfMonth());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // you can change this format as you wish!
String dateAsString = sdf.format(dateObj);

Related Links

How to only allow input of letters? [duplicate]
not BOUND in this code of the TSP?
Run Java application with minimal code (hiding the main-method) [duplicate]
How to code switch Mobile Data on / off and check current Status on all Android Versions?
S3: User cannot access object in his own s3 bucket if created by another user
What is the benefit of having multiple logger instances instead of having a single static logger class?
Spark DataFrame.registerTempTable doesn't update the temp table in jdbc hive
NoClassDefFoundError spring boot maven
Can i create separate properties file for Virgo OSGi bundle?
Can't get JTable to refresh/repaint a DefaultTableModel in same instance of GUI run
JOptionPane icon gets cropped in Windows 10
Null Layout default JFrame dimension?
How to I get rid of an anonymous object in an arrayList?
Binary Search Tree insert() and removeMin()
AccessDeniedException when Creating a recently deleted file
android fragment version 4 text issue

Categories

HOME
sendgrid
google-chrome-extension
image
clips
oracle11g
minimum-spanning-tree
drivers
iot
dot
yum
constraint-programming
primary-key
export-to-csv
circular-dependency
windows-phone-7
flask-wtforms
quickfix
django-simple-history
ghc
openrefine
highlight.js
footer
serilog
interop
plunker
dcevm
sqlcipher
facet
pingfederate
gsmcomm
titanium-mobile
siesta-swift
accelerate-framework
amazon-kinesis-kpl
host
main
automake
space-complexity
unspecified
sqlite2
lumberjack
broadcastreceiver
firebase-admin
no-www
unixodbc
gpx
taffy
termination
komodoedit
pubmed
winscp-net
pebble-watch
gabor-filter
lowpass-filter
brightcove
lync-client-sdk
smart-table
eventkit
word-vba-mac
static-ip-address
slicknav
home-directory
thrust
autorest
testng-dataprovider
hover-over
whois
suffix-tree
cloudbees
wso2cloud
metaclass
retina
sframe
key-management
streambase
nsmutabledictionary
sorl-thumbnail
offloading
operator-precedence
camanjs
android-nested-fragment
castle
uitouch
dml
funcunit
algebraic-data-types
ivyde
commoncrypto
flash-builder4.5
back-stack
seed
ocunit
rdoc
pysimplesoap
ohm
punbb
bigcouch
netdna-api
qt-jambi
deobfuscation
infobox
modelstate
routedevent
thunderbird-lightning
boost-smart-ptr
yagni
sector

Resources

Encrypt Message