So basically my app starts out with a TabView, then through the options menu the user selects to add a game to the database. This opens the InputGame class, which accepts a few values, and then it should put them into a database when the user clicks "Submit". It will also go back to the original home view. The app goes back the the home tabs view just fine, bu nothing ever gets added to the database. Am I doing something wrong?
InputGame:
public class InputGame extends Activity {
private EditText gameTitle;
private Spinner consoleSelect;
private Spinner genreSelect;
private Spinner ratingSelect;
private Spinner styleSelect;
private EditText gamePub;
private EditText gameDev;
private EditText gameRegion;
private EditText gamePrice;
private EditText gameRelease;
private DatabaseHelper db = null;
private Cursor constantsCursor=null;
private Button addGame;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inputgame);
db = new DatabaseHelper(this);
constantsCursor = db.getReadableDatabase().rawQuery(
"SELECT _ID, title, console " + "FROM constants ORDER BY title",
null);
/*Hide the scroll bar*/
ScrollView sView = (ScrollView)findViewById(R.id.ScrollInput);
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);
/* Accepts game title */
gameTitle = (EditText) findViewById(R.id.gametitle);
/* Console select*/
consoleSelect = (Spinner) findViewById(R.id.console_select);
ArrayAdapter<CharSequence> consoleAdapter = ArrayAdapter.createFromResource(
this, R.array.consoles_array, android.R.layout.simple_spinner_item);
consoleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
consoleSelect.setAdapter(consoleAdapter);
/* Genre select*/
genreSelect = (Spinner) findViewById(R.id.genre_select);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
this, R.array.genres_array, android.R.layout.simple_spinner_item);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
genreSelect.setAdapter(genreAdapter);
/* Style select*/
styleSelect = (Spinner) findViewById(R.id.style_select);
ArrayAdapter<CharSequence> styleAdapter = ArrayAdapter.createFromResource(
this, R.array.style_array, android.R.layout.simple_spinner_item);
styleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
styleSelect.setAdapter(styleAdapter);
/* Rating select*/
ratingSelect = (Spinner) findViewById(R.id.rating_select);
ArrayAdapter<CharSequence> ratingAdapter = ArrayAdapter.createFromResource(
this, R.array.ratings_array, android.R.layout.simple_spinner_item);
ratingAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ratingSelect.setAdapter(ratingAdapter);
/* Accepts game publisher */
gamePub = (EditText) findViewById(R.id.gamepublisher);
/* Accepts game developer */
gameDev = (EditText) findViewById(R.id.gamedev);
/* Release date selector */
gameRelease = (EditText) findViewById(R.id.gamerelease);
/* Add the game button */
this.addGame = (Button)this.findViewById(R.id.addgame);
this.addGame.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
processAdd();
}
});
}
private void processAdd(){
ContentValues values=new ContentValues(8);
values.put("title", getGameTitle());
values.put("console", getGameConsole());
values.put("genre", getGameGenre());
values.put("style", getGameStyle());
values.put("rating", getGameRating());
values.put("publisher", getGamePublisher());
values.put("developer", getGameDeveloper());
values.put("release", getGameRelease());
db.getWritableDatabase().insert("constants", "title", values);
constantsCursor.requery();
Intent launchgamesActivity = new Intent(this, GCM.class);
startActivity(launchgamesActivity);
}
public String getGameTitle(){
return(gameTitle.getText().toString());
}
public String getGameConsole(){
return (consoleSelect.getContext().toString());
}
public String getGameGenre(){
return(genreSelect.getContext().toString());
}
public String getGameStyle(){
return(styleSelect.getContext().toString());
}
public String getGameRating(){
return(ratingSelect.getContext().toString());
}
public String getGamePublisher(){
return(gamePub.getText().toString());
}
public String getGameDeveloper(){
return(gameDev.getText().toString());
}
public String getGameRelease(){
return(gameRelease.getText().toString());
}}
and here is my database helper. The records I have pre-programmed in show up just fine:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "gameDb";
public static final String TITLE="title";
public static final String CONSOLE="console";
public static final String GENRE="genre";
public static final String RATING="rating";
public static final String PUBLISHER="publisher";
public static final String DEVELOPER="developer";
// public STATIC FINAL STRING REGION="REGION";
public static final String PRICE="price";
public static final String RELEASE="release";
public static final String COMPLETION="completion";
public static final String DESCRIPION="description";
public static final String IMAGE="image";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db
.execSQL("CREATE TABLE constants (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, console TEXT, genre TEXT, " +
"rating TEXT, publisher TEXT, developer TEXT, region TEXT, price REAL, release BLOB, completion BLOB, description BLOB, image BLOB);");
ContentValues cv = new ContentValues();
cv.put(TITLE, "Super Mario Galaxy");
cv.put(CONSOLE, "Wii");
db.insert("constants", TITLE, cv);
cv.put(TITLE, "Transformers: War for Cybertron");
cv.put(CONSOLE, "Xbox 360");
db.insert("constants", TITLE, cv);
cv.put(TITLE, "Final Fantasy XIII");
cv.put(CONSOLE, "Playstation 3");
db.insert("constants", TITLE, cv);
cv.put(TITLE, "Final Fantasy VII");
cv.put(CONSOLE, "Playstation");
db.insert("constants", TITLE, cv);
cv.put(TITLE, "New Super Mario Bros");
cv.put(CONSOLE, "Nintendo DS");
db.insert("constants", TITLE, cv);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.w("Constants",
"Upgrading database, which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS constants");
onCreate(db);
}
}
EDIT: When submitting from InputGames, should I be closing that activity all together? I think the way I have it set now just goes back to the other activity, but nothing really gets done. Or is that not it at all?
EDIT #2 Well I got it to add. For some reason I have to use .execSQL. Thats fine I guess, but bow when I try to add from a spinner item in InputGames, I get this populating the respective element:
com.jvavrik.gcm.InputGame#43bb0510
were the number after the "#" is always different. Any ideas for this?
What if you change this:
db.getWritableDatabase().insert("constants", "title", values);
to this:
db.getWritableDatabase().insert("constants", null, values);
Related
I am working with app that will have toggle button and I want to store on and off values in Database without using Edit Text can u tell me the process for this.
The following is a simple App that displays 3 buttons which when clicked toggle saving the state in an SQlite database.
It consists of 3 pieces of code (designing each would be a process to be followed):-
The layout which has 3 buttons activity_main.xml
The DatabaseHelper, which has the core database code and provides methods that can be used to add (insert), update and query rows DatabaseHelper.java.
The activity which manages the user interface MainActivity.java
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="#+id/toggle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/toggle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/toggle3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
DataabseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydatabase"; // The name of the database (the file name)
public static final int DBVERSION = 1; // The SQliteOpenHelper class provides a means of managing versions so verion nmber is required
//publicly availavle constants for the toggle states
public static final int TOGGLESTATUSON = 1;
public static final int TOGGLESTATUSOFF = 0;
// The table and the columns
public static final String TABLE_TOGGLE = "toggle";
public static final String COL_TOGGLE_ID = BaseColumns._ID; // using _id allows CursorAdapater to be used
public static final String COL_TOGGLE_STATUS = "toggle_status";
SQLiteDatabase mDB; // The database connection
// The Constructor
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION); // Call the super constructor
mDB = this.getWritableDatabase(); // store the connection
}
// This is called ONCE when the database is created. Used here to create the table
#Override
public void onCreate(SQLiteDatabase db) {
//The SQL for creating the table
String crt_toggle_table_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TOGGLE + "(" +
COL_TOGGLE_ID + " INTEGER PRIMARY KEY, " +
COL_TOGGLE_STATUS + " INTEGER " +
")";
// Execute the sql
db.execSQL(crt_toggle_table_sql);
}
//No Version management included
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add a row to the table (sets the button state to ON)
public long addToggleRow() {
ContentValues cv = new ContentValues();
cv.put(COL_TOGGLE_STATUS,TOGGLESTATUSON);
return mDB.insert(TABLE_TOGGLE,null,cv);
}
// Retrieve all rows
public Cursor getToggleRows() {
return mDB.query(TABLE_TOGGLE,null,null,null,null,null,null);
}
// Update a row, as per the provided id, toggling the value
public void toggleToggle(long id) {
mDB.execSQL(
"UPDATE " + TABLE_TOGGLE + " SET " + COL_TOGGLE_STATUS + " = NOT " + COL_TOGGLE_STATUS + " WHERE " + COL_TOGGLE_ID + " =?",
new String[]{String.valueOf(id)} // the arguments to be bound
);
}
}
MainActivity.java (managing the UI)
public class MainActivity extends AppCompatActivity {
//Class variables for the Buttons (3) and the DatabaseHelper object
Button[] mButtons = new Button[3];
DatabaseHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiate the DatabaseHelper (will create it when first run)
mDBHlpr = new DatabaseHelper(this);
initialiseDBToggleRows(); // Add the rows to the table, 1 per button, if not already added
// set the array of buttons
mButtons[0] = this.findViewById(R.id.toggle1);
mButtons[1] = this.findViewById(R.id.toggle2);
mButtons[2] = this.findViewById(R.id.toggle3);
// Get the buttons states from the database setting the button text to ON or OFF
loadButtons();
// Add the onCLickListeners to
// a) update the respective row in the database (toggle it)
// b) refresh the button display
for (int i=0; i < mButtons.length;i++) {
final int current = i;
mButtons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDBHlpr.toggleToggle((long)current + 1);
loadButtons();
}
});
}
}
// Set the button text according to the values tored in the database
private void loadButtons() {
Cursor csr = mDBHlpr.getToggleRows();
while (csr.moveToNext()) {
if (csr.getInt(csr.getColumnIndex(DatabaseHelper.COL_TOGGLE_STATUS)) == DatabaseHelper.TOGGLESTATUSON) {
mButtons[csr.getPosition()].setText("ON");
} else {
mButtons[csr.getPosition()].setText("OFF");
}
}
}
//Add a row, if no rows exist, for each button in the mButtons array
private void initialiseDBToggleRows() {
if(DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseHelper.TABLE_TOGGLE) > 0) return;
for (int i=0; i < mButtons.length; i++) {
mDBHlpr.addToggleRow();
}
}
}
Result
The App when installed looks like :-
Clicking any Button will toggle it from ON to OFF or from OFF to ON, the state is stored in the database so stopping the App and restarting maintains/restores the last state (unless the App is uninstalled or the App's data is cleared/deleted).
I would please need your help.
I would like to fill a spinner with data from another class.
When I click on the button btn_add, it adds data into my database. At the same time I store the "String-quality" into the sharedPreferences. The List I would like to fill is in the MainActivity-class and the button into the AddActivity-class.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
::::
public class AddActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
sqLiteHelper = new SQLiteHelper(AddActivity.this, "Plant.sqlite", null, 1);
sqLiteHelper.insertData(
edt_quality.getText().toString().trim(),
edt_name.getText().toString().trim()
);
//////////////////SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("TheQualities", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("quality", edt_quality.getText().toString().trim());
editor.apply();
//reset
resetFields(),
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
In the following class, I would like to fill my list.
1. problem: After sending data into my database, I have to restart the program before the quality appears into my list. I would like to update my list at the same time I send data into my database.
2. problem: The previous quality is always replace by the new one, I would like to fill the list and to maintain the eldest quality in the list.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
::::
public class MainActivity extends Activity {
Spinner spinner;
public static SQLiteHelper sqLiteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqLiteHelper = new SQLiteHelper(this, "item.sqlite", null, 1);
// Get reference of widgets from XML layout
spinner = (Spinner) findViewById(R.id.spinnerX);
// Initializing an ArrayAdapter
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, fillList()) {
}; spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
}
};
//RETRIEVING PREFERENCES
public String getQuality() {
SharedPreferences prefs = getSharedPreferences("TheQualities", 0);
return prefs.getString("quality", "choice");
}
public List<String> fillList() {
List<String> list = new ArrayList<>();
if(!list.contains(getQuality())) {
list.add(getQuality());
}
return list;
}
}
NB: there is no error while running the app.
Please does someone have an idea how I can do that?
Here's a quickly put together example as per the suggestion only using tables. That will also select the items according to the selected category.
Note this adds, for the sake of demonstration, 1 initial category (My First Category) and 1 item,that uses the My First Category. The item being named My First Item.
When listed the item's Category is also displayed.
It does not facilitate adding items. However, it does facilitate adding categories (noting that selecting an added from the spinner, will show nothing in the list, but re-selecting My First category will then list the item).
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydatabase";
public static final int DBVERSION = 1;
public static final String TABLE_ITEM = "item";
public static final String TABLE_CATEGORY = "category";
public static final String COLUMN_ITEM_ID = BaseColumns._ID;
public static final String COLUMN_ITEM_NAME = "itemname";
public static final String COLUMN_ITEM_CATEGORYREF = "category_reference";
public static final String COLUMN_CATEGORY_ID = BaseColumns._ID;
public static final String COLUMN_CATEGORY_NAME = "category";
SQLiteDatabase mDB;
public SQLiteHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_item_table = "CREATE TABLE IF NOT EXISTS " + TABLE_ITEM + "(" +
COLUMN_ITEM_ID + " INTEGER PRIMARY KEY, " +
COLUMN_ITEM_NAME + " TEXT, " +
COLUMN_ITEM_CATEGORYREF + " INTEGER" +
")";
db.execSQL(crt_item_table);
String crt_category_table = "CREATE TABLE IF NOT EXISTS " + TABLE_CATEGORY + "(" +
COLUMN_CATEGORY_ID + " INTEGER PRIMARY KEY," +
COLUMN_CATEGORY_NAME + " TEXT" +
")";
db.execSQL(crt_category_table);
mDB = db;
// ADD AN INITIAL CATEGORY AND THEN AN ITEM USING THAT CATEGORY
addCateory("My FIRST CATEGORY");
addItem("My First Item",1);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addCateory(String category) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_CATEGORY_NAME,category);
return mDB.insert(TABLE_CATEGORY,null,cv);
}
public long addItem(String name, long category_reference) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_ITEM_NAME,name);
cv.put(COLUMN_ITEM_CATEGORYREF,category_reference);
return mDB.insert(TABLE_ITEM,null,cv);
}
public Cursor getAllCategories() {
return mDB.query(TABLE_CATEGORY,null,null,null,null,null, COLUMN_CATEGORY_NAME + " ASC");
}
public Cursor getAllItemsWithCategoryName(long category_id) {
String table = TABLE_ITEM +
" JOIN " + TABLE_CATEGORY + " ON " + TABLE_ITEM + "." + COLUMN_ITEM_CATEGORYREF + " = " + TABLE_CATEGORY + "." + COLUMN_CATEGORY_ID;
String[] columns = new String[]{
TABLE_ITEM + "." + COLUMN_ITEM_ID,
COLUMN_ITEM_NAME,
COLUMN_CATEGORY_NAME
};
String whereclause;
String[] whereargs;
if (category_id < 1) {
whereclause = null;
whereargs = null;
} else {
whereclause = COLUMN_ITEM_CATEGORYREF + "=?";
whereargs = new String[]{String.valueOf(category_id)};
}
return mDB.query(table,columns,whereclause,whereargs,null,null,COLUMN_ITEM_NAME + " ASC");
}
}
Note the QUERY for the items in the getAllItemsWithCategoryName method is effectively SELECT item._id, itemname, category FROM item JOIN category ON item._id = category._id WHERE category_reference = ? ORDER BY itemname ASC
? will be the selected category id (category._id)
Note if the selected category id is 0, then the WHERE clause is omitted.
MainActivity.java
public class MainActivity extends Activity {
// Define class variables/objects
Spinner mCategorySpinner;
long mCurrentSelectedcategory = 0;
ListView mItemList;
Button btn_add;
Cursor mCategories, mItems;
SQLiteHelper mDBHlpr;
CursorAdapter mCategorySpinnerAdapter;
CursorAdapter mItemListViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Added button to initiate AddActivity
*/
btn_add = this.findViewById(R.id.add_button);
mCategorySpinner = (Spinner) this.findViewById(R.id.spinnerX);
mItemList = (ListView) this.findViewById(R.id.item_listview);
mDBHlpr = new SQLiteHelper(this);
setupOrRefreshUI();
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,AddActivity.class);
startActivity(i);
}
});
}
private void setupOrRefreshUI() {
//Category Spinner
mCategories = mDBHlpr.getAllCategories();
if (mCategorySpinnerAdapter == null) {
mCategorySpinnerAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_dropdown_item,
mCategories,
new String[]{
SQLiteHelper.COLUMN_CATEGORY_NAME
},
new int[]{
android.R.id.text1
},
0
);
((SimpleCursorAdapter) mCategorySpinnerAdapter).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mCategorySpinner.setAdapter(mCategorySpinnerAdapter);
mCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
mCurrentSelectedcategory = l;
setupOrRefreshUI();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} else {
mCategorySpinnerAdapter.swapCursor(mCategories);
}
//Item ListView
mItems = mDBHlpr.getAllItemsWithCategoryName(mCurrentSelectedcategory);
if (mItemListViewAdapter == null) {
mItemListViewAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
mItems,
new String[]{
SQLiteHelper.COLUMN_ITEM_NAME,
SQLiteHelper.COLUMN_CATEGORY_NAME
},
new int[]{
android.R.id.text1,
android.R.id.text2
},
0
);
mItemList.setAdapter(mItemListViewAdapter);
mItemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//<<<<<<<<<<<<<<<< handle clicking an item here
}
});
} else {
mItemListViewAdapter.swapCursor(mItems);
}
}
/**
* ADDED as this is called when activity is resumed, so rebuild the Spinner's list
*/
#Override
protected void onResume() {
super.onResume();
setupOrRefreshUI();
}
}
AddActivity.java
public class AddActivity extends AppCompatActivity {
EditText edt_quality;
Button btn_add, btn_done;
SQLiteHelper mDBHlpr;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
edt_quality = this.findViewById(R.id.edt_quality);
btn_add = this.findViewById(R.id.add_button);
btn_done = this.findViewById(R.id.done_button);
mDBHlpr = new SQLiteHelper(this);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newcategory = edt_quality.getText().toString();
if (newcategory.length() > 0) {
mDBHlpr.addCateory(newcategory);
}
}
});
btn_done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
activity_main.xml
<?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=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD NEW CATEGORY"/>
<Spinner
android:id="#+id/spinnerX"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Spinner>
<ListView
android:id="#+id/item_listview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
activity_add.xml
<?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=".AddActivity">
<EditText
android:id="#+id/edt_quality"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SAVE CATEGORY"/>
<Button
android:id="#+id/done_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DONE ADDING CATEGORIES"
/>
</LinearLayout>
NOTE The above is a working example, provided solely as a demonstration of how you could solve the numerous issues.
The Spinner will not magically refresh assuming that your flow is that you go to the AddActivity from the MainActivity, add the quality and then return.
If that is the case you need to refresh the Spinner's source and then tell the adapter that the data has changed. You do the latter using the Adapter's notifyDatasetChanged method.
Using List is very limited for List's (Spinner's, Listviews) that change. ArrayList is more adaptable.
Assuming the above, then the following is a working example based upon your code.
Note database access code has been commented out.
To simulate invoking the AddActivity a button has been added to MainActivity.
To simulate returnin/finishing
Code
AddActivity (basically button added for return)
public class AddActivity extends AppCompatActivity {
EditText edt_quality;
Button btn_add, btn_done;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
edt_quality = this.findViewById(R.id.edt_quality);
btn_add = this.findViewById(R.id.add_button);
btn_done = this.findViewById(R.id.done_button);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
/*
}
sqLiteHelper = new SQLiteHelper(AddActivity.this, "Plant.sqlite", null, 1);
sqLiteHelper.insertData(
edt_quality.getText().toString().trim(),
edt_name.getText().toString().trim()
);
*/
//////////////////SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("TheQualities", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("quality", edt_quality.getText().toString().trim());
editor.apply();
//reset
//resetFields()
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn_done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
MainActivity (see comments)
public class MainActivity extends Activity {
// Define class variables/objects
Spinner spinner;
Button btn_add;
ArrayAdapter<String> mSpinnerArrayAdapter;
ArrayList<String> mFillList; //<<<<<<<<<< changed from List<String>
//public static SQLiteHelper sqLiteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Added button to initiate AddActivity
*/
btn_add = this.findViewById(R.id.add_button);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,AddActivity.class);
startActivity(i);
}
});
//sqLiteHelper = new SQLiteHelper(this, "item.sqlite", null, 1);
// Get reference of widgets from XML layout
spinner = (Spinner) findViewById(R.id.spinnerX);
fillList(); //<<<<<<<<<< Fill the list for the spinner (will initially be empty)
// Initializing an ArrayAdapter
mSpinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, mFillList) {
};
mSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mSpinnerArrayAdapter);
}
/**
* ADDED as this is called when activity is resumed, so rebuild the Spinner's list
*/
#Override
protected void onResume() {
super.onResume();
fillList();
}
public String getQuality() {
SharedPreferences prefs = getSharedPreferences("TheQualities", 0);
return prefs.getString("quality", "choice");
}
/**
* Changed to do a little more depending upon status of the list and adapter
*/
public void fillList() {
// Initialise arraylist if not already initalised
if (mFillList == null) {
mFillList = new ArrayList<>();
}
// clear all elements from the arraylist
mFillList.clear();
// add the element (only ever 1)
if(!mFillList.contains(getQuality())) {
mFillList.add(getQuality());
}
// If the Adapter has been initialised then notify that the data has changed
if (mSpinnerArrayAdapter != null) {
mSpinnerArrayAdapter.notifyDataSetChanged();
}
}
}
Result
When App starts (very first time after install)
Nothing in Spinner.
Add button is clicked on MainActivity
Very Good is then entered in the EditText, ADD is clicked and then DONE is clicked :-
Main Activity is resumed
and as you can see Very Good can now be selected in the Spinner.
Note as it stands there will only ever be 1 choice, you would be better off obtaining the list from the database.
I have 7 checkboxes, if checked each checkbox will be calculate 3 edittext based on user input (Number). if user doesn't checked, 3 edittext setEnabled(false);
so, i have a problem when execute save button, it couldn't save if all checkbox are checked. i want only selected checkboxes can do saving in sqlite db and calcuate 3 ediitext.
Here is my code,
p1=(CheckBox)findViewById(R.id.cek1);
cp1=(EditText) findViewById(R.id.editcp1);
cp12=(EditText) findViewById(R.id.editcp12);
cp13=(EditText) findViewById(R.id.editcp13);
p1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
palm1=longitude+","+latitude;
Toast.makeText(getBaseContext(), palm1, Toast.LENGTH_SHORT).show();
percentage();
cp1.setEnabled(true);
cp1.setFocusable(true);
cp12.setEnabled(true);
cp12.setFocusable(true);
cp13.setEnabled(true);
cp13.setFocusable(true);
String larva1 = cp1.getText().toString().trim();
String larva12 = cp12.getText().toString().trim();
String pupa1 = cp13.getText().toString().trim();
}else{
palm1="-";
Toast.makeText(getBaseContext(), palm1, Toast.LENGTH_SHORT).show();
cp1.setEnabled(false);
cp1.setFocusable(false);
cp12.setEnabled(false);
cp12.setFocusable(false);
cp13.setEnabled(false);
cp13.setFocusable(false);
} }});
Here is handle when execute save Button
save = (Button)findViewById(R.id.btnsave);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int lv1= Integer.parseInt(larva1);
int lv12= Integer.parseInt(larva12);
int pup1= Integer.parseInt(pupa1);
int total=lv1+lv12+pup1;
String totallv1=Integer.toString(ttllv1);
upd.setpalm1(palm1);
upd.setlarva1(larva1);
upd.setlarva12(larva12);
upd.setpupa1(pupa1);
upd.settotal1(totallv1);
db.addUPD(upd);
db.close();
}});
Then MySQLiteHelper :
public void addUPD(UPD upd){
Log.d("addUPD", upd.toString());
SQLiteDatabase db = this.getWritableDatabase();
values.put(KEY_PALM1, upd.getpalm1());
values.put(KEY_LARVA1, upd.getlarva1());
values.put(KEY_LARVA12, upd.getlarva12());
values.put(KEY_PUPA1, upd.getpupa1());
values.put(KEY_TTL_LARVA, upd.getttl_larva());
db.insert(TABLE_UPD, null, values);
db.close();
}
Class UPD -->
public class UPD {
private String palm1;
private String larva1,larva12,pupa1,totallv1;
public String getpalm1(){
return palm1;}
public void setpalm1(String palm1) {
this.palm1 = palm1;}
public String getlarva1(){
return larva1;}
public void setlarva1(String larva1) {
this.larva1 = larva1;}
public String getlarva12(){
return larva12;}
public void setlarva12(String larva12) {
this.larva12 = larva12;}
public String getpupa1(){
return pupa1;}
public void setpupa1(String pupa1) {
this.pupa1 = pupa1;}
public String getttl_larva(){
return ttl_larva;}
public void setttl_larva(String ttl_larva) {
this.ttl_larva= ttl_larva;}
Please your advice
Example, table:
"CREATE TABLE settings (
checkId INTEGER NOT NULL,
value INTEGER NOT NULL DEFAULT 0);"
Code, in checkbox on checked change listener:
ContentValues cv = new ContentValues();
cv.put("value", isChecked); //checkbox value
db.update("settings", cv, "checkId LIKE ?", new String[] {checkBoxIndex});
i am a very very dumb newbie in Android Programming,
here i want to make a Cashflow note app in android studio.
In this case i want to create a table call Category_Table with 4 column called CategId, CategName, Note and Currency.
I have doing the tutorial from google and etc extacly. But till now i still have this problem.
When i want to insert some data into Category_Table, it says No Column named Currency in Android Studio report.
I dont know what to do, i have googling it but still cant solve this problem.
Please gimme an answer that i can understand as a newbie programmer.
Thanks.
NB. Here is my code:
Add_Category code :
public class AddCategory extends ActionBarActivity {
private static Button BtnIAdd;
private static Button BtnICancel;
EditText txtcategname, txtnote;
Spinner selectCurrency;
ArrayAdapter<CharSequence> adapterCurrency;
DatabaseHelper myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
myDB = new DatabaseHelper(this);
txtcategname = (EditText)findViewById(R.id.editText);
txtnote = (EditText)findViewById(R.id.editText2);
BtnICancel = (Button)findViewById(R.id.btnCancel);
BtnIAdd = (Button)findViewById(R.id.btnAdd);
//spinner
selectCurrency = (Spinner) findViewById(R.id.spin_selectCurrency);
adapterCurrency = ArrayAdapter.createFromResource(this, R.array.CurrencyName,android.R.layout.simple_spinner_item );
adapterCurrency.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCurrency.setAdapter(adapterCurrency);
selectCurrency.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position)+" selected",Toast.LENGTH_LONG).show();
String currencyValue = String.valueOf(parent.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
addCategData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_category, menu);
return true;
}
public void addCategData(){
BtnIAdd.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(AddCategory.this,"Clicked", Toast.LENGTH_LONG).show();
boolean isInserted = myDB.insertCategData(txtcategname.getText().toString(),
txtnote.getText().toString(), selectCurrency.getSelectedItem().toString());
if (isInserted == true)
Toast.makeText(AddCategory.this,"Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(AddCategory.this,"Not Inserted", Toast.LENGTH_LONG).show();
}
}
);
BtnICancel.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this one for DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String MyVillageSoftware = "MyVillageSoftware";
public static final String DATABASE_NAME = "Cashflow.db";
public static final String TABLE_Categ_NAME = "category_table";
public static final String COL1 = "CategId";
public static final String COL2 = "CategName";
public static final String COL3 = "Note";
public static final String COL4 = "Currency";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Drop Table" + TABLE_Categ_NAME);
/*db.execSQL("Create table " + TABLE_Categ_NAME +
"(CategID Integer PRIMARY KEY AUTOINCREMENT " +
"CategName Text" +
"Note Text" +
"Currency Text)");*/
}
public boolean insertCategData(String categname, String note, String currency){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, categname);
contentValues.put(COL3, note);
contentValues.put(COL4, currency);
long result = db.insert(TABLE_Categ_NAME, null, contentValues);
if (result == -1)
return true;
else
return false;
}
public ArrayList<String>getAllCategory(){
ArrayList<String> AllCategoryList = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String selectCateg="Select * FROM " +TABLE_Categ_NAME;
Cursor cursor = db.rawQuery(selectCateg, null);
if(cursor.getCount()>0){
while (cursor.moveToNext()){
String categname=cursor.getString(cursor.getColumnIndex(COL2));
AllCategoryList.add(COL2);
}return AllCategoryList;
}
return AllCategoryList;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_Categ_NAME);
onCreate(db);
thanks before... :)
1) Uninstall the App and Install again.
2) issue is "No Column named Currency in Android Studio report" this is because column currency might be added after table created. so for that you have to define Database Version(an integer value e.g. Ver=1) and change the version of DB whenever you do changes in database(increase that int value e.g. Ver=2) so it will call onUpgrade() and drop your tables and create it again. this will solve your problem.
EDIT: You have given that Database version 1 as default in super(context,dbName,cursorFactory,dbVersion)
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
So i used a editText called "add", when i click on the button he have to insert into a table a title (string) and amount(int) and comments (string) .
the title is like this : String title = add.getText().toString();
But it does not appear in the table .
Plus when i had forgotten the "getText()" it displayed : android.widget.EditText#43e41168 .
I dont know why ...
(Sorry for my bad english, i'm french ^^).
private Table income;
private Table expense;
String title,comment;
int amount;
EditText add;
Button add_btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHelper helper = new DatabaseHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
expense = new Table(db,helper.TABLE_1);
income = new Table(db,helper.TABLE_2);
add_btn = (Button)findViewById(R.id.add_btn);
add = (EditText)findViewById(R.id.add);
add_btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
title = add.getText().toString();
income.insertTable(title, 100, " test");
expense.insertTable("another title", 50, "blah blah");
}
}
this is the right answer, i had to move the String title from the onCreate to the onClick.