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.
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 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);
}
I am adding TextView programmatically on LinearLayout :
And then I click on a TextView and I pass IDs and Texts of TextView to another Activity (With SharedPreferences).
But when I get data from SharedPreferences in another activity and see data with Log I just get the ID and Value bottommost TextView.
(For example i just see the data of TextView_3).
But perhaps i had multiple TextView on LinearLayout and i click on 2nd TextView or another TextView but it just get me data of bottommost TextView.
public class ChatPage extends Activity {
TextView[] txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_page);
txt = new TextView[totalPersons];
for (int s = 0; s < listOfPersons.getLength(); s++) {
txt[s] = new TextView(ChatPage.this);
if (group.equals("Admin")) {
txt[s].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startActivity(new Intent(
ChatPage.this,
ConversationPage.class));
editor.putString("Adminid", id);
editor.putString("NameAdmin", name);
editor.commit();
}
});
}
if (group.equals("User")) {
txt[s].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startActivity(new Intent(
ChatPage.this,
ConversationPage.class));
editor.putString("Userid", id);
editor.putString("NameUser", name);
editor.commit();
}
});
}
}
}
}
Another Activity i get data :
UserID = (shared.getString("Userid", "NULLID"));
UserNAME = (shared.getString("NameUser", "NULLNAME"));
IDAdmin = (shared.getString("Adminid", "NULL_idSharee"));
AdminName = (shared.getString("NameAdmin", "NULL_NameSharee"));
Log.i("test", "UserID " + UserID );
Log.i("test", "UserNAME " + UserNAME );
Log.i("test", "IDAdmin " + IDAdmin );
Log.i("test", "AdminName " + AdminName );
It's a java issue, you need to instantiate new class for each on click listener, you can't do in this way. create a private class in your code
private class MyOnClickListener implements OnClickListener {
private final String mId;
public MyOnClickListener(String id) {
mId= id;
}
public void onClick(View v) {
Intent intent= new Intent(getApplicationContext(), ACtivity.class);
intent.putExtra("current_post_id", mId);
startActivity(intent);
}
}
then
textView.setOnClickListener(new MyOnClickListener(id));
add your views like this:
final View view = getLayoutInflater().inflate(R.layout.yourLayout,
yourLinearLayout, false);
TextView text= (TextView ) view.findViewById(R.id.chapter_page);
view.setTag(unique Id);//your TextView's id that later use in onClick
text.setText(yourText);
goToPage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int id = (Integer) view.getTag();//this return clicked textView id
//do some thing...
}
});
yourLinearLayout.addView(view);
you can put this code in loop and add view to linearLayout more than one.
you should provide a unique id to your text view like this
for an example
public void add_Text_view_row(String name,int i){
TextView a = new TextView(getActivity());
a.setText(name);
a.setId(17*i);
linearlayout_your.addView(a);
a.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// your codes should be here
}
});
}
you can use this method in side a loop.you should pass data to those parameters
Your response is here :
///In your Oncreate
txt[s].setText(usename);
txt[s].setLayoutParams(params);
txt[s].setTextColor(Color.BLACK);
txt[s].setClickable(true);
txt[s].setId(5*s);
txt[s].set
OnClickListener(new listen(s,idTwo,nameTwo));
//----//
////And then create a class
public class listen implements OnClickListener{
int bId;
String Pid;
String Pname;
listenSharee(int _id,String _Pid,String _Pname) {
bId = _id;
Pid = _Pid;
Pname = _Pname;
}
#Override
public void onClick(View v) {
startActivity(new Intent(ChatPage.this,YourClass.class));
editor.putString("Aname", Pid);
editor.putString("Aname", Pname);
editor.commit();
//Toast.makeText(getBaseContext(), txt[bId].getText()+ " * " + Pid + " * " + Pname, Toast.LENGTH_LONG).show();
}
}
Good Luck. ;)
I have a Mainactivity that contains the list of Trainings. And on each list is clicked it starts the session of the same training in whole application.
I managed to use Singleton and access that into my main activity. But onItemClick it takes to dialog box and on button click inside dialog it should take to another activity. Now I a getting error like java NullPointerException. Here is the code below;
Remember: I want same training session in second activity also.
MainActivity class;
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
currentTraining = (Training)arg0.getAdapter().getItem(arg2);
Log.i("DEBUG", currentTraining.getTitle());
CurrentTraining.getInstance().setTraining(currentTraining);
Toast.makeText(
getApplicationContext(),
"You clicked on position : " + arg2 + " and ID : "
+ currentTraining.getId(), Toast.LENGTH_LONG).show();
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(currentTraining.getTitle());
TextView description = (TextView) dialog.findViewById(R.id.textView1);
description.setText("Description: " + currentTraining.getDescription());
TextView location = (TextView) dialog.findViewById(R.id.textView2);
location.setText("Location: " + currentTraining.getLocation());
TextView date = (TextView) dialog.findViewById(R.id.textView3);
date.setText("Date: " + currentTraining.getDate());
Button back_btn = (Button) dialog.findViewById(R.id.button1);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
Button start_btn = (Button) dialog.findViewById(R.id.button2);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
TraineeActivity.class);
//intent.putExtra("trainingId", currentTraining.getId());
//intent.putExtra("title", currentTraining.getTitle().toString());
MainActivity.this.startActivity(intent);
}
});
dialog.show();
}
And in second Activity Class;
Training currentTraining;
private ListView personNamesListView;
// Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter traineeListAdapter;
private TextView TitleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trainees);
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Log.i("DEBUG", ""+currentTraining.getTitle());
TitleView = (TextView)findViewById(R.id.training_title);
TitleView.setText(currentTraining.getTitle());
Button addnew = (Button) findViewById(R.id.add_btn);
addnew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(TraineeActivity.this,
FormActivity.class);
TraineeActivity.this.startActivity(intent);
}
});
personNamesListView = (ListView) findViewById(R.id.traineeslist);
// Create a list that contains only full name of the trainee
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
protected void onResume(){
super.onResume();
traineeListAdapter = new ArrayAdapter<Trainee>(this, android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
My Singleton Class:
public class CurrentTraining {
private Training training ; //Training is my model class
private static CurrentTraining instance;
private CurrentTraining() {
}
public static CurrentTraining getInstance() {
if (instance == null)
instance = new CurrentTraining();
return instance;
}
public Training getTraining() {
return training;
}
public Training setTraining(Training training) {
return this.training = training;
}
}
In onCreate() of your second activity, you do this:
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Since currentTraining is null, this will just set the singleton variable training to null and return null.
Where are you actually setting the value of the one that the user picked?
i have two activity files in my code, and the first activity file loads the layout search, and the second file loads layout list. I have a textbox in layout search and enter some text. I want to use this text in my second activity file but i can not reach it since it is in the layout search. How can i do this? Here the first activity file, here there is an EditText item called searchedText, and i want to use it in the second activity file.
public class SearchActivity extends Activity{
public EditText searchedText;
public RadioGroup radioGroup;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
}
public void onStart(){
super.onStart();
searchedText = (EditText) findViewById(R.id.searchText);
Button searchinSearchButton = (Button)findViewById(R.id.searchInSearch);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
searchinSearchButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String searched=searchedText.getText().toString();
Intent myIntent = new Intent(v.getContext(),
SearchListActivity.class);
startActivityForResult(myIntent, 1);
}
});
}
}
And here is the second activity file:
public class SearchListActivity extends Activity{
public DatabaseAdapter db;
public ArrayList<String> myList;
public ListView listview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
db = new DatabaseAdapter(this);
myList = new ArrayList<String>();
getContacts();
// Example of retrieving tweets of the user "mashable" and adding them to
myList
/*
ArrayList<Tweet> tweets= new ArrayList<Tweet>();
tweets.addAll(Twitter.getTimeline("mashable", 10));
for(Tweet t: tweets){
myList.add(t.username + ": " + t.message + " Tweet id: "+ t.id);
}
*/
printList();
}
public void printList(){
listview = (ListView)findViewById(R.id.contactcListView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listview.setAdapter(adapter);
}
public void getContacts() {
db.open();
Cursor c = db.getContactbyName("y");
if (c.moveToFirst()) {
do {
DisplayContact(c);
} while (c.moveToNext());
}
db.close();
}
public void DisplayContact(Cursor c) {
String entry = "";
// if you add another attribute to your table, you need to change 3 into x
for (int i=1; i<5;i++){
entry += c.getString(i) + "\n";
}
myList.add(entry);
}
}
In this second activity file, you can see the getContacts() method. There, i search by Cursor c = db.getContactbyName("y"); but instead of "y", i want to search whatever user enters the texbox, whic is in the 1st activity file called searchedText. How can i do this?
Thanks
Send the text as an extra in your Intent when you start your second activity.
searchinSearchButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String searched=searchedText.getText().toString();
Intent myIntent = new Intent(v.getContext(),
SearchListActivity.class);
myIntent.putExtra("SEARCH_STRING",searched);
startActivityForResult(myIntent, 1);
}
});
And in your onCreate get the extra. You could use Intent.getStringExtra(String name)
In other words:
mySearched = getIntent().getStringExtra("SEARCH_STRING");
Just make sure to see if anything is null before using it.