I can't see the ListView - java

What is the reason for the empty ListView? Actually, I have filled the database with dates, but the ListView is empty, especially the activity is empty. The activity is empty when the ListView is create with the arrayAdapter, but the app chrashes when it is create with the the cursor Adapter.
I wrote an app which uses a ListView to list a part of my SQLite dates.
But I can't see the ListView. The app starts without an error, but the Activity is empty. I can't see my error. I hope, someone else can see the error.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context="com.example.katjarummler.hundeschule_petra_bennemann.
GruppeAuslesenActivity"
android:focusableInTouchMode="true"
android:weightSum="1">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="visible"
/>
</LinearLayout>
public class GruppeAuslesenActivity extends AppCompatActivity {
public static final String LOG_TAG =
GruppeAuslesenActivity.class.getSimpleName();
ListView mKundenListView;
private HundeschuleMemoDataSource dataSource = new
HundeschuleMemoDataSource(this);
private GoogleApiClient client;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gruppeauslesen);
initializeHundeschuleKundenListView();
HundeschuleMemoDataSource dataSource = new
HundeschuleMemoDataSource(this);
client = new
GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void initializeHundeschuleKundenListView() {
List<HundeschuleMemoKunden> listForInitialization = new
ArrayList<HundeschuleMemoKunden>();
mKundenListView = (ListView) findViewById(R.id.list);
// Erstellen des ArrayAdapters für unseren ListView
ArrayAdapter<HundeschuleMemoKunden>
hundeschuleMemoKundenArrayAdapter = new
ArrayAdapter<HundeschuleMemoKunden>(
this,
android.R.layout.simple_list_item_multiple_choice,
listForInitialization) {
// Wird immer dann aufgerufen, wenn der übergeordnete ListView
die Zeile neu zeichnen muss
#NonNull
public View getView(int position, View convertView, #NonNull
ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view;
HundeschuleMemoKunden memo = (HundeschuleMemoKunden)
mKundenListView.getItemAtPosition(position);
// Hier prüfen, ob Eintrag abgehakt ist. Falls ja, Text
durchstreichen
if (memo.isChecked()) {
textView.setPaintFlags(textView.getPaintFlags() |
Paint.STRIKE_THRU_TEXT_FLAG);
textView.setTextColor(Color.rgb(175, 175, 175));
} else {
textView.setPaintFlags(textView.getPaintFlags() &
(~Paint.STRIKE_THRU_TEXT_FLAG));
textView.setTextColor(Color.DKGRAY);
}
return view;
}
};
mKundenListView.setAdapter(hundeschuleMemoKundenArrayAdapter);
mKundenListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
HundeschuleMemoKunden memo = (HundeschuleMemoKunden)
mKundenListView.getItemAtPosition(position);
// Hier den checked-Wert des Memo-Objekts umkehren, bspw.
von true auf false
// Dann ListView neu zeichnen mit showAllListEntries()
HundeschuleMemoKunden updatedHundeschuleMemoKunden =
dataSource.updateHundeschuleMemoKunden(memo.getId(), memo.getgName(),
memo.getkName(),
memo.getkTelefon(), memo.gethName(),
memo.getbeginn(), (!memo.isChecked()));
Log.d(LOG_TAG, "Checked-Status von Eintrag: " +
updatedHundeschuleMemoKunden.toString() + " ist: " +
updatedHundeschuleMemoKunden.isChecked());
showAllListEntries();
}
});
}
private void showAllListEntries() {
List<HundeschuleMemoKunden> hundeschuleMemoGruppenList =
dataSource.getAllGruppen();
ArrayAdapter<HundeschuleMemoKunden> adapter =
(ArrayAdapter<HundeschuleMemoKunden>) mKundenListView.getAdapter();
adapter.clear();
adapter.addAll(hundeschuleMemoGruppenList);
adapter.notifyDataSetChanged();
}
protected void onResume() {
super.onResume();
Log.d(LOG_TAG, "Die Datenquelle wird geöffnet.");
dataSource.open();
Log.d(LOG_TAG, "Folgende Einträge sind in der Datenbank
enthalten:");
showAllListEntries();
}
protected void onPause() {
super.onPause();
Log.d(LOG_TAG, "Die Datenquelle wird geschlossen.");
dataSource.close();
}
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("GruppeAuslesen Page") // TODO: Define a title for
the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
public class HundeschuleMemoDataSource {
private static final String LOG_TAG =
HundeschuleMemoDataSource.class.getSimpleName();
private SQLiteDatabase database;
private HundeschuleMemoDBHelper dbHelper;
private String[] columns = {
HundeschuleMemoDBHelper.COLUMN_ID,
HundeschuleMemoDBHelper.COLUMN_KName,
HundeschuleMemoDBHelper.COLUMN_GNAME,
HundeschuleMemoDBHelper.COLUMN_KTELEFON,
HundeschuleMemoDBHelper.COLUMN_HUND,
HundeschuleMemoDBHelper.COLUMN_BEGINN,
HundeschuleMemoDBHelper.COLUMN_CHECKED,
};
public HundeschuleMemoDataSource(Context context) {
Log.d(LOG_TAG, "Unsere DataSource erzeugt jetzt den dbHelper. ");
dbHelper = new HundeschuleMemoDBHelper(context, "gruppe",
TABLE_KUNDEN_LIST);
}
public void open() {
Log.d(LOG_TAG, "Eine Referenz auf die Datenbank wird jetzt
angefragt.");
database = dbHelper.getWritableDatabase();
Log.d(LOG_TAG, "Datenbankreferenz erhalten. Pfad zur Datenbank: " +
database.getPath());
}
public void close() {
dbHelper.close();
Log.d(LOG_TAG, "Datenbank mit Hilfe des DBHelpers geschlossen.");
}
public HundeschuleMemoKunden createHundeschuleMemoKunden(String kName,
String gName, String kTelefon, String hName,
String beginn)
{
ContentValues values = new ContentValues();
values.put(COLUMN_KName, kName);
values.put(COLUMN_GNAME, gName);
values.put(HundeschuleMemoDBHelper.COLUMN_KTELEFON, kTelefon);
values.put(COLUMN_HUND, hName);
values.put(HundeschuleMemoDBHelper.COLUMN_BEGINN, beginn);
long insertId = database.insert(TABLE_KUNDEN_LIST, null, values);
Cursor cursor = database.query(TABLE_KUNDEN_LIST,
columns, HundeschuleMemoDBHelper.COLUMN_ID + "=" +
insertId,
null, null, null, null);
cursor.moveToFirst();
HundeschuleMemoKunden hundeschuleMemoKunden =
cursorToHundeschuleMemoKunden(cursor);
cursor.close();
return hundeschuleMemoKunden;
}
public HundeschuleMemoKunden createHundeschuleMemoGruppen(String gName,
String kName, String hName) {
ContentValues values = new ContentValues();
values.put(COLUMN_GNAME, gName);
values.put(COLUMN_KName, kName);
values.put(COLUMN_HUND, hName);
long insertId = database.insert(TABLE_KUNDEN_LIST, null, values);
Cursor cursor = database.query(TABLE_KUNDEN_LIST,
columns, HundeschuleMemoDBHelper.COLUMN_ID + "=" +
insertId,
null, null, null, null);
cursor.moveToFirst();
HundeschuleMemoKunden hundeschuleMemoGruppen =
cursorToHundeschuleMemoKunden(cursor);
cursor.close();
return hundeschuleMemoGruppen;
}
public void deleteHundeschuleMemoKunden(HundeschuleMemoKunden
hundeschuleMemoKunden) {
long id = hundeschuleMemoKunden.getId();
database.delete(TABLE_KUNDEN_LIST,
HundeschuleMemoDBHelper.COLUMN_ID + "=" + id,
null);
Log.d(LOG_TAG, "Eintrag gelöscht! ID: " + id + " Inhalt: " +
hundeschuleMemoKunden.toString());
}
public HundeschuleMemoKunden updateHundeschuleMemoKunden(long id,
String newkName, String newgName, String newkTelefon, String newHund,
String
newBeginn, boolean newChecked) {
int intValueChecked = (newChecked) ? 1 : 0;
ContentValues values = new ContentValues();
values.put(COLUMN_KName, newkName);
values.put(COLUMN_GNAME, newgName);
values.put(HundeschuleMemoDBHelper.COLUMN_KTELEFON, newkTelefon);
values.put(COLUMN_HUND, newHund);
values.put(HundeschuleMemoDBHelper.COLUMN_BEGINN, newBeginn);
values.put(HundeschuleMemoDBHelper.COLUMN_CHECKED,
intValueChecked);
database.update(TABLE_KUNDEN_LIST,
values,
HundeschuleMemoDBHelper.COLUMN_ID + "=" + id,
null);
Cursor cursor = database.query(TABLE_KUNDEN_LIST,
columns, HundeschuleMemoDBHelper.COLUMN_ID + "=" + id,
null, null, null, null);
cursor.moveToFirst();
HundeschuleMemoKunden hundeschuleMemoKunden =
cursorToHundeschuleMemoKunden(cursor);
cursor.close();
return hundeschuleMemoKunden;
}
private HundeschuleMemoKunden cursorToHundeschuleMemoKunden(Cursor
cursor) {
int idIndex =
cursor.getColumnIndex(HundeschuleMemoDBHelper.COLUMN_ID);
int idKName = cursor.getColumnIndex(COLUMN_KName);
int idGName = cursor.getColumnIndex(COLUMN_GNAME);
int idKTelefon =
cursor.getColumnIndex(HundeschuleMemoDBHelper.COLUMN_KTELEFON);
int idHund = cursor.getColumnIndex(COLUMN_HUND);
int idBeginn =
cursor.getColumnIndex(HundeschuleMemoDBHelper.COLUMN_BEGINN);
int idChecked =
cursor.getColumnIndex(HundeschuleMemoDBHelper.COLUMN_CHECKED);
String kName = cursor.getString(idKName);
String gName = cursor.getString(idGName);
String kTelefon = cursor.getString(idKTelefon);
String Hund = cursor.getString(idHund);
String beginn = cursor.getString(idBeginn);
long id = cursor.getLong(idIndex);
int intValueChecked = cursor.getInt(idChecked);
boolean isChecked = (intValueChecked != 0);
HundeschuleMemoKunden hundeschuleMemoKunden = new
HundeschuleMemoKunden(kName, gName, kTelefon, Hund,
beginn);
return hundeschuleMemoKunden;
}
public List<HundeschuleMemoKunden> getAllHundeschuleMemos() {
List<HundeschuleMemoKunden> hundeschuleMemoKundenList = new
ArrayList<>();
Cursor cursor = database.query(TABLE_KUNDEN_LIST,
columns, null, null, null, null, null);
cursor.moveToFirst();
HundeschuleMemoKunden hundeschuleMemoKunden;
while (!cursor.isAfterLast()) {
hundeschuleMemoKunden = cursorToHundeschuleMemoKunden(cursor);
hundeschuleMemoKundenList.add(hundeschuleMemoKunden);
Log.d(LOG_TAG, "ID: " + hundeschuleMemoKunden.getId() + ",
Inhalt: " + hundeschuleMemoKunden.toString());
cursor.moveToNext();
}
cursor.close();
return hundeschuleMemoKundenList;
}
public List<HundeschuleMemoKunden> getAllGruppen() {
List<HundeschuleMemoKunden> gruppenList = new ArrayList<>();
SQLiteDatabase database = dbHelper.getWritableDatabase();
String selectQuery = "SELECT " +
HundeschuleMemoDBHelper.COLUMN_ID + " , " +
HundeschuleMemoDBHelper.COLUMN_GNAME + " , " +
HundeschuleMemoDBHelper.COLUMN_KName + " , " +
HundeschuleMemoDBHelper.COLUMN_HUND + " , " +
HundeschuleMemoDBHelper.COLUMN_CHECKED +
" FROM " + HundeschuleMemoDBHelper.TABLE_KUNDEN_LIST + "
ORDER BY 2 ASC ";
Cursor cursor = database.rawQuery(selectQuery, null);
cursor.moveToFirst();
cursor.close();
database.close();
return gruppenList;
}
}
public class HundeschuleMemoDBHelper extends SQLiteOpenHelper {
private static final String LOG_TAG =
HundeschuleMemoDBHelper.class.getSimpleName();
public static final String DB_NAME = "Kunden_list.db";
public static final int DB_VERSION = 7;
public static final String TABLE_KUNDEN_LIST = "Kunden_list";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_KName = "Name";
public static final String COLUMN_GNAME = "Gruppe";
public static final String COLUMN_KTELEFON = "Telefon";
public static final String COLUMN_HUND = "Hund";
public static final String COLUMN_BEGINN = "Beginn";
public static final String COLUMN_CHECKED = "checked";
public static final String SQL_CREATE = "CREATE TABLE " +
TABLE_KUNDEN_LIST +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_KName + " TEXT NOT NULL, " +
COLUMN_GNAME + " TEXT NOT NULL, " +
COLUMN_KTELEFON + " TEXT NOT NULL, " +
COLUMN_HUND + " TEXT NOT NULL, " +
COLUMN_BEGINN + " TEXT NOT NULL, " +
COLUMN_CHECKED + " BOOLEAN NOT NULL DEFAULT 0);";
public static final String SQL_DROP = "DROP TABLE IF EXISTS " +
TABLE_KUNDEN_LIST;
public HundeschuleMemoDBHelper(Context context, String gruppe, String
sql) {
super(context, DB_NAME, null, DB_VERSION);
Log.d(LOG_TAG, "DBHelper hat die Datenbank: " + getDatabaseName() +
" erzeugt.");
}
//Die onCreate-Methode wird nur aufgerufen, falls die Datenbank noch
nicht existiert
public void onCreate(SQLiteDatabase db) {
try{
Log.d(LOG_TAG, "Die Tabelle wird mit SQL-Befehl: " + SQL_CREATE
+ " angelegt.");
db.execSQL(SQL_CREATE);
}
catch(Exception ex){
Log.e(LOG_TAG, "Fehler beim Anlegen der Tabelle: " +
ex.getMessage());
}
}
// Die onUpgrade-Methode wird aufgerufen, sobald die neue
Versionsnummer höher
// als die alte Versionsnummer ist und somit ein Upgrade notwendig wird
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
Log.d(LOG_TAG, "Die Tabelle mit Versionsnummer " + oldVersion + "
wird entfernt.");
db.execSQL(SQL_DROP);
onCreate(db);
}
}
public class HundeschuleMemoKunden {
private String kName;
private String gName;
private String kTelefon;
private String hName;
private String beginn;
private long id;
private boolean checked;
public HundeschuleMemoKunden(String kName, String gName, String
kTelefon, String hName,
String beginn){
this.id=id;
this.kName=kName;
this.gName=gName;
this.kTelefon=kTelefon;
this.hName=hName;
this.beginn=beginn;
this.checked = checked;
}
public String getkName(){
return kName;
}
public void setkName(String kName){
this.kName = kName;
}
public String getgName(){return gName;}
public void setgName(String gName){
this.gName = gName;
}
public String getkTelefon(){
return kTelefon;
}
public void setkTelefon(String kTelefon){this.kTelefon = kTelefon;}
public String gethName(){
return hName;
}
public void sethName(String hName){
this.hName = hName;
}
public String getbeginn(){
return beginn;
}
public void setbeginn(String beginn){
this.beginn = beginn;
}
public long getId(){return id;}
public void setId(long id){
this.id = id;
}
public boolean isChecked(){return checked;}
public void setChecked(boolean checked){this.checked = checked;}
public String toString(){
String output = kName + " " + gName + " " + kTelefon + " " + hName
+ " " + beginn;
return output;
}
}

android:layout_height="wrap_content"
You need match parent
And if you're using a database, try to use CursorAdapter instead of ArrayAdapter and ensure that dataSource.getAllGruppen() actually returns something
Also, you have two instances of HundeschuleMemoDataSource dataSource. Remove the declaration from the field since the Context is not yet initialized
private HundeschuleMemoDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gruppeauslesen);
dataSource = new HundeschuleMemoDataSource(this);
initializeHundeschuleKundenListView();
And if you did use a CursorAdapter, here's your corrected method
public Cursor getAllGruppen() {
String selectQuery = "SELECT " +
HundeschuleMemoDBHelper.COLUMN_ID + " , " +
HundeschuleMemoDBHelper.COLUMN_GNAME + " , " +
HundeschuleMemoDBHelper.COLUMN_KName + " , " +
HundeschuleMemoDBHelper.COLUMN_HUND + " , " +
HundeschuleMemoDBHelper.COLUMN_CHECKED +
" FROM " + HundeschuleMemoDBHelper.TABLE_KUNDEN_LIST +
" ORDER BY 2 ASC ";
return dbHelper.getReadableDatabase().rawQuery(selectQuery, null);
}

Related

How to correctly display user's info among multiple users?

The command to retrieve user data doesn't display correctly, it shows the information of the last registered user.
MainActivity/login
public class MainActivity extends AppCompatActivity {
Button btnRegister, btnLogin;
EditText edtAccount, edtPassword;
Database db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegister = (Button) findViewById(R.id.buttonSignup);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(i);
}
});
edtAccount = (EditText) findViewById(R.id.editTextAccount);
edtPassword = (EditText) findViewById(R.id.editTextPassword);
btnLogin = (Button) findViewById(R.id.buttonLogin);
db=new Database(this);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String account = edtAccount.getText().toString();
String password = edtPassword.getText().toString();
if (account.equals("") || password.equals("")){
Toast.makeText(MainActivity.this,
"Account and password are empty",Toast.LENGTH_SHORT).show();
}
else {
Boolean result = db.checkUserNamePassword(account, password);
if(result==true) {
Intent intent = new Intent(MainActivity.this, TestActivity.class);
intent.putExtra("account", account);
startActivity(intent);
}
else{
Boolean userCheckResult = db.checkUserName(account);
if(userCheckResult == true){
Toast.makeText(MainActivity.this,
"invalid password!", Toast.LENGTH_SHORT).show();
edtPassword.setError("invalid password!");
} else{
Toast.makeText(MainActivity.this,
"Account does not exist", Toast.LENGTH_SHORT).show();
edtAccount.setError("Account does not exist!");
}
}
}
}
});
}
}
Database
public class Database extends SQLiteOpenHelper {
public static final String TB_USER = "USER";
public static final String TB_PERSONAL = "PERSONAL";
public static final String TB_GROUPSCHEDULE = "GROUPSCHEDULE";
public static String TB_USER_ACCOUNT = "ACCOUNT";
public static String TB_USER_PASSWORD = "PASSWORD";
public static String TB_USER_ID = "USERID";
public static String TB_USER_FIRSTNAME = "USERFIRSTNAME";
public static String TB_USER_LASTNAME = "USERLASTNAME";
public static String TB_USER_PHONENUMBER = "PHONENUMBER";
public static String TB_USER_EMAIL = "EMAIL";
public static String TB_PERSONAL_ID = "PERSONALID";
public static String TB_PERSONAL_TIME = "PERSONALTIME";
public static String TB_PERSONAL_EVENT = "PERSONALEVENT";
public static String TB_GROUP_ID = "GROUPID";
public static String TB_GROUP_MEMBERS = "GROUPMEMBERS";
public static String TB_GROUP_LEADER = "GROUPLEADER";
public static String TB_GROUP_EVENT = "GROUPEVENT";
public static String TB_GROUP_TIME = "GROUPTIME";
public Database(Context context) {
super(context, "Mysche", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String tbUSER = " CREATE TABLE " + TB_USER + " ( "
+ TB_USER_ACCOUNT + " TEXT , "
+ TB_USER_PASSWORD + " TEXT , "
+ TB_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TB_USER_FIRSTNAME + " TEXT, "
+ TB_USER_LASTNAME + " TEXT, "
+ TB_USER_EMAIL + " TEXT, "
+ TB_USER_PHONENUMBER + " TEXT )";
String tbPERSONAL = " CREATE TABLE " + TB_PERSONAL + " ( "
+ TB_PERSONAL_ID + " TEXT PRIMARY KEY , "
+ TB_PERSONAL_EVENT + " TEXT, "
+ TB_PERSONAL_TIME + " DATE )";
String tbGROUP = " CREATE TABLE " + TB_GROUPSCHEDULE + " ( "
+ TB_GROUP_ID + "INTEGER PRIMARY KEY , "
+ TB_GROUP_LEADER + " TEXT, "
+ TB_GROUP_MEMBERS + " TEXT, "
+ TB_GROUP_EVENT + " TEXT, "
+ TB_GROUP_TIME + " TEXT )";
db.execSQL(tbUSER);
db.execSQL(tbPERSONAL);
db.execSQL(tbGROUP);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TB_USER);
db.execSQL("DROP TABLE IF EXISTS " + TB_PERSONAL);
db.execSQL("DROP TABLE IF EXISTS " + TB_GROUPSCHEDULE);
onCreate(db);
}
public Boolean insertData(String ACCOUNT, String PASSWORD, String USERFIRSTNAME, String USERLASTNAME, String PHONENUMBER, String EMAIL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ACCOUNT", ACCOUNT);
contentValues.put("PASSWORD", PASSWORD);
contentValues.put("USERFIRSTNAME", USERFIRSTNAME);
contentValues.put("USERLASTNAME", USERLASTNAME);
contentValues.put("PHONENUMBER", PHONENUMBER);
contentValues.put("EMAIL", EMAIL);
long result = db.insert("USER", null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Boolean checkUserName(String ACCOUNT) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM USER WHERE ACCOUNT = ?"
, new String[]{ACCOUNT});
if (cursor.getCount() > 0) {
return true;
} else {
return false;
}
}
public Boolean checkUserNamePassword(String ACCOUNT, String PASSWORD) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from USER where ACCOUNT = ? and PASSWORD = ?"
, new String[]{ACCOUNT, PASSWORD});
if (cursor.getCount() > 0) {
return true;
} else {
return false;
}
}
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT, null);
return cursor;
}
}
TestActivity
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Database database = new Database(this);
TextView textViewName = findViewById(R.id.textViewUserName);
TextView textViewEmail = findViewById(R.id.textViewUserEmail);
TextView textViewPhone = findViewById(R.id.textViewPhone);
TextView textViewAccount = findViewById(R.id.textViewAccount);
String account = getIntent().getStringExtra("account");
textViewPhone.setText(account);
Cursor cursor = database.getInfo();
while (cursor.moveToNext()){
textViewName.setText(cursor.getString(4 ) + " " +(cursor.getString(3)));
textViewPhone.setText(cursor.getString(5));
textViewEmail.setText(cursor.getString(6));
textViewAccount.setText(account);
}
}
}
I think I need to change this command:
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT, null);
return cursor;
}
to:
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT + "=" + loggingAccount();, null);
return cursor;
}
But I don't know how to create and insert that loggingAccount() function. I was able to display username by getIntent() in TestActivity.
String account = getIntent().getStringExtra("account");
textViewPhone.setText(account);
Or if anyone knows another way please guide me.
You could create an overloaded method getInfo(String acct) and invoke as follows:
Cursor cursor = database.getInfo(account);
and define it as such:
public Cursor getInfo(String account) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT + " = '" + account + "'", null);
return cursor;
}
An overloaded method means methods within a class can have the same name (e.g. getInfo) but differ in method signature (parameters). And of course their implementation can differ.
Since your query is formed using data from user input you should use prepared statements. Check out PreparedStatement for more discussion on that.

Com.example path with errors

When I was releasing an apk on google play I had to use a different package name cause of "com.example". I tried this and I get crash after testing an application. Before that everything was ok. I can send a manifest.
There are my errors.
My classes
Details.java
public class Details extends AppCompatActivity {
NoteDatabase db;
Note note;
TextView mDetails;
TextView clientDetails;
TextView timeDetails;
TextView nameDetails;
TextView detailsDetails;
ImageView noteDetails;
private Bitmap getImageFromByte(byte[] zdjecie){
return BitmapFactory.decodeByteArray(zdjecie, 0, zdjecie.length);
}
#SuppressLint("WrongThread")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDetails = findViewById(R.id.detailsOfNote);
mDetails.setMovementMethod(new ScrollingMovementMethod());
clientDetails = findViewById(R.id.clientOfNote);
timeDetails = findViewById(R.id.timeofNote);
nameDetails = findViewById(R.id.nameOfNote);
detailsDetails = findViewById(R.id.detailsOfNote);
noteDetails = findViewById(R.id.noteImage);
Intent i = getIntent();
Long id = i.getLongExtra("ID", 0);
db = new NoteDatabase(this);
note = db.getNote(id);
getSupportActionBar().setTitle(note.getTitle());
mDetails.setText(note.getContent());
clientDetails.setText(note.getTitle());
timeDetails.setText(note.getTime());
nameDetails.setText(note.getName());
detailsDetails.setText(note.getDetails());
noteDetails.setImageBitmap(stringToImage(note.getImage()));
Toast.makeText(this, "Podgląd klienta", Toast.LENGTH_SHORT).show();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.deleteNote(note.getID());
Toast.makeText(getApplicationContext(), "Klient usunięty", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),klienci.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.edit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.editNote){
Toast.makeText(this, "Edytowanie notatki", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this,Edit.class);
i.putExtra("ID",note.getID());
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
private void goToMain() {
Intent i = new Intent(this,klienci.class);
startActivity(i);
}
private Bitmap stringToImage(String imgString){
byte[] decodedString = Base64.decode(imgString,Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString,0,decodedString.length);
return decodedByte;
}
NoteDatabase.java
public class NoteDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 42;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
private static final String KEY_PHONE = "phone";
private static final String KEY_CLIENT = "client";
private static final String KEY_DETAILS = "details";
private static final String KEY_IMAGE = "image";
NoteDatabase(Context context) {
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ DATABASE_TABLE + "("+ KEY_ID+" INT PRIMARY KEY,"+
KEY_TITLE + " TEXT,"+
KEY_CONTENT + " TEXT,"+
KEY_DATE + " TEXT,"+
KEY_TIME + " TEXT,"+
KEY_CLIENT + " TEXT,"+
KEY_DETAILS + " TEXT,"+
KEY_PHONE + " TEXT,"+
KEY_IMAGE + " TEXT"+")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion >= newVersion)
return;
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public long addNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_PHONE,note.getPhone());
c.put(KEY_CLIENT,note.getClient());
c.put(KEY_DETAILS,note.getDetails());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
c.put(KEY_IMAGE,note.getImage());
long ID = db.insert(DATABASE_TABLE,null, c);
Log.d("Inserted", "ID -> " + ID);
return ID;
}
public Note getNote(long id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,new String[] {KEY_ID,KEY_TITLE,KEY_CONTENT,KEY_PHONE,KEY_CLIENT,KEY_DETAILS,KEY_DATE,KEY_TIME,KEY_IMAGE}, KEY_ID+"=?",
new String[]{String.valueOf(id)}, null, null,null);
if (cursor != null)
cursor.moveToFirst();
return new Note
(cursor.getLong(0)
,cursor.getString(1)
,cursor.getString(2)
,cursor.getString(3)
,cursor.getString(4)
,cursor.getString(5)
,cursor.getString(6)
,cursor.getString(7)
,cursor.getString(8));
}
public List<Note> getNotes() {
SQLiteDatabase db = this.getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
String query = "SELECT * FROM " + DATABASE_TABLE + " ORDER BY "+KEY_TITLE+" ASC";
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setDetails(cursor.getString(2));
note.setPhone(cursor.getString(3));
note.setClient(cursor.getString(4));
note.setContent(cursor.getString(5));
note.setDate(cursor.getString(6));
note.setTime(cursor.getString(7));
note.setImage(cursor.getString(8));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
public int editNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
Log.d("Edited", "Edited Title: -> "+ note.getTitle() + "\n ID -> "+note.getZdjecie());
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_PHONE,note.getPhone());
c.put(KEY_CLIENT,note.getClient());
c.put(KEY_DETAILS,note.getDetails());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
c.put(KEY_IMAGE,note.getImage());
return db.update(DATABASE_TABLE,c,KEY_ID +"=?",new String[]{String.valueOf(note.getID())});
}
void deleteNote(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DATABASE_TABLE, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You are trying to get 0 index in the database. Every time you add a new Note its ID will be 0. So, change your database KEY_ID to AUTOINCREMENT.
String query = "CREATE TABLE " + DATABASE_TABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT," +
KEY_PIES + " TEXT," +
KEY_RASAPSA + " TEXT," +
KEY_TEL + " TEXT," +
KEY_ZDJECIE + " TEXT" + ")";
db.execSQL(query);
Then check your cursor not null in
getNote()

SQLiteDatabase not displaying information ImageButton Crashes App

I'm creating a Calorie App for my class project. I attempted to implement a database to store the information of the calories added by the user which would be displayed in a listview. The user will input the calories in the add_entry fragment and be displayed on the fragment_home page in the listview.
Problem: I'm not sure if I'm adding the information correctly to the database using the Entry Add Fragment in order to display the info in the listview. this is my first time working with Android Studio/App.
Problem 2:
For Some Reason when I click on imagebutton on my homefragment app crashes and
it doesnt go to the add_entry fragment
logcat:
04-06 00:33:41.213 30567-30567/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 30567
java.lang.IllegalStateException: Could not find method Click(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'AddItems'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
listview = (ListView) getActivity().findViewById(R.id.listView);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber - FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID,
KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null, "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
}
}
}
AddEntry.java
public class AddEntry extends Fragment implements
View.OnClickListener {
EditText DescriptionET,CalorieET;
ImageButton savebtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_entry, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
break;
case R.id.CancelBtn:
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private static final String DATABASE_NAME = "CalorieDb.db";
And then call below method in oncreat()
public void checkDB() {
try {
//android default database location is : /data/data/youapppackagename/databases/
String packageName = this.getPackageName();
String destPath = "/data/data/" + packageName + "/databases";
String fullPath = "/data/data/" + packageName + "/databases/"
+ DATABASE_NAME;
//this database folder location
File f = new File(destPath);
//this database file location
File obj = new File(fullPath);
//check if databases folder exists or not. if not create it
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
}
//check database file exists or not, if not copy database from assets
if (!obj.exists()) {
this.CopyDB(fullPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Unintall app and clean and rebuild project then I think solve your problem.
Try Replaceing this, Removing the last Comma(,) from the statement
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
Remove , from last field
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private static final String DATABASE_CREATE_SQL =
" create table " + DATABASE_TABLE
+ " ( " + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null, "
+ " ); ";
Add space " ) "

How to get data from database on click of an event?

I am generating an events dynamically. These events data I am storing in sqlite database. Now I want to retrieve data of the clicked event. I tried to retrieve data but always getting 0th id data.
Generating events function :
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
tvTitle.setText(title);
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
startActivity(i);
}
});
}
This is my attempt to get data:
db = new EventTableHelper(getApplication());
eventData = new EventData();
if(editMode)//true
{
eventData = events.get(id);
Toast.makeText(getApplicationContext(),String.valueOf(id),Toast.LENGTH_LONG).show();
title.setText(eventData.getTitle());
eventTitle = title.getText().toString();
db.updateEvent(eventData);
Toast.makeText(getApplicationContext(),"Edit mode",Toast.LENGTH_LONG).show();
Log.i("Log","save mode");
}
I have EventTableHelper in that i have created functions to get event,update and delete events.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE,KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I want to show data and update data if changes made.
Whats going wrong?

Show SQL data in android layout

I have a problem with the following issue:
I have build an Android app which saves data into a SQL database (SQLite). I managed so the current date, time and the category is saved down and shown in a different menu. Somehow I am not able to get the value saved down and shown in the other layout. The data should come from an EditText: android:id="#+id/edit_betrag
The SQL column is defined like: public static final String BUDGET_BETRAG = "betrag";
and then should be shown in textView_betrag in the class BudgetRechnerAdapter respectively the other layout.
Can you please help me with this issue? Thanks a lot!!!
public class BudgetRechnerOpenHandler extends SQLiteOpenHelper {
private static final String TAG = BudgetRechnerOpenHandler.class
.getSimpleName();
// Name und Version der Datenbank
private static final String DATABASE_NAME = "budgetrechner.db";
private static final int DATABASE_VERSION = 1;
// Name und Attribute der Tabelle "Budget"
public static final String _ID = "_id";
public static final String TABELLE_NAME_BUDGET = "budget";
public static final String BUDGET_ZEIT = "zeitStempel";
public static final String BUDGET_AUSGABENART = "ausgabenArt";
public static final String BUDGET_BETRAG = "betrag";
// Konstanten für die Stimmungen
public static final int BUDGET_ESSEN = 1;
public static final int BUDGET_GETRAENK = 2;
public static final int BUDGET_SONSTIGES = 3;
// Tabelle Budget anlegen
private static final String TABELLE_BUDGET_ERSTELLEN = "CREATE TABLE "
+ TABELLE_NAME_BUDGET + " (" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + BUDGET_ZEIT + " INTEGER, "
+ BUDGET_BETRAG + " INTEGER," + BUDGET_AUSGABENART + " INTEGER);";
// Tabelle Budget löschen
private static final String TABELLE_BUDGET_DROP = "DROP TABLE IF EXISTS "
+ TABELLE_NAME_BUDGET;
BudgetRechnerOpenHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABELLE_BUDGET_ERSTELLEN);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrade der Datenbank von Version " + oldVersion + " zu "
+ newVersion + "; alle Daten werden gelöscht");
db.execSQL(TABELLE_BUDGET_DROP);
onCreate(db);
}
public void insert(int art, String beschreibung, long zeit) {
long rowId = -1;
try {
// Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
// die zu speichernden Werte
ContentValues wert = new ContentValues();
wert.put(BUDGET_AUSGABENART, art);
wert.put(BUDGET_BETRAG, beschreibung);
wert.put(BUDGET_ZEIT, zeit);
// in die Tabelle Budget einfügen
rowId = db.insert(TABELLE_NAME_BUDGET, null, wert);
} catch (SQLiteException e) {
Log.e(TAG, "insert()", e);
} finally {
Log.d(TAG, "insert(): rowId=" + rowId);
}
}
public Cursor query() {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
return db.query(TABELLE_NAME_BUDGET, null, null, null, null, null,
BUDGET_ZEIT + " DESC"
);
}
public void update(long id, int ausgabe_art_zahl) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BUDGET_AUSGABENART, ausgabe_art_zahl);
int numUpdated = db.update(TABELLE_NAME_BUDGET, values, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "update(): id=" + id + " -> " + numUpdated);
}
public void delete(long id) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
int numDeleted = db.delete(TABELLE_NAME_BUDGET, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "delete(): id=" + id + " -> " + numDeleted);
}
}
public class BudgetRechnerAdapter extends CursorAdapter {
private final Date datum;
private static final DateFormat DF_DATE = SimpleDateFormat
.getDateInstance(DateFormat.MEDIUM);
private static final DateFormat DF_TIME = SimpleDateFormat
.getTimeInstance(DateFormat.MEDIUM);
private Integer betrag;
private static final Integer DF_BETRAG = R.id.edit_betrag;
private LayoutInflater inflator;
private int ciAusgabenArt, ciZeit, ciBetrag;
public BudgetRechnerAdapter(Context context, Cursor c) {
super(context, c);
datum = new Date();
betrag = null;
inflator = LayoutInflater.from(context);
ciAusgabenArt = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_AUSGABENART);
ciZeit = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_ZEIT);
ciBetrag = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_BETRAG);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView image = (ImageView) view.findViewById(R.id.icon);
int art = cursor.getInt(ciAusgabenArt);
TextView textView_art = (TextView) view.findViewById(R.id.text3);
if (art == BudgetRechnerOpenHandler.BUDGET_ESSEN) {
image.setImageResource(R.drawable.bild_essen);
textView_art.setText("Essen");
} else if (art == BudgetRechnerOpenHandler.BUDGET_GETRAENK) {
image.setImageResource(R.drawable.bild_getraenk);
textView_art.setText("Getränk");
} else {
image.setImageResource(R.drawable.bild_sonstiges);
textView_art.setText("Sonstiges");
}
TextView textView_Datum = (TextView) view.findViewById(R.id.text1);
TextView textView_Zeit = (TextView) view.findViewById(R.id.text2);
TextView textView_betrag = (TextView) view.findViewById(R.id.text4);
long zeitStempel = cursor.getLong(ciZeit);
datum.setTime(zeitStempel);
textView_Datum.setText(DF_DATE.format(datum));
textView_Zeit.setText(DF_TIME.format(datum));
textView_betrag.setText(DF_BETRAG.toString());
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflator.inflate(R.layout.verlauf, null);
}
}

Categories

Resources