How to run main in android - java

Hi all i am writing simple app to train my ContentProvider skills .So i wrote Contract class that specifies all the meta data for all the tale her it is
public class StoreContract {
public static String AUTHORITY = "com.ura.store.intentProvider";
public static String DATABASE_NAME = "Store.db";
public static class Customer{
public static final String TABLE_NAME ="tblCustomers";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_NAME="First Name";
public static final String COLUMN_LAST_NAME = "Last name";
public static final String COLUMN_PHONE_NUMBER = "Phone number";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NAME+" TEXT , "
+COLUMN_LAST_NAME+" TEXT , "
+COLUMN_PHONE_NUMBER+" TEXT);";
}
static class Seller{
public static final String TABLE_NAME = "tblEmployes";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_NAME="First Name";
public static final String COLUMN_LAST_NAME = "Last name";
public static final String COLUMN_EMPLOY_TYPE = "Type";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NAME+" TEXT , "
+COLUMN_LAST_NAME+" TEXT , "
+COLUMN_EMPLOY_TYPE+" TEXT);";
}
static class Buy{
public static final String TABLE_NAME = "tblBuys";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_CUSTOMER_ID = "Customer";
public static final String COLUMN_SELLER_ID = "Seller";
public static final String COLUMN_INFO = "Info";
public static final String COLUMN_PRICE = "Price";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_CUSTOMER_ID+" TEXT, "
+COLUMN_SELLER_ID+" TEXT , "
+COLUMN_INFO+" TEXT "
+COLUMN_PRICE+" REAL"
+"FOREIGN KEY("+COLUMN_CUSTOMER_ID+") REFERENCES "+Customer.TABLE_NAME+"("+Customer.COLUMN_AUTO_ID+")"
+"FOREIGN_KEY("+COLUMN_SELLER_ID+") REFERENCES "+Seller.COLUMN_AUTO_ID+"("+Seller.COLUMN_AUTO_ID+")";
}
public static void main(String []args){
System.out.println(StoreContract.Customer.CREAT_STRING);
}
Notice the main method i wrote it to see how my Table creation String looks like of course the method didn't work probably be cause it is Android Project .So my question is simple what do you suggest to do in such cases i mean a except of copying and passing all class in to other project i am pretty sure that there is a standard solution for this stuff some unit-test or something.
Thank :)

The Android equivalent of the main method is onCreate() in Activities (and pretty much everywhere else)

Unlike pure java applications, Android apps will not call main() as their starting point, but instead the onCreate() method of their top level activity. This activity needs to be specified by name through <action android:name="android.intent.action.MAIN" /> in the manifest section defining that activity.
To go about this, you would make a class that inherits from activity, add the code from your current main method in the onCreate() method, and access the class you have currently from there.
Also, there is a lot more to how android handles the lifespan of activities, and the method calls in them. I recommend this link as a starting point to look into how android code runs.

Related

Correct way to use static parameters in Android

I am pretty new in Android and I do not know how is the proper way to manage static constants. I mean, I need to use several constants (such as COMMAND_BACK = 100) in several Java classes and activities. It is not beautiful to declare them as attributes in each single activity so, what is the correct way to do this?
I though about declaring them in strings.xml, but it does not seem suitable neither...
Thanks in advance.
You can make a class like this :
public final class AppConstants {
//put all the constant here
// Eg :
public static final int SPLASH_TIME = 1000;
}
The disadvantage by declaring it in a resource.xml file is that you need a context to receive the value. This is fine as long as you need those values inside a context class otherwise you have to pass one around.
The elegant solution would be extending the Application class since the android os itself uses static fields that way.
Declare
public final class ConstantClass {
public final static int COMMAND_BACK = 100;
}
Usage
int num = ConstantClass.COMMAND_BACK;
Add a Constants class to the project
public class Constants {
public static final String STRING1 = "First String";
public static final String STRING2 = "Second String";
public static final int INTEGER1 = 1;
public static final float FLOAT1 = 0.1f;
}
// Use
textView.setText(Constants.STRING1);
Create a common interface where you can declare all the constants.Constants can further be grouped here to make it mode clean.
public interface Constants {
public interface XYZ{
public static final int A= 1;
public static final int B= 2;
}
public interface REPORT_TYPE_FLAGS{
public static final String C= "0";
public static final String D= "1";
}
}
Another elegant way is to define a constant class with other inner subclasses
`private final class Constant {
public static class TypeOne {
public static final String NAME = "Type 1";
public static final int CODE = 1;
}
public static class TypeTwo {
public static final String NAME = "Type 2";
public static final int CODE = 2;
}
}
`
And you can access it in this way
`String typeOneName = Constant.TypeOne.NAME;
int typeTwoCode = Constant.TypeTwo.CODE;
`

Creating a Database in Android

Okay so I've followed a few tutorials and created a databaseHelper class after following a tutorial. However I don't fully understand or get how to actually create the database in the first place.
In my mainActivity I've added this to my onCreate but it doesn't create any database or at least nothing shows up in my Android Device Monitor.
Basically how do I actually get the database to be created?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
dbHelper = new databaseHelper(this);
}
Java
public class databaseHelper extends SQLiteOpenHelper {
static final String DATABASEHELPER = "DATABASE HELPER";
static final String dbName="chefs";
//User Table Fields
static final String userTable="user";
static final String userColID="userID";
static final String userColName="firstName";
static final String userColLast="lastName";
static final String userColDOB="DOB";
static final String userColGend="gender";
static final String userColAddr="address";
static final String userColPost="postcode";
static final String userColBio="bio";
static final String userColUser="username";
static final String userColEmail="email";
static final String userColPass="password";
static final String userColPic="picture";
static final String userColLastLog="lastlogin";
static final String userColLastLogIP="lastloginIP";
static final String userColRegisteredIP="registeredIP";
static final String userColCreatedOn="createdOn";
//Recipe Table Fields
static final String recipeTable="recipe";
static final String recipeColID="recipeID";
static final String recipeColName="name";
static final String recipeColCate="category";
static final String recipeColDesc="description";
static final String recipeColUserID="user_userID";
//Ingredient Table Fields
static final String ingredientTable="ingredient";
static final String ingredientColID="ingredientID";
static final String ingredientColRecipeID="recipe_recipeID";
static final String ingredientColName="name";
static final String ingredientColAmount="amount";
static final String ingredientColUnit="unit";
//Step Table Fields
static final String stepTable="step";
static final String stepColID="stepID";
static final String stepColRecipeID="recipe_recipeID";
static final String stepColNumber="stepNumber";
static final String stepColDesc="description";
public databaseHelper(Context context) {
super(context, dbName, null,1);
Log.d(DATABASEHELPER, "Database Created");
}
#Override
public void onCreate(SQLiteDatabase db) {
// Creating User Table
db.execSQL("CREATE TABLE "+userTable+" ("+userColID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+userColName+" TEXT, "+userColLast+" TEXT, "
+userColDOB+" NUMERIC, "+userColGend+" TEXT, "+userColAddr+" TEXT, "+userColPost+" TEXT, "+userColBio+" TEXT, "
+userColUser+" TEXT, "+userColEmail+" TEXT, "+userColPass+" TEXT, "+userColPic+" TEXT, "+userColLastLog+" NUMERIC, "
+userColLastLogIP+" TEXT, "+userColRegisteredIP+" TEXT, "+userColCreatedOn+" NUMERIC)");
// Creating Recipe Table
db.execSQL("CREATE TABLE "+recipeTable+" ("+recipeColID+" INTEGER AUTOINCREMENT, "+recipeColName+" INTEGER, "+recipeColCate+" TEXT, "
+recipeColDesc+" TEXT, "+recipeColUserID+" INTEGER");
// Creating Ingredient Table
db.execSQL("CREATE TABLE "+ingredientTable+" ("+ingredientColID+" INTEGER AUTOINCREMENT, "+ingredientColRecipeID+" TEXT ,"+ingredientColName+" TEXT, "
+ingredientColAmount+" INTEGER, "+ingredientColUnit+" TEXT");
db.execSQL("CREATE TABLE "+stepTable+" ("+stepColID+" INTEGER AUTOINCREMENT, "+stepColRecipeID+" INTEGER, "+stepColNumber+" INTEGER, "
+stepColDesc+" TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(DATABASEHELPER, "Upgrading Database");
}
}
Any help is appreciated.
As given in the android documentation, the database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.
Link: http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

Android: Creating a Login/Register Screen using an SQLite database?

I want to add a Login/Register Activity at the start of my Application.
Can I do so using SQLite, I.e. with the help of a "DatabaseHelper" class?
I have already implemented a Database within my application using the DatabaseHelper class shown below that extends SQLiteOpenHelper
Can I just create another class like this, or extend the current one? If so, how would I do so?
Current class (note this is database for storing game scores etc):
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 10;
// Database Name
private final static String DATABASE_NAME = "MeditationDatabase";
// Contacts table name
private static final String TABLE_SCORE = "scores";
// Contacts Table Columns names
private static final String COL_SESSION = "sessionid";
private static final String COL_GAMETITLE = "game";
private static final String COL_NAME = "name";
private static final String COL_MED = "avgmeditation";
private static final String COL_MAX = "maxmeditation";
private static final String COL_AVGATT = "avgattention";
private static final String COL_MAXATT = "maxattention";
private static final String COL_SCORE = "score";
private static final String COL_DATE = "date";
/**
* Constructor
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Method that creates the database
*/
#Override
public void onCreate(SQLiteDatabase db) {
//VERY IMPORTANT: ALWAYS CHECK THAT THERE ARE SPACES AND COMMAS IN CORRECT PLACE IN CODE BELOW:
String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "(" + COL_SESSION
+ " STRING PRIMARY KEY, " + COL_GAMETITLE + " STRING, " + COL_NAME + " STRING, " + COL_MED + " INTEGER, "
+ COL_MAX + " INTEGER, " + COL_AVGATT + " INTEGER, " + COL_MAXATT + " INTEGER, " + COL_SCORE + " INTEGER, " + COL_DATE + " STRING " + ")";
db.execSQL(CREATE_TABLE_SCORE);
}
/**
* Method that upgrades the database
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE);
// Create tables again
onCreate(db);
}
/**
* All CRUD operations
*/
// Adding new score details (Name, score, date)
void addScore(Score score) {
SQLiteDatabase db = this.getWritableDatabase();
// ContentValues- holds the values.
ContentValues values = new ContentValues();
values.put(COL_SESSION, score.getSessionID());
values.put(COL_GAMETITLE, score.getGameTitle());
values.put(COL_NAME, score.getName());
values.put(COL_MED, score.getMeditation());
values.put(COL_MAX, score.getMax());
values.put(COL_AVGATT, score.getAvgAttention());
values.put(COL_MAXATT, score.getMaxAttention());
values.put(COL_SCORE, score.getScore());
values.put(COL_DATE, score.getDate());
// Inserting Row (i.e. the values that were entered from above
db.insert(TABLE_SCORE, null, values);
db.close(); // Closing database connection
}
}
The better approach here is to inner class your helper. Then add method to your outer class to manipulate the data or whatever else like login or register!
public class DataAccsses {
public Boolean login(String username, String password){
}
public Boolean regester(//what ever needed here){
}
//other data manipulation method from your helper
class DatabaseHelper extends SQLiteOpenHelper {
//keep everything private. outer class can access inner class private members.
}
}
You only need one helper in your application (except rare conditions) So do not create another one. You can put as many as methods in your outer class DataAccess as needed to cover all the oprations on the database on all the tables.

Android SQLite errors while inserting records

I have tried many things and searched both SO and google, but this is an odd error. The error happens when I click a button which creates(inserts) a new level in the database.
Logcat follows:
http://pokit.org/get/?564ecab747237335f72006e8e3d5d633.jpg
There is more down but it's the same error.
And here is the code that does the insert. I'm using SQLiteAssetHelper by the way.
public void createLevel(Level lev){
ContentValues values = new ContentValues();
if(lev.getGameMode()=="SinglePlayer")
{
LevelSinglePlayer level=(LevelSinglePlayer)lev;
values.put(GAME_MODE_COLUMN, level.getGameMode());
values.put(DIFFICULTY_COLUMN, level.getDifficulty());
values.put(SINGLE_PLAYER_MODE_COLUMN, level.getSinglePlayerMode());
values.putNull(TIME_CHALLENGE_MODE_COLUMN);
values.put(POINTS_COLUMN, level.getPoints());
values.put(LIVES_COLUMN, level.getLives());
values.putNull(TIME_COLUMN);
values.put(SUFFIX_COLUMN, level.getSuffix());
values.put(SUFFIX_WORDS_COUNT_COLUMN, level.getSuffixWordsCount());
db.insert(LEVELS_TABLE, null, values);
Log.w("INSERT_NEW_LEVEL", "SUCCESSFUL INSERT");
}
else if(lev.getGameMode()=="TimeChallenge")
{
LevelTimeChallenge level= (LevelTimeChallenge)lev;
values.put(GAME_MODE_COLUMN, level.getGameMode());
values.put(DIFFICULTY_COLUMN, level.getDifficulty());
values.putNull(SINGLE_PLAYER_MODE_COLUMN);
values.put(TIME_CHALLENGE_MODE_COLUMN, level.getTimeChallengeMode());
values.put(POINTS_COLUMN, level.getPoints());
values.put(LIVES_COLUMN, level.getLives());
values.put(TIME_COLUMN, level.getTime());
values.put(SUFFIX_COLUMN, level.getSuffix());
values.put(SUFFIX_WORDS_COUNT_COLUMN, level.getSuffixWordsCount());
db.insert(LEVELS_TABLE, null, values);
Log.w("INSERT_NEW_LEVEL", "SUCCESSFUL INSERT");
}
}
I have three tables, created by the following statements:
CREATE TABLE IF NOT EXISTS words(_id INTEGER PRIMARY KEY, word TEXT, tezina INTEGER)
CREATE TABLE IF NOT EXISTS levels(_id INTEGER PRIMARY KEY, modIgre TEXT NOT NULL, tezina INTEGER NOT NULL, modSingle TEXT, modTime TEXT, targetpoints INTEGER, lives INTEGER, nastavak TEXT, brojRijeciNastavak INTEGER, locked BOOLEAN, earnedpoints INTEGER, kaladonts INTEGER, req2stars INTEGER, req3stars INTEGER)
CREATE TABLE IF NOT EXISTS highscores(_id INTEGER PRIMARY KEY, player TEXT, points INTEGER)
I can post anything needed quickly.
EDIT: Java consts
//konstante(nazivi tabela)
private static final String GAME_MODE_COLUMN = "modIgre";//mod igre - single, time
private static final String DIFFICULTY_COLUMN = "tezina";//tezina rijeci na levelu
private static final String SINGLE_PLAYER_MODE_COLUMN = "modSingle";//mod single playera
private static final String TIME_CHALLENGE_MODE_COLUMN = "modTime";//mod time challenga
private static final String POINTS_COLUMN = "points";
private static final String LIVES_COLUMN = "lives";//zivoti
private static final String TIME_COLUMN = "";//koliko vrijeme?
private static final String SUFFIX_COLUMN = "nastavak";//koji nastavak?
private static final String SUFFIX_WORDS_COUNT_COLUMN = "brojRijeciNastavak";//koliko
private static final String ID_COLUMN = "_id";
private static final String TARGET_POINTS_COLUMN = "targetpoints";
private static final String LOCKED_COLUMN = "locked";
private static final String KALADONTS_COLUMN = "kaladonts";
private static final String TWO_STARS_COLUMN = "req2stars";
private static final String THREE_STARS_COLUMN = "req3stars";
private static final String EARNED_POINTS_COLUMN = "earnedpoints";
private static final String LEVELS_TABLE = "levels";
Your TIME_COLUMN is an empty string, causing the invalid SQL to be created:
private static final String TIME_COLUMN = "";//koliko vrijeme?
You can replace it with your actual column name. Didn't see a suitable column in your CREATE TABLE so it's possible that you should remove the put(TIME_COLUMN) calls altogether.
There is extra ',' in ur query or u r forget to put first field in ur query so correct query is :
INSERT into levels(modIgre,modTime,modSingle,brojRijeciNastavak,nastavak,tezina,lives,points)Values(?,?,?,?,?,?,?,?)
Your primary Key seems to be null and values too.
INSERT into levels(,modIgre,modTime,modSingle,brojRijeciNastavak,nastavak,tezina,lives,points)Values(?,?,?,?,?,?,?,?)
it is a problem because you begin your query by ,.

What are the possible ways to store this data?

Well, I need this data to be used in at least two classes:
String navHome = "home";
String navAbout = "about";
String navUpload = "upload";
String navUploadProc = "uploadProc";
String navStartUpload = "startUpload";
String navContact = "contact";
String navSearch = "search";
String navManual = "manual";
String navBackToGmis = "backToGmis";
I was thinking of just pasting that into other classes, but then it violates the principles of programming, since it's repeating the same thing. Text and XML files are not comfortable to store data, inheritance isn't an option, since Java doesn't support multiple inheritance... Any ideas?
Yeah, I know it will sound retarded to most of you, but I need tipps on this.
If these are constants, then you can declare them in one class (or interface) and use them in another:
A.java:
public class A {
public static final String navHome = "home";
public static final String navAbout = "about";
public static final String navUpload = "upload";
public static final String navUploadProc = "uploadProc";
public static final String navStartUpload = "startUpload";
public static final String navContact = "contact";
public static final String navSearch = "search";
public static final String navManual = "manual";
public static final String navBackToGmis = "backToGmis";
. . .
}
B.java:
import static A.*; // or list each String in a separate import
public class B {
. . . // code can use nav* as if they were declared in class B
}

Categories

Resources