other class static (android)? - android

i've problem access other class in android...
i've class databasex (non static) and class CountingFragment (static)....
in CountingFragment i want to access databasex class..but i get result null....
here is my piece of code...
class Databasex
public class DataBasex {
public static final String KEY_ROWID="_id";
public static final String KEY_NAME="namaLokasi";
public static final String KEY_JENIS="jenis";
public static final String KEY_KETERANGAN="ket";
public static final String tanda="DataBasex";
private static final String DATABASE_NAME="DbPeta";
private static final String DATABASE_TABLE="lokasi";
private static final int DATABASE_VERSION=1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i(tanda,"dbHelper-> "+context);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.i(tanda,"onCreate-> "+db);
/*db.execSQL("CREATE TABLE " + DATABASE_TABLE + "("+
KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME +" TEXT NOT NULL, " + KEY_JENIS +" TEXT NOT NULL, " +
KEY_KETERANGAN +" TEXT NOT NULL);");
*/
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.i(tanda,"onUpgrade-> "+db);
//db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE);
//onCreate(db);
}
}
public DataBasex(Context c){
ourContext =c;
Log.i(tanda,"DataBasex-> "+ourContext);
}
public DataBasex open() throws SQLException{
Log.i(tanda,"DataBasex open awal ");
ourHelper = new DbHelper(ourContext);
ourDatabase=ourHelper.getWritableDatabase();
Log.i(tanda,"DataBasex open-> "+ourDatabase);
return this;
}
public void close(){
Log.i(tanda,"[close]");
ourHelper.close();
}
}
and here is CountingFragment class...
public static class CountingFragment extends SherlockFragment {
//here myproblem...
DataBasex con=new DataBasex(getSherlockActivity());
/**
*other method
*/
}
i think the code bellow is my problem
DataBase con=new DataBase(getSherlockActivity());
if in non-static class i use code bellow and everything is ok....but in static class i can't...why??
DataBase con=new DataBase(this);

It is due to the fact that Fragments need to first be attached to an Activity (see the document on Fragments before they can return an Activity. Specifically the lifecycle. First the Fragment is attached to an Activity (and onAttach() is called. Then the Fragment can get an Activity instance.
DataBasex con=new DataBasex(getSherlockActivity());
is in the root of the Class, it will return null - the Fragment does not have an Activity right off the bat.
Change
DataBasex con=new DataBasex(getSherlockActivity());
So it is:
DataBasex con;
And add this method:
#Override
public void onCreate (Bundle b)
{
super.onCreate (b);
con = new DataBasex(getSherlockActivity());
}

The reason for that is because in Static class there will be No Object, and the access of the methods will be class level access, but in the none-static class there will be an Object of that class, then you should have no null value in the none-static class

Related

SQLite Datebase Creation

I am trying to create a database, but nothing happening with my code. I know this question is very basic but I am a new learner so I could not solve my problem so kindly help me.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="employeedb";
private static final String TABLE_NAME="EMPLOYEETABLE";
private static final int DATABASE_VERSION=1;
private static final String EID="_id";
private static final String NAME="Name";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+EID+" INTEGER PRIMARY AUTOINCREMENT, "+NAME+" VARCHAR(255))";
private static final String DROP_TABLE="DROP TABLE "+TABLE_NAME+"IF EXISTS";
private Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Message.message(context, "Constructor called.");
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
Message.message(context, "onCreate called.");
db.execSQL(CREATE_TABLE);
}
catch (Exception e)
{
Message.message(context, ""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context, "onUpgrade called.");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
Message.message(context, ""+e);
}
}
}
Here is Message Class that only one method
public class Message {
public static void message(Context context, String message){
Toast.makeText(context,message,Toast.LENGTH_SHORT);
}
}
Here is MainActivity Code where i call the getWritabeDatase Method.
public class MainActivity extends Activity implements MyDialog.Communicator {
LinearLayout layout;
TextView txt;
TextView date;
DatabaseHelper dbhelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.layoutbottom);
date = (TextView) findViewById(R.id.date);
txt =(TextView) findViewById(R.id.title);
GeneralMethods generalmethods = new GeneralMethods(this,this);
dbhelper = new DatabaseHelper(this);
SQLiteDatabase sqLiteDatabase = dbhelper.getWritableDatabase();
}
public void showDialog(View v){
FragmentManager manager = getFragmentManager();
MyDialog myDialog = new MyDialog();
myDialog.show(manager,"MyDialog");
}
#Override
public void onDialogueMessage(String message) {
date.setText(message);
}
}
You onCreate will get called when you first access the database using the helper.
Any call to either
getReadableDatabase() or getWritableDatabase()
will cause the onCreate to get triggered and only then. Your onUpgrade will trigger when you change the database version of an already existing schema.
Also as per SQLite documentation, an integer primary key will automatically get incremented to the max+1 value on it's own.
Adding an Auto increment causes unnecessary explicit overhead and changes the rowid selection algorithm and they do not recommend it.
You have forgotten the show() for the toast in your Message class
Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
Basically without the show(), the Toast will not get shown, it will just get created. Now since onCreate gets called only once, to check if it's working , uninstall and reinstall the app or clear it's data before testing

How to save with onclicklistener - Android

I'm new to android. Here's one of my OnClickListeners. The thing is I don't know how to make it save when clicking the button. When I call createEventT(Event event), it says "non-static method cannot be referenced from a static context". Sometimes there's no error message, but the app crashes when clicking this button. Any ideas? Thanks.
OnClickListener:
OnClickListener doneT = new OnClickListener(){
#Override
public void onClick(View v) {
event.setTitle(inputToday.toString());
event.setYY(bearsCalendar.get(Calendar.YEAR));
event.setMM(bearsCalendar.get(Calendar.MONTH));
event.setDD(bearsCalendar.get(Calendar.DAY_OF_MONTH));
dateToday.setText(EventDBAdapter.createEventT(event));
}
};
And the event class:
public class Event {
int YY,MM,DD;
private String title;
public void setYY(int YY){this.YY=YY;}
public void setMM(int MM){this.MM=MM;}
public void setDD(int DD){this.DD=DD;}
public void setTitle(String title){this.title=title;};
public int getYY(){return YY;}
public int getMM(){return MM;}
public int getDD(){return DD;}
public String getTitle(){return title;}
}
public class EventDBAdapter{
private final Context mCtx;
static final String dbName="BearDatabase";
static final String eventTable="Events";
static final int dbVersion=1;
static final String colID="EventId";
static final String colTitle="Title";
static final String colDetails="Details";
static final String colYear="YY";
static final String colMonth="MM";
static final String colDay="DD";
static final String colHour="HH";
static final String colMinute="TT";
public DatabaseHelper mDbHelper;
public SQLiteDatabase mDb;
public EventDBAdapter(Context context){
mCtx=context;
}
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context,dbName,null,dbVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+eventTable+" ("+colID+" INTEGER PRIMARY KEY , "
+colTitle+" TEXT NOT NULL , "+colDetails+" TEXT , "
+colYear+" INTEGER , "+colMonth+" INTEGER , "+colDay+" INTEGER , "
+colHour+" INTEGER , "+colMinute+" INTEGER );");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + eventTable);
onCreate(db);
}
}
public EventDBAdapter open() throws SQLException{
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void upgrade(){
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
mDbHelper.onUpgrade(mDb, 1, 0);
}
public long createEventT(Event event){
ContentValues values = new ContentValues();
values.put(colTitle,event.getTitle());
values.put(colYear,event.getYY());
values.put(colMonth, event.getMM());
values.put(colDay, event.getDD());
return mDb.insert(eventTable,null,values);
}
public long createEventI(Event event){
ContentValues values = new ContentValues();
values.put(colTitle,event.getTitle());
return mDb.insert(eventTable,null,values);
}
}
Update:
Any problems in the database? After I made the changes, the whole thing crush.
change below to
dateToday.setText(EventDBAdapter.createEventT(event));
with below and it will work.
dateToday.setText(String.valueOf(EventDBAdapter.createEventT(event)));
I hope you are initializing event object before using it in onClick. if not, then initialize it like event = new Event(); before
event.setTitle(inputToday.toString());
Unless EventDBAdapter in your question is an instance of the EventDBAdapter class, then you are attempting to use a non-static method (public long createEventT()) in a static way (by accessing it through the class name).
To access it, you first need to create an instance of EventDBAdapter. One way to achieve this would probably be (assuming you are calling this method from inside an Activity):
long date = new EventDBAdapter(this).createEventT(event);
dateToday.setText(String.valueOf(date));
There are more answers on this topic here.

Android SQLiteOpenHelper : SOPL from onCreate() method not shown

im trying to do a system.out.println("something") inside onCreate() for SQLiteOpenHelper. but i didn't get anything. i even made sure to call getReadableDatabase();
anyone knows why?
this is my sqlite class
public class ChatOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "FeedReader.db";
private static final String CHAT_TABLE_NAME = "Bolster_ME_YOU";
private static final String CHAT_TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + CHAT_TABLE_NAME + " (" +
" test VARCHAR(255) );";
private static final String CHAT_TABLE_DELETE =
"DROP TABLE IF NOT EXISTS " + CHAT_TABLE_NAME + ");";
public ChatOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
System.out.println("hello from sqlite");
System.out.println(this.getDatabaseName());
db.execSQL(CHAT_TABLE_DELETE);
db.execSQL(CHAT_TABLE_CREATE);
Log.v("smartdbhelper", "after creation");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
this.onCreate(db);
}
}
//this is the activity class
public class LoginActivity extends ActionBarActivity {
private Button signin;
private Button signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
signin = (Button)findViewById(R.id.login_signin);
signup = (Button)findViewById(R.id.login_signup);
ChatOpenHelper open = new ChatOpenHelper(this);
SQLiteDatabase sql = open.getReadableDatabase();
sql.close();
open.close();
}
}
SQLiteOpenHelper.onCreate() is only called when the database is created for the first time.
You'd better use Log.d("label", "value") rather than System.out.print().

Insert data in sqlitedatabase using AndroidStudio

I am trying to insert data in the table MyProduct but every time i run the program it shows "null pointer exception" in db.insertData() in MainActivity and method insertData() in MyHelper class. Can anyone please tell me whats going wrong?? Thank You
MainActivity
public class MainActivity extends Activity {
MyHelper helper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new MyHelper(this);
SQLiteDatabase sqLiteDatabase=helper.getWritableDatabase();
// helper.onCreate(sqLiteDatabase);
helper.insertData();
}
}
MyHelper.class
public class MyHelper extends SQLiteOpenHelper {
static final String DATABASE_NAME="MyDatabase";
static final int DATABASE_VERSION=1;
static final String TABLE_NAME="MyCatalog";
static final String UID="ID";
static final String UTITLE="TITLE";
static final String UPRICE="PRICE";
static final String UDESCP="DESCP";
static final String CREATE_TABLE="CREATE TABLE"+TABLE_NAME+"("+UID+"VARCHAR(25) PRIMARY KEY,"+UTITLE+ " VARCHAR(255),"+UPRICE+" VARCHAR(255),"+UDESCP+" VARCHAR(255));";
private static final String DROP_TABLE="DROP TABLE" +TABLE_NAME+"IF EXISTS";
private Context context;
public MyHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.context=context;
Message.message(context,"Constructor called");
}
public void onCreate(SQLiteDatabase db)
{
Message.message(context,"on create");
db.execSQL(CREATE_TABLE);
Message.message(context,"table created");
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
Message.message(context,"upgrade called");
db.execSQL(DROP_TABLE);
onCreate(db);
}
ContentValues contentValues;
public SQLiteDatabase db;
public void insertData()
{
contentValues.put(UID,"W");
contentValues.put(UTITLE,"w");
contentValues.put(UPRICE,"10");
contentValues.put(UDESCP, "abc");
db.insert(TABLE_NAME, null, contentValues);
}
}
You haven't initialized your db or contentValues objects. At the start of your insertData method, try putting the following:
db = getWriteableDatabase();
contentValues = new ContentValues();

SQLite database problems

I have veritabani.java and i create database in this class. Then i create object in mainactivity.java. But when i run app. the program dont move database.java so i cant create database how i can solve this problem.
veritabani.java
public class veritabani extends SQLiteOpenHelper {
private static final String VERİTABANİ_ADİ="kayit";
public veritabani(Context c)
{
super(c,VERİTABANİ_ADİ,null,2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE kayit(ilacadi TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST kayit");
onCreate(db);
}
}
mainactivity.java
public class MainActivity extends Activity {
private veritabani v1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
v1=new veritabani(this);
}
v1=new veritabani(this) doesnt work.
Try this code
public class DBAdapter
{
private static final String DATABASE_NAME = "GSDATA.db";
private static final int DATABASE_VERSION = 2;
private static final String CREATE_COVERPHOTO_TABLE = "CREATE TABLE IF NOT EXISTS COVERPHOTO (path Text,date DATE);";
private final Context context;
public String group;
private DatabaseHelper DBHelper;
private static SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_COVERPHOTO_TABLE);
System.out.println("The Database is Created Here :");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// db.execSQL("DROP TABLE IF EXISTS calSimpleNote");
onCreate(db);
}
} // database helper class complete
// ---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
db.close();
}
// and write below line in main activity
DBAdapter adapter = new DBAdapter(MainActivity.this);
I'm not sure what you mean by "the program dont move database.java" but i had issues with databases using SQLiteOpenHelper.
Actually, SQLiteOpenHelper calls " public void onCreate(SQLiteDatabase db)" only once, so if you change your tables between 2 launch, it won't be updated.
To solve this you have to manually delete the database by going into parameters / applications / [your_app] / erase data (or something like this) and try again.

Categories

Resources