i extreme beginner @ android studio , using javascript, still learning , trying grasp new concepts of android studio whole.
i trying create database adds, edits , deletes records user manually inputs.
when friends.xml page (friends.java) , fill out fields add user , press "add" comes toast notify user data has been added succesfully when click on "view data" (which links view_data.xml (listdata.java)) doesn't seem show entries.
it great if answer put possible still beginner! appreciated! thanks!
friends.java
package com.example.chris.mobileappsassignment; import android.content.context; import android.content.intent; import android.os.bundle; import android.support.design.widget.floatingactionbutton; import android.support.design.widget.snackbar; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.view.view; import android.view.menu; import android.view.menuitem; import android.widget.button; import android.widget.edittext; import android.widget.toast; public class friends extends appcompatactivity { edittext firstnameinput, lastnameinput, ageinput, addressinput; button addbutton, viewbutton; databasehelper dbhlpr; context context; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.content_friends); toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); firstnameinput = (edittext) findviewbyid(r.id.firstnameinput); lastnameinput = (edittext) findviewbyid(r.id.lastnameinput); ageinput = (edittext) findviewbyid(r.id.ageinput); addressinput = (edittext) findviewbyid(r.id.addressinput); addbutton = (button) findviewbyid(r.id.addbutton); viewbutton = (button) findviewbyid(r.id.viewbutton); dbhlpr = new databasehelper(this); addbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { boolean addok = true; int age_as_int = -1; string firstname = firstnameinput.gettext().tostring(); string lastname = lastnameinput.gettext().tostring(); string age = ageinput.gettext().tostring(); string address = addressinput.gettext().tostring(); if (firstname.length() < 1) { toastmessage("you must enter in field!"); firstnameinput.requestfocus(); addok = false; } if (lastname.length() < 1) { toastmessage("you must enter in field!"); lastnameinput.requestfocus(); addok = false; } if (age.length() < 1) { toastmessage("you must enter in field!"); ageinput.requestfocus(); addok = false; } if (address.length() < 1) { toastmessage("you must enter in field!"); addressinput.requestfocus(); addok = false; } try { age_as_int = integer.parseint(age); } catch (numberformatexception e) { toastmessage("you must enter valid number in field!"); ageinput.requestfocus(); addok = false; } if (addok) { dbhlpr.adddata(firstname,lastname,"????",age_as_int,address); toastmessage("friend added!"); } } }); viewbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { intent intent = new intent(context,listdata.class); startactivity(intent); } }); } //end on create class //toast mssg private void toastmessage(string message) { toast.maketext(this,message, toast.length_short).show(); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.menu_friends, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { // handle action bar item clicks here. action bar // automatically handle clicks on home/up button, long // specify parent activity in androidmanifest.xml. int id = item.getitemid(); //noinspection simplifiableifstatement if (id == r.id.action_settings) { return true; } return super.onoptionsitemselected(item); } }
listdata.java
package com.example.chris.mobileappsassignment; import android.content.intent; import android.database.cursor; import android.os.bundle; import android.support.annotation.nullable; import android.support.v7.app.appcompatactivity; import android.util.log; import android.view.view; import android.widget.adapterview; import android.widget.arrayadapter; import android.widget.listadapter; import android.widget.listview; import android.widget.toast; import java.util.arraylist; import static com.example.chris.mobileappsassignment.r.layout.view_data; public class listdata extends appcompatactivity { private static final string tag = "listdata"; databasehelper mdatabasehelper; private listview mlistview; @override protected void oncreate(@nullable bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(view_data); mlistview = (listview) findviewbyid(r.id.listview); mdatabasehelper = new databasehelper(this); populatelistview(); } //end oncreate private void populatelistview() { log.d(tag, "populate listview: displaying data in listview"); //get data , append list cursor data = mdatabasehelper.getdata(); log.d("cursorcount", "number of rows in cursor ="); integer.tostring(data.getcount()); arraylist<string> listdata = new arraylist<>(); while(data.movetonext()){ //get value db in col1 //then add arraylist listdata.add(data.getstring(1)); listdata.add(data.getstring(2)); listdata.add(data.getstring(3)); listdata.add(data.getstring(4)); listdata.add(data.getstring(5)); // numbers refer col's. (coloumns) } //create list adapter , set adapter listadapter adapter = new arrayadapter<>(this, android.r.layout.simple_list_item_1, listdata); mlistview.setadapter(adapter); //set on onclick listener list view mlistview.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick(adapterview<?> adapterview, view view, int position, long id) { string name = adapterview.getitematposition(position).tostring(); // grab object , convert string log.d(tag, "onitemclick: clicked on " + name); cursor data = mdatabasehelper.getitemid(name); // id associated name int itemid = 1; // when searching // return exists while (data.movetonext()){ itemid = data.getint(0); // if data returned } if (itemid > -1) { log.d(tag, "onitemclick: id is: " + itemid); intent editscreenintent = new intent(listdata.this, editdataactivity.class ); // vid2, 2.49 editscreenintent.putextra("id", itemid); editscreenintent.putextra("name", name); startactivity(editscreenintent); } else { toastmessage("no id associated name"); } } }); } /** * customizable toast */ private void toastmessage(string message) { toast.maketext(this, message, toast.length_short).show(); } } //end class
error in logcat when pressing "add"
--------- beginning of crash 09-12 02:40:00.329 26615-26615/com.example.chris.mobileappsassignment e/androidruntime: fatal exception: main process: com.example.chris.mobileappsassignment, pid: 26615 java.lang.nullpointerexception: attempt invoke virtual method 'java.lang.string android.content.context.getpackagename()' on null object reference @ android.content.componentname.<init>(componentname.java:128) @ android.content.intent.<init>(intent.java:4449) @ com.example.chris.mobileappsassignment.friends$2.onclick(friends.java:99) @ android.view.view.performclick(view.java:5198) @ android.view.view$performclick.run(view.java:21147) @ android.os.handler.handlecallback(handler.java:739) @ android.os.handler.dispatchmessage(handler.java:95) @ android.os.looper.loop(looper.java:148) @ android.app.activitythread.main(activitythread.java:5417) @ java.lang.reflect.method.invoke(native method) @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:726) @ com.android.internal.os.zygoteinit.main(zygoteinit.java:616)
the issue here column called address couldn't found in table named friends_table per :-
09-10 20:38:48.892 10003-10003/com.example.chris.mobileappsassignment e/sqlitedatabase: error inserting address=mike lastname=mike firstname=mike age=mike malefemale=mike android.database.sqlite.sqliteexception: table friends_table has no column named address (code 1): , while compiling: insert friends_table(address,lastname,firstname,age,malefemale) values (?,?,?,?,?)
it definition used create table needs changed or definition has been changed has been implemented because database's oncreate
method has not been run.
the oncreate
method runs automatically when database created, being once lifetime of database file. there 3 easy ways oncreate
run, noting all 3 delete existing data in database.
- uninstall app.
- clear app's data.
- if onupgrade method drops respective table or tables , calls
oncreate
verion number of database can incremented.
as such need to
- a) ensure table definition includes address column (and columns lastname, firstname, age , malefemale)
- b)
oncreate
run 1 of 3 methods above (there other ways around issue want need retain existing data).
again, log, have issue how prepare data within adddata
trying insert same data columns e.g. error inserting address=mike lastname=mike firstname=mike age=mike malefemale=mike
result in lastname, firstname, age, malefemale having value mike (sheesh didn't know popular :))
looking @ friends class use (as 1 example):-
if (firstnameinput.length() !=0) { adddata(firstname); firstnameinput.settext(""); .........
you passing single paremeter adddata
method, 1 parameter being used data populate of columns.
as such want change adddata
method accept 5 parameters (address, lastname, firstname, age , malefemale) , populate columns respective data.
additionally subsequently call adddata
number of times (4) each data item (except malefemale). result in 4 rows being added per click of add button. believe want 1 row added such should call adddata
once 5 or 4 (perhaps haven't got malefemale yet) data items. end 1 row respective data.
edit after adding data reported working.
as you're having many problems, many of appear coming pre-existing code. appears of code untested. i'd suggest different approach. concentrate on getting working , add this.
as such here's working code (pretty basic) works , allows a) add friends (bar gender you'd want select this) , b) list them via view button.
first androidmanifest.xml (note! use comparison if needed)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="mjt.so46145559friendsdb"> <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundicon="@mipmap/ic_launcher_round" android:supportsrtl="true" android:theme="@style/apptheme"> <activity android:name=".friends"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name=".listdata"></activity> </application> </manifest>
activity_friends.xml layout friends activity (very basic no spinner) :-
<?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="match_parent" android:layout_height="match_parent" tools:context="mjt.so46145559friendsdb.friends"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hello world!" /> <edittext android:id="@+id/firstnameinput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="firstname" android:inputtype="text"/> <edittext android:id="@+id/lastnameinput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="lastname" android:inputtype="text"/> <edittext android:id="@+id/ageinput" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxlength="3" android:inputtype="number"/> <edittext android:id="@+id/addressinput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="address" android:inputtype="text"/> <button android:id="@+id/addbutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="add"/> <button android:id="@+id/viewbutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="view"/> </linearlayout>
note! might existing layout works.
activity_listdata.xml layout listdata activity invoked when view button clicked (extremely basic).
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <textview android:id="@+id/friendslist_heading" android:layout_width="match_parent" android:layout_height="wrap_content" /> <listview android:id="@+id/friendlist" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> </listview> </linearlayout>
listdataitem.xml layout used each item (row) displayed listview in listdata activity.
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <textview android:id="@+id/firstnamedisplay" android:layout_width="0dp" android:layout_weight="2" android:layout_height="match_parent" /> <textview android:id="@+id/lastnamedisplay" android:layout_width="0dp" android:layout_weight="2" android:layout_height="match_parent" /> <textview android:id="@+id/agedisplay" android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" /> <textview android:id="@+id/addressdisplay" android:layout_width="0dp" android:layout_weight="4" android:layout_height="match_parent" /> </linearlayout>
databasehelper.java sqliteopenhelper subclass, note changes have been made (brownie points available spotting them :))
public class databasehelper extends sqliteopenhelper { private static final string tag = "databasehelper"; public static final string table_name = "friends_table"; public static final string idcol = "_id"; public static final string col1 = "firstname"; public static final string col2 = "lastname"; public static final string col3 = "malefemale"; public static final string col4 = "age"; public static final string col5 = "address"; public databasehelper (context context) { super(context, table_name, null, 1); } @override public void oncreate(sqlitedatabase db) { string createtable = "create table " + table_name + " (" + idcol+ " text primary key, " + col1 + " text, " + col2 + " text, " + col3 + " text, " + col4 + " integer, " + col5 + " text " + ")"; db.execsql(createtable); } @override public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { db.execsql("drop if table exists" + table_name); oncreate(db); } public boolean adddata(string firstname, string lastname, string gender, int age, string address) { sqlitedatabase db = this.getwritabledatabase(); contentvalues contentvalues = new contentvalues(); contentvalues.put(col1, firstname); contentvalues.put(col2, lastname); contentvalues.put(col3, gender); contentvalues.put(col4, age); contentvalues.put(col5, address); long result = db.insert(table_name, null, contentvalues); //if data inserted inorrectly return -1 if (result == 1) return false; else { return true; } } /** * returns data db */ public cursor getdata() { sqlitedatabase db = this.getwritabledatabase(); string query = "select * " + table_name; return db.query(table_name,null,null,null,null,null,null); } /** * returns id matches name * searches db , returns id associated name */ public cursor getitemid(string name) { sqlitedatabase db = this.getwritabledatabase(); string query = "select " + col1 + " " + table_name + // select id db " " + col2 + " = '" + name + "'"; // last name = name selected cursor data = db.rawquery(query, null); return data; } /** * alternative means of getting id return long rather in cursor */ public long getid(string firstname) { long rv = 0; sqlitedatabase db = this.getwritabledatabase(); cursor csr = db.query(table_name,null,col2 + "=?",new string[]{firstname},null,null,null); if (csr.movetofirst()) { rv = csr.getlong(csr.getcolumnindex(idcol)); } csr.close(); return rv; } /** * updates name * * update table > set lastnname(col2) = newname = id = id in question = , lastname(col2) = oldname (was previously) > */ public void updatename (string newname, int id, string oldname) { sqlitedatabase db = this.getwritabledatabase(); string query = "update " + table_name + " set " + col2 + " = '" + newname + "' " + col1 + " = '" + id + "'" + " , " + col2 + " = '" + oldname + "'"; //logs new name log.d(tag, "updatename: query: " + query); log.d(tag, "updatename: setting name " + newname); // new name changing db.execsql(query); // execute query } /** * delete database * >>> delete table id = id passed , name = name passed * */ public void deletename(int id, string name){ sqlitedatabase db = this.getwritabledatabase(); string query = "delete " + table_name + " " + col1 + " = '" + id + "'" + " , " + col2 + " = '" + name + "'"; log.d(tag, "deletename: query: " + query); log.d(tag, "deletename: deleting " + name + " database."); db.execsql(query); // execute query } }
friends.java (bare bones works, prettifying :))
public class friends extends appcompatactivity { edittext firstnameinput, lastnameinput, ageinput, addressinput; button addbutton, viewbutton; databasehelper dbhlpr; context context; //############### fix_001 @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_friends); context = this; //########## fix_001 firstnameinput = (edittext) findviewbyid(r.id.firstnameinput); lastnameinput = (edittext) findviewbyid(r.id.lastnameinput); ageinput = (edittext) findviewbyid(r.id.ageinput); addressinput = (edittext) findviewbyid(r.id.addressinput); addbutton = (button) findviewbyid(r.id.addbutton); viewbutton = (button) findviewbyid(r.id.viewbutton); dbhlpr = new databasehelper(this); addbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { boolean addok = true; int age_as_int = -1; string firstname = firstnameinput.gettext().tostring(); string lastname = lastnameinput.gettext().tostring(); string age = ageinput.gettext().tostring(); string address = addressinput.gettext().tostring(); if (firstname.length() < 1) { toastmessage("you must enter in field!"); firstnameinput.requestfocus(); addok = false; } if (lastname.length() < 1) { toastmessage("you must enter in field!"); lastnameinput.requestfocus(); addok = false; } if (age.length() < 1) { toastmessage("you must enter in field!"); ageinput.requestfocus(); addok = false; } if (address.length() < 1) { toastmessage("you must enter in field!"); addressinput.requestfocus(); addok = false; } try { age_as_int = integer.parseint(age); } catch (numberformatexception e) { toastmessage("you must enter valid number in field!"); ageinput.requestfocus(); addok = false; } if (addok) { dbhlpr.adddata(firstname,lastname,"????",age_as_int,address); toastmessage("friend added!"); } } }); viewbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { intent intent = new intent(context,listdata.class); //########## fix_001 startactivity(intent); } }); } private void toastmessage(string message) { toast.maketext(this,message,toast.length_short).show(); } }
finally cheap , cheerful listdata.java
public class listdata extends appcompatactivity { listview mlistview; textview firstname, lastname, age, address; databasehelper dbhlpr; cursor friendlist; simplecursoradapter sca; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_listdata); mlistview = (listview) findviewbyid(r.id.friendlist); firstname = (textview) findviewbyid(r.id.firstnamedisplay); lastname = (textview) findviewbyid(r.id.lastnamedisplay); age = (textview) findviewbyid(r.id.agedisplay); address = (textview) findviewbyid(r.id.addressdisplay); dbhlpr = new databasehelper(this); friendlist = dbhlpr.getdata(); log.d("cursorcount","rows in cursor " + friendlist.getcount()); // make list of columns data extracted string[] dbcolums = { databasehelper.col1, databasehelper.col2, databasehelper.col4, databasehelper.col5 }; // make list of view's id data placed //note each column have respective view int[] listviewids = {r.id.firstnamedisplay, r.id.lastnamedisplay, r.id.agedisplay, r.id.addressdisplay}; // setup adapter sca = new simplecursoradapter( this, // context r.layout.listdataitem, // lasyout item friendlist, // cursor data dbcolums, // list of db columns data listviewids, // views in layout place data 0 // don't worry ); // tie adapter listview mlistview.setadapter(sca); } }
take these, perhaps start new project, as are, working , add small bits @ time. create new questions when have problems. please not amend questions removing stuff you've added add question asked. (very confusing bits going). make clear has been added.
it works per :-
a) when first started :-
b) adding data :-
c) view :-
Comments
Post a Comment