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);
}
Related
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'm stuck for few days, and unfortunately dont know how to fix it.
I have DetailScreen.java that show data from MainScreen (one of recyclerview's list).
I tried this code but there is no effect, when i try to change use
COLUMN_NOMOR in my update function, i can change the name but
getting error when change the nomor. I guess, its right to use
COLUMN_ID in my update function because id is my PK-AI. So whether
because I didnt call COLUMN_ID in my DetailScreen? But how i can call my
id in my DetailsScreen also in my UpdateScreen?
If the data success updated, the screen will be automatically go to the DetailScreen again, but still showing old data. I had to go to MainActivity first to get the new data. Where code should i modified?
Here my Update function in my DBHandler.java
public int updateDataSiswa(Siswa siswa) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NOMOR, siswa.getNomor());
values.put(COLUMN_NAMA, siswa.getNama());
return db.update(TABLE_SISWA, values, COLUMN_ID + " = ?",
new String[]{String.valueOf(siswa.getId())});
}
Here DetailScreen.java
public class DetailScreen extends AppCompatActivity {
private TextView txt_resultnomor, txt_resultnama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_details);
//put data
Intent i = getIntent();
final String id = i.getExtras().getString("id");
final String nomor = i.getExtras().getString("nomor");
final String nama = i.getExtras().getString("nama");
//inisialisasi
txt_resultnomor = (TextView) findViewById(R.id.txt_resultnomor);
txt_resultnama = (TextView) findViewById(R.id.txt_resultnama);
//set
txt_resultnomor.setText(nomor);
txt_resultnama.setText(nama);
}
#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_detail, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_edit) {
Intent in = new Intent(this, UpdateScreen.class);
in.putExtra("nomor", txt_resultnomor.getText().toString());
in.putExtra("nama", txt_resultnama.getText().toString());
startActivity(in);
}
if (id == R.id.action_delete) {
return true;
}
if (id == R.id.action_settings) {
// Intent i = new Intent(this, About.class);
//startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Then here my UpdateScreen.java
public class UpdateScreen extends AppCompatActivity {
private EditText et_nomor;
private EditText et_nama;
private Button button_updatedata;
private DBHandler dbHandler;
private SiswaAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_screen);
dbHandler = new DBHandler(this);
initComponents();
}
private void initComponents(){
et_nomor = (EditText) findViewById(R.id.et_nomor);
et_nama = (EditText) findViewById(R.id.et_nama);
//ambil data
Intent in=getIntent();
final String id=in.getExtras().getString("id_siswa");
final String nomor=in.getExtras().getString("nomor");
final String nama=in.getExtras().getString("nama");
//set inisial
et_nomor.setText(nomor);
et_nama.setText(nama);
button_updatedata = (Button) findViewById(R.id.button_updatedata);
button_updatedata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validasiForm();
}
});
}
private void validasiForm() {
String form_nomor = et_nomor.getText().toString();
String form_nama = et_nama.getText().toString();
if (form_nomor.isEmpty()){
et_nomor.setError("Nomor belum diisi");
et_nomor.requestFocus();
}
else if (form_nama.isEmpty()){
et_nama.setError("Nama belum diisi");
et_nama.requestFocus();
}
else {
dbHandler.updateDataSiswa(new Siswa(form_nomor, form_nama));
List<Siswa> siswaList = dbHandler.getSemuaSiswa();
adapter = new SiswaAdapter(siswaList);
adapter.notifyDataSetChanged();
Toast.makeText(UpdateScreen.this, "Berhasil Memperbarui Data Siswa", Toast.LENGTH_SHORT).show();
MainSiswaActivity.mma.refresh();
finish();
}
}
}
I hope i tell clearly, help me please. Thanks.
where is your call to the update method you given public int updateDataSiswa(Siswa siswa)..? Also based on what you have provided...your notifyDataSetChanged() for adapter just tries to update the listview of the RecyclerView..
but it does not understand what underlying data has changed for it..you need to create a method for your Database Handler where you can fetch a List of new records..and then use this method to update your adapter with it and then set the new adapter to your listView in validasiForm() method..
please check this for more details...Android ListView not refreshing after notifyDataSetChanged
i try using SQLite in Fragment. But always error. I know that my syntax isn't great and I should be saving from a Party object instead of straight from the fragment interface, but my focus is really on the the process. Any help would be super helpful! Here my code. I try using getActivity() but not work.
public class DataHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "biodatadiri.db";
private static final int DATABASE_VERSION = 1;
public DataHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "create table biodata(no integer primary key, nama text null, tgl text null, jk text null, alamat text null);";
Log.d("Data", "onCreate: " + sql);
db.execSQL(sql);
sql = "INSERT INTO biodata (no, nama, tgl, jk, alamat) VALUES ('1001', 'Fathur', '1994-02-03', 'Laki-laki','Jakarta');";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
And here is the interface screen:
public class UserFragment extends Fragment {
String[] daftar;
ListView ListView01;
Menu menu;
protected Cursor cursor;
DataHelper dbcenter;
public static UserFragment ma;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_fragment);
Button btn=(Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inte = new Intent(UserFragment.this, BuatBiodata.class);
startActivity(inte);
}
});
ma = this;
dbcenter = new DataHelper(this);
RefreshList();
}
public void RefreshList(){
SQLiteDatabase db = dbcenter.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM biodata",null);
daftar = new String[cursor.getCount()];
cursor.moveToFirst();
for (int cc=0; cc < cursor.getCount(); cc++){
cursor.moveToPosition(cc);
daftar[cc] = cursor.getString(1).toString();
}
ListView01 = (ListView)findViewById(R.id.listView1);
ListView01.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, daftar));
ListView01.setSelected(true);
ListView01.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
final String selection = daftar[arg2]; //.getItemAtPosition(arg2).toString();
final CharSequence[] dialogitem = {"Lihat Biodata", "Update Biodata", "Hapus Biodata"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserFragment.this);
builder.setTitle("Pilihan");
builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0 :
Intent i = new Intent(getApplicationContext(), LihatBiodata.class);
i.putExtra("nama", selection);
startActivity(i);
break;
case 1 :
Intent in = new Intent(getApplicationContext(), UpdateBiodata.class);
in.putExtra("nama", selection);
startActivity(in);
break;
case 2 :
SQLiteDatabase db = dbcenter.getWritableDatabase();
db.execSQL("delete from biodata where nama = '"+selection+"'");
RefreshList();
break;
}
}
});
builder.create().show();
}});
((ArrayAdapter)ListView01.getAdapter()).notifyDataSetInvalidated();
}
#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_main, menu);
return true;
}
Here is error from Android Studio.
Error:(81, 25) error: method updateDisplay in class MainMenu cannot be applied to given types;
required: Fragment
found: UserFragment
reason: actual argument UserFragment cannot be converted to Fragment by method invocation conversion
I use case in MainMenu.java
case R.id.navigation_item_user:
updateDisplay(new UserFragment());
break;
Anyone? Thank you for your help :) Sorry for bad english
setContentView(R.layout.user_fragment); // this call should be made only activity.
In Fragments you need to override onCreateView method to setup view. In this return the view that you show it in fragment
Best explained here
fragments with transactions
usage
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});
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);