Can somebody help me solve the database? - java

Hello everybody i m building an android application which has timepicker. what i want is that i want to update the database when user clicks the save button twice. Please guide me how to do that. Now my application crashes because no updation of database takes place.
TimeTable.java
public class Monday extends FragmentActivity implements TimePickerFragment.TimePickerDialogListener {
EditText et1, et2, et3;
TextView tvm;
LinearLayout llm;
int fhour, fmin, thour, tmin, j;
private int cnt = 0;
View vi[] = new View[100];
TimeTableDbHelper db;
String txt,fmeridien,tmeridien,ftime,ttime;
private static final int START_TIME_PICKER_ID = 1;
private static final int END_TIME_PICKER_ID = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_monday);
tvm = (TextView) findViewById(R.id.tvm);
llm = (LinearLayout) findViewById(R.id.llm);
db = new TimeTableDbHelper(this);
cnt = db.check("timetableM");
if (cnt > 0) {
int i;
for (i = 0; i < cnt; i++) {
LinearLayout mn = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, mn, false);
vi[i] = view;
mn.addView(view);
et1 = (EditText) vi[i].findViewById(R.id.txtTime);
et1.setText(db.rd1(i,1));
//Log.i("Monday", "Database read" + db.read(2) + db.read(3));
et2 = (EditText) vi[i].findViewById(R.id.txtTime2);
et2.setText(db.rd1(i,2));
//Log.i("Monday", "Database read" + db.read(4) + db.read(5));
et3 = (EditText) vi[i].findViewById(R.id.txtSet);
et3.setText(db.rd1(i,3));
}
j = i;
} else {
j = 0;
}
}
#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_monday, menu);
return true;
}
#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
return super.onOptionsItemSelected(item);
}
public void setTime(View v) {
LinearLayout main = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, main, false);
view.setTag(j);
main.addView(view);
vi[j] = view;
}
public void setTime2(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(START_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
public void setTime3(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(END_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
#Override
public void onTimeSet(int id, TimePicker view, int hourOfDay, int minute) {
Log.i("TimePicker", "Time picker set from id " + id + "!");
if (id == START_TIME_PICKER_ID) {
et1 = (EditText) vi[j].findViewById(R.id.txtTime);
fmin = minute;
if(hourOfDay <= 12) {
fhour = hourOfDay;
fmeridien = "AM";
} else {
fhour = hourOfDay-12;
fmeridien = "PM";
}
ftime =fhour + ":" + fmin + fmeridien;
et1.setText(ftime);
} else {
et2 = (EditText) vi[j].findViewById(R.id.txtTime2);
tmin = minute;
if(hourOfDay < 12) {
thour = hourOfDay;
tmeridien = "AM";
} else {
thour = hourOfDay-12;
tmeridien = "PM";
}
ttime = thour + ":" + tmin +tmeridien;
et2.setText(ttime);
}
}
public void Save(View v)
{
int position = (int) v.getTag();
if(position<j);
else {
et3 = (EditText) vi[j].findViewById(R.id.txtSet);
txt = et3.getText().toString();
Log.i("Position", "Value is " + position);
db.write1(j, ftime, ttime, txt);
Toast.makeText(this, "Successfully saved", Toast.LENGTH_LONG).show();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
int day = c.get(Calendar.DAY_OF_WEEK);
int value;
if(fmeridien=="AM") value=0;
else value=1;
c.set(Calendar.DAY_OF_WEEK,day);
c.set(Calendar.AM_PM, value);
c.set(Calendar.HOUR, fhour);
c.set(Calendar.MINUTE, fmin);
c.set(Calendar.SECOND,0);
Intent i = new Intent("com.example.annu.sheduler.DisplayNotification");
//---assign an ID of 1---
i.putExtra("NotifID", j);
i.putExtra("text",txt);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), j, i, 0);
j++;
//---sets the alarm to trigger---
alarmManager.set(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), displayIntent);}
}
}
activity_monday.xml
<LinearLayout android:id="#+id/llm"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.annu.sheduler.Monday"
android:background="#ffffa751"
android:label="Monday">
<TextView
android:id="#+id/tvm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setTime"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:text="Create a schedule"
android:textStyle="bold"
android:textSize="24sp"/>
</LinearLayout>
activity_timepicker.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txtTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="From"
android:onClick="setTime2"/>
<EditText
android:id="#+id/txtTime2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="To"
android:onClick="setTime3"/>
<EditText
android:id="#+id/txtSet"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".40"
android:hint="Description!!!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="Save"
android:minHeight="0dp"
android:minWidth="20dp"/>
</LinearLayout>
TimeTableDbHelper.java
public class TimeTableDbHelper extends SQLiteOpenHelper {
public static final String TABLE_NAMEM = "timetableM";
public static final String COLUMN_NO1 = "c_no1";
public static final String COLUMN_FROM_TIME1 = "FTIME1";
public static final String COLUMN_TO_TIME1 = "TTIME1";
public static final String COLUMN_DESC1 = "Description1";
private static final int DATABASE_VERSION = 1;
static final String DATABASE_NAME = "TimeTable.db";
public TimeTableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_TIME_TABLE1 = "CREATE TABLE " + TABLE_NAMEM + " (" +
COLUMN_NO1 + " INTEGER PRIMARY KEY, " +
COLUMN_FROM_TIME1 + " STRING NOT NULL," +
COLUMN_TO_TIME1 + " STRING NOT NULL," +
COLUMN_DESC1 + " TEXT NOT NULL" +
" );";
sqLiteDatabase.execSQL(SQL_CREATE_TIME_TABLE1);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAMEM);
onCreate(sqLiteDatabase);
}
public void write1(int column_no, String ftime, String ttime, String desc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NO1, column_no);
values.put(COLUMN_FROM_TIME1, ftime);
values.put(COLUMN_TO_TIME1, ttime);
values.put(COLUMN_DESC1, desc);
Boolean res = CheckIsDataAlreadyInDBorNot(TABLE_NAMEM, COLUMN_NO1, column_no);
if (res == false) db.insert(TABLE_NAMEM, null, values);
else db.update(TABLE_NAMEM, values, null, null);
db.close();
}
public int check(String tname) {
SQLiteDatabase db = this.getWritableDatabase();
String count = "SELECT count(*) FROM " + tname;
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
return icount;
}
public String rd1(int c_no, int col) {
String selectQuery = "SELECT * FROM " + TABLE_NAMEM + " WHERE " + COLUMN_NO1 + " = " + c_no;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String data = "";
if (cursor.moveToFirst()) {
// get the data into array,or class variable
do {
data = cursor.getString(col);
//Log.i("TimeTableDbHelper", "Value read " + cursor.getString(6));
} while (cursor.moveToNext());
}
db.close();
return data;
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, int fieldValue) {
SQLiteDatabase db = this.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = db.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
}

As stated here
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#update(java.lang.String,%20android.content.ContentValues,%20java.lang.String,%20java.lang.String[]):
Returns:
the number of rows affected
So you can do just:
if (db.update(TABLE_NAMEM, values, null, null) == 0)
db.insert(TABLE_NAMEM, null, values);
db.close();

Related

list view change item randomly

I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
public class MyAdapter extends BaseAdapter {
private String[] from;
ArrayList <HashMap<String, Object>> BuyList ;
private int[] to;
private Context context;
private ArrayList<HashMap<String, Object>> data ;
private ArrayList<HashMap<String, Object>> selecteddata;
private ArrayList<HashMap<String, Object>> fdata ;
private ImageView pay,more;
private EditText search;
private String user_mobile;
private TextView buy_toolbar_count;
private Holder holder;
// private HashMap<String, Object> hm;
public MyAdapter( Context context, ArrayList<HashMap<String, Object>> data,
ArrayList<HashMap<String, Object>> selecteddata , String[] from, int[] to, ArrayList Bylist,
ImageView pay, ImageView more, String user_mobile, TextView buy_count_toolbar, EditText search) {
this.data = data;
this.selecteddata = selecteddata;
this.fdata = new ArrayList<>(selecteddata);
this.context = context;
this.from = from;
this.to = to;
this.BuyList = Bylist;
this.pay = pay;
this.more = more;
this.search = search;
this.user_mobile = user_mobile;
this.buy_toolbar_count = buy_count_toolbar;
}
public void filter(String s, ImageView img) {
HashMap<String, Object> wp = new HashMap<>();
if (!s.equals("")) {
fdata.clear();
for (int i = 0 ;i<data.size();i++) {
wp = data.get(i);
// Log.i("mosi",wp.get("name").toString() + " wp ");
if (wp.get("name").toString().toLowerCase().contains(s)) {
fdata.add(wp);
}
}
}
else {
fdata = new ArrayList<>(selecteddata);
}
notifyDataSetChanged();
}
public class Holder
{
ImageView g_img;
ImageView plus;
ImageView mines;
TextView g_name;
TextView g_price;
TextView g_off;
TextView count;
TextView f_range;
TextView sum;
TextView temp2;
}
#Override
public int getCount() {
return fdata.size();
}
#Override
public HashMap<String, Object> getItem(int i) {
return fdata.get(i);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Typeface font_titr = Typeface.createFromAsset(context.getAssets(), "fonts/titr.TTF");
final HashMap<String, Object> hm = fdata.get(position);
if (convertView == null ) {
holder = new Holder();
convertView = LayoutInflater.from(context).
inflate(R.layout.my_row_layout2, parent, false);
holder.g_img = (ImageView) convertView.findViewById(R.id.f_img);
holder.g_name = (TextView) convertView.findViewById(R.id.f_name);
holder.g_price = (TextView) convertView.findViewById(R.id.f_price);
holder.g_off = (TextView) convertView.findViewById(R.id.f_off);
holder.count = (TextView) convertView.findViewById(R.id.f_count);
holder.f_range = (TextView) convertView.findViewById(R.id.f_kilo);
holder.plus = (ImageView) convertView.findViewById(R.id.plus_id_btn);
holder.mines = (ImageView) convertView.findViewById(R.id.mines_id_btn);
holder.sum = (TextView) convertView.findViewById(R.id.count_sum_id);
holder.temp2 = (TextView) convertView.findViewById(R.id.txt2);
//Date currentTime = Calendar.getInstance().getTime();
convertView.setTag(holder);
// Log.i("mosi",convertView.getTag() + " tagfffff " + hm.get("convertview"));
hm.put("convertview", "1");
}
else
{
holder = (Holder) convertView.getTag();
// Log.i("mosi",convertView.getTag() + " tag " + hm.get("convertview"));
}
final View tempview = convertView;
// set font++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
holder.g_price.setTypeface(font_titr, Typeface.NORMAL);
holder.g_name.setTypeface(font_titr, Typeface.BOLD);
holder.g_off.setTypeface(font_titr, Typeface.NORMAL);
holder.count.setTypeface(font_titr, Typeface.NORMAL);
holder.sum.setTypeface(font_titr, Typeface.NORMAL);
holder.temp2.setTypeface(font_titr, Typeface.NORMAL);
//----------------------------------------------------------------------------------------
// Set pre count and sum
holder.sum.setText(" میلغ کل : " + hm.get("sum").toString() + " تومان ");
holder.count.setText(hm.get("count").toString());
final String oldprice = hm.get("price").toString();
holder.g_off.setText(hm.get("off").toString());
holder.g_name.setText(hm.get("disc").toString());
holder.f_range.setText(hm.get("f_range").toString());
final float f=
(Float.valueOf(oldprice)*
Float.valueOf(holder.g_off.getText().toString()))/100;
// holder.g_price.setText(" قیمت : "+ DtoS((Float.valueOf(oldprice.toString()))-f)+" تومان ");
holder.g_price.setText(" قیمت : "+ oldprice +" تومان ");
File imageFile = new File(hm.get("image").toString());
if(imageFile.exists()){
holder.g_img.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
}
else
holder.g_img.setImageResource(R.drawable.coming_soon);
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
change_count(holder, hm, "p", tempview, ChangeType.DtoS((Float.valueOf(oldprice.toString())) - f), position);
}
});
holder.mines.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
change_count(holder, hm, "m", tempview , ChangeType.DtoS((Float.valueOf(oldprice.toString()))-f), position);
}
});
// Button Pay && More
pay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (BuyList.size() > 0) {
Intent intent = new Intent(context, Payment_act.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("data", BuyList);
intent.putExtra("all_data", data);
intent.putExtra("mobile", user_mobile);
view.getContext().startActivity(intent);
//
} else {
Toast.makeText(context, "سبد خرید شما خالی است", Toast.LENGTH_LONG).show();
}
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Choose_act.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("blist", BuyList);
intent.putExtra("data", data);
intent.putExtra("mobile", user_mobile);
view.getContext().startActivity(intent);
// ((Activity)context).finish();
}
});
// Search -------------------------------------------------------------------
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
// Log.i("mosi", s+" --- s ***");
// filter(s.toString(), holder.g_img);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return convertView;
}
// template
// Onclick for mines and plus Button
//#Override
public void change_count(final Holder holder1, HashMap<String, Object> hm_addtolist, String tag, View c_view, String oldprice, int position) {
// Log.i("mosi", position+" position on list ");
String is_pack = hm_addtolist.get("is_pack").toString();
ChangeType ch = new ChangeType();
double temp1 = 0;
double p_with_off = 0;
holder = (Holder) c_view.getTag();
String off = hm_addtolist.get("off").toString();
String num_sum = "0";
if (ch.stringToDouble(off)>0)
{
p_with_off = ch.stringToDouble(hm_addtolist.get("price_with_off").toString());
}
else
p_with_off = ch.stringToDouble(oldprice.toString());
holder.count= (TextView) c_view.findViewById(R.id.f_count);
holder.sum = (TextView) c_view.findViewById(R.id.count_sum_id);
if (!holder.count.getText().toString().equals("") && holder.count!= null)
temp1 = ch.stringToDouble(holder.count.getText().toString());
//my_alert("", temp1+"");
if (tag.equals("p")) {
if (is_pack.equals("1"))
temp1 = temp1 + 1;
else
temp1 = temp1 + 0.5;
// Log.i("mosi", " ::: set 2 !!!!");
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long)(temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else if (tag.equals("m")) {
if (is_pack.equals("1")) {
if (temp1 > 1) {
temp1 = (temp1 - 1);
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long) (temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else {
holder.count.setText("0");
holder.sum.setText("مبلغ کل : 0 تومان");
num_sum = "0";
BuyList.remove(hm_addtolist);
notifyDataSetChanged();
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
}
}
else {
if (temp1 > 0.5) {
temp1 = (temp1 - 0.5);
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long) (temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else {
holder.count.setText("0");
holder.sum.setText("مبلغ کل : 0 تومان");
num_sum = "0";
hm_addtolist.put("count","0");
hm_addtolist.put("sum","0");
BuyList.remove(hm_addtolist);
notifyDataSetChanged();
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
}
}
}
//}
if (!num_sum.equals("0")) {
hm_addtolist.put("sum", num_sum);
hm_addtolist.put("count", holder.count.getText().toString());
boolean check = false;
for (int i = 0; i < BuyList.size(); i++) {
if (BuyList.get(i).get("name").toString().equals(hm_addtolist.get("name").toString())) {
check = true;
HashMap<String, Object> temp_updatelist = BuyList.get(i);
temp_updatelist.put("sum", num_sum);
temp_updatelist.put("count", holder.count.getText().toString());
// BuyList.add(temp_updatelist);
// Log.i("mosi", "add count "+i+"");
// Toast.makeText(context, "ok", Toast.LENGTH_SHORT);
notifyDataSetChanged();
}
}
if (!check) {
// Log.i("mosi", "add count to :: "+hm_addtolist.get("name")+"");
BuyList.add(hm_addtolist);
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
notifyDataSetChanged();
}
}
notifyDataSetChanged();
// Log.i("mosi", BuyList.toString());
// clearbug( c_view);
}
}
make list on activity
I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
private void setlist() {
ArrayList<HashMap<String, Object>> selected_data = new ArrayList<>();
for (int i = 0; i < all_data.size(); i++) {
if (all_data.get(i).get("type").toString().equals(mtag)) {
HashMap<String, Object> t = all_data.get(i);
selected_data.add(t);
}
}
//Log.i("mosi",selected_data.toString());
EditText search = (EditText) findViewById(R.id.et_search_id);
ImageView pay = (ImageView) findViewById(R.id.btn_pay_firstpage);
ImageView more = (ImageView) findViewById(R.id.btn_more_firstpage);
String[] from = {"image", "name", "price", "off"};
int[] to = {R.id.f_img, R.id.f_name, R.id.f_price, R.id.f_off};
final MyAdapter adb = new MyAdapter(getBaseContext(), all_data, selected_data, from, to, BuyList, pay, more, user_mobile, buyCount_toolbar, search);
lv.setAdapter(adb);
}
I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
its my activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:background="#drawable/main_background_theme">
<include
android:id="#+id/mytoolbar"
layout="#layout/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"/>
<include
android:id="#+id/app_message"
layout="#layout/message"
android:layout_height="30dp"
android:layout_width="match_parent"
android:layout_below="#+id/mytoolbar"/>
<include
android:id="#+id/searchbox_id"
layout="#layout/searchbox"
android:layout_height="40sp"
android:layout_width="match_parent"
android:layout_below="#+id/app_message"
android:visibility="invisible"/>
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/searchbox_id"
android:id="#+id/FirstPage_id">
<RelativeLayout
android:id="#+id/rv_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainLayoutActivity">
<ListView
android:id="#+id/my_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/listDivader"
android:dividerHeight="1dp"
android:paddingBottom="?attr/actionBarSize" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignBottom="#id/my_listview"
android:background="#color/toolbar_back"
android:orientation="horizontal">
<ImageView
android:id="#+id/btn_pay_firstpage"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="50"
android:paddingLeft="10sp"
android:src="#drawable/btn_pay" />
<ImageView
android:id="#+id/btn_more_firstpage"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="50"
android:paddingLeft="10sp"
android:src="#drawable/btn_more" />
</LinearLayout>
</RelativeLayout>
<fragment
android:layout_width="180dp"
android:layout_height="match_parent"
android:id="#+id/drawer_fragment"
android:layout_gravity="start"
android:layout="#layout/drawer_fragment_layout"
tools:layout="#layout/drawer_fragment_layout"
android:name="com.com.seyedi89gmail.sm.zanco.Drawer_fragment">
</fragment>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
Remove notifyDataSetChanged from if-else conditions, May this will work
public void filter(String s, ImageView img) {
HashMap<String, Object> wp = new HashMap<>();
if (!s.equals("")) {
fdata.clear();
for (int i = 0 ;i<data.size();i++) {
wp = data.get(i);
if (wp.get("name").toString().toLowerCase().contains(s)) {
fdata.add(wp);
//notifyDataSetChanged();
}
}
}
else {
fdata = new ArrayList<>(selecteddata);
//notifyDataSetChanged();
}
notifyDataSetChanged();
}
you can use NestedScrollview outside the listview and stop the scrolling of listview by using this: smoothScrollBy(0, 0);

How to refresh ListView on data delete automaticaly

I want list view automatically update after deletion. I use adapter.notifyDataSetChanged() but it doesn't work for me
Here is my code
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Returns all the data from database
* #return
*/
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Delete from database
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
}
EditData
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private Button btnDelete;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
ActionBar actionBar=getSupportActionBar();
actionBar.hide();
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.4),(int)(height*.2));
btnDelete = (Button) findViewById(R.id.btnDelete);
mDatabaseHelper = new DatabaseHelper(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
toastMessage("removed from database");
adapter.notifyDataSetChanged();
}
});
}
/**
* customizable toast
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListData
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
static ArrayAdapter adapter;
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
public void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
EditText editField;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
mDatabaseHelper = new DatabaseHelper(this);
editField = (EditText) findViewById(R.id.editText);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editField.getText().toString().length() == 0) {
Toast.makeText(MainActivity.this, "Please Enter!", Toast.LENGTH_SHORT).show();
return;
}
String editText = editField.getText().toString();
AddData(editText);
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
And Layout are
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.tabian.saveanddisplaysql.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Enter any Thing"
android:layout_marginBottom="47dp"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="197dp"
android:orientation="horizontal"
android:id="#+id/linearLayout">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:text="Add" />
<Button
android:id="#+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/btnAdd"
android:text="View Data" />
</LinearLayout>
</RelativeLayout>
edit_data_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<Button
android:id="#+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="DELETE" />
</RelativeLayout>
list_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
After deletion instead of adapter.notifyDataSetChanged(); you can use the following code. It works fine for me:
adapter.remove(selectedName);

Display SQLite data in Android tablelayout

Im trying to retrieve data from SQLite database table and display as tablelayout in android. However it only display the title and the textview. What is wrong with the codes?
Graf.java
public class Graf extends AppCompatActivity {
DatabaseHelper myDb;
TextView dt, water, inc;
TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graf);
myDb=new DatabaseHelper(this);
dt=(TextView)findViewById(R.id.date);
water=(TextView)findViewById(R.id.water);
inc=(TextView)findViewById(R.id.inc);
tableLayout=(TableLayout)findViewById(R.id.tableLayout1);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final String date=getDate();
Toast.makeText(getApplicationContext(),date, Toast.LENGTH_SHORT).show();
BuildTable(date);
}
private void BuildTable(String date){
Cursor c=myDb.readEntry(date);
int rows=c.getCount();
int cols=c.getColumnCount();
c.moveToFirst();
for (int i=0;i<rows;i++){
TableRow row=new TableRow(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
for (int j=0;j<cols;j++){
TextView tv=new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tv.setBackgroundResource(R.drawable.cell_shape);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0,5,0,5);
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
tableLayout.addView(row);
}
}
/*public void getData(){
buttonA.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
showMessage("Ralat", "Tiada Rekod.");
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Tarikh : " + res.getString(1) + "\n");
buffer.append("Air Diminum : " + res.getString(2) + "\n");
buffer.append("Pencapaian : " + res.getString(3) + "\n\n");
showMessage("Laporan", buffer.toString());
}
}
});
}
public void showMessage(String title, String message){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}*/
#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_graf, menu);
return true;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
#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);
}
}
activity_graf.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context="info.androidhive.materialdesign.activity.Graf">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="45dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="LAPORAN MINGGUAN ANDA"
android:id="#+id/textView7"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tarikh" />
<TextView
android:id="#+id/water"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Penambahan Air" />
<TextView
android:id="#+id/inc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Peningkatan Peratus" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
</TableLayout>
</ScrollView>
</LinearLayout>
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper myDb;
SQLiteDatabase db = this.getWritableDatabase();
public static final String DATABASE_NAME = "HU.db";
public static final String TABLE_NAME = "User_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_4 = "GENDER";
public static final String COL_5 = "WEIGHT";
public static final String COL_6 = "HEIGHT";
public static final String COL_7 = "ACTIVENESS";
public static final String COL_8 = "TARGET";
public static final String TABLE2_NAME = "Drink_Table";
public static final String COL2_1 = "DRINK_ID";
public static final String COL2_2 = "DATE";
public static final String COL2_3 = "AMOUNT";
public static final String COL2_4 = "PERCENT";
public static final String COL2_5 = "ID";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, GENDER TEXT, WEIGHT DOUBLE, HEIGHT DOUBLE, ACTIVENESS INTEGER, TARGET DOUBLE)");
db.execSQL("create table " + TABLE2_NAME + " (DRINK_ID INTEGER PRIMARY KEY AUTOINCREMENT, DATE DATETIME DEFAULT CURRENT_DATE, AMOUNT DOUBLE, PERCENT DOUBLE, ID INTEGER, FOREIGN KEY(ID) REFERENCES " + TABLE_NAME + "(ID))");
db.execSQL("create table "+TABLE3_NAME+" (Entry_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , ID INTEGER, DATE DATETIME DEFAULT CURRENT_DATE, TOTALAMOUNT DOUBLE, TOTAL PERC DOUBLE, FOREIGN KEY(DATE) REFERENCES "+TABLE2_NAME+"(DATE), FOREIGN KEY(ID) REFERENCES "+TABLE_NAME+"(ID))");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String gender, String weight, String height, String activeness, String target) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_4, gender);
contentValues.put(COL_5, weight);
contentValues.put(COL_6, height);
contentValues.put(COL_7, activeness);
contentValues.put(COL_8, target);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean updateData(String id, String name, String gender, String weight, String height, String activeness, String target) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(COL_2, name);
contentValues.put(COL_4, gender);
contentValues.put(COL_5, weight);
contentValues.put(COL_6, height);
contentValues.put(COL_7, activeness);
contentValues.put(COL_8, target);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{id});
return true;
}
public boolean addWater(String date, String id, double amount) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
double target = getTargetu(id);
contentValues.put(COL2_2, date);
contentValues.put(COL2_3, amount);
contentValues.put(COL2_4, (amount / target) * 100);
contentValues.put(COL2_5, id);
long result = db.insert(TABLE2_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor readEntry(String date) {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = ("SELECT DATE, AMOUNT, PERCENT FROM "+TABLE2_NAME+"WHERE DATE= ?");
Cursor c = db.query(TABLE2_NAME,new String[]{COL2_2,COL2_3,COL2_4},COL2_2+"=?", new String[] { String.valueOf(date)}, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
I think the problem is with picking wrong layout params. Should be:
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
Table layout requires table Layout params.

How to create ListView with Custom Adapter and retrieve database in the listView?

I am trying to do a Timetable which a user have to select their subjects and their subjects will be displayed in another activity(ViewTimetable) by clicking the button (See Your Timetable).
After the user have selected his or her subjects, the user will see what have chosen in the same activity(ChooseSubject), and when they click "See Your Timetable", the subjects will be listed in ViewTimetable.java according to the days like "Mon, Tue, Wed, Thu, Fri".
If there is no subject on a day for example like Monday, "Monday" will not be shown.
But I have no idea how to retrieve the data from database into the ListView
Please help me! :(
ChooseSubject.java (How I get user's selection)
public class ChooseSubject extends ActionBarActivity {
ArrayList<String> subjects = new ArrayList<String>();
SQLiteDatabase db;
String[] dbSubject = {
"INSERT INTO `subjects` VALUES (1,'TPRG343','Introduction to Android Programming')",
"INSERT INTO `subjects` VALUES (2,'TNWK343(L)','Network Security(Lectural)')",
"INSERT INTO `subjects` VALUES (3,'TNWK224(L)','System Administration')",
"INSERT INTO `subjects` VALUES (4,'TWEB334','Advanced Web Design')",
"INSERT INTO `subjects` VALUES (5,'TWEB224','Web Programming')",
"INSERT INTO `subjects` VALUES (6,'TNWK343(T)','Network Security(Tutorial)')",
"INSERT INTO `subjects` VALUES (7,'TMMD233','Multimedia Presentation')",
"INSERT INTO `subjects` VALUES (8,'TMMD113','Computer Graphics Editing')"
};
String[] dbTimetable = {
"INSERT INTO `timetable` VALUES (1,'Monday','8.30am - 11.30am','KKL','B106')",
"INSERT INTO `timetable` VALUES (2,'Monday','12.30pm - 2.30pm','GBS','B103/B302')",
"INSERT INTO `timetable` VALUES (3,'Monday','3.00pm - 6.00pm','GBS','B103/B302')",
"INSERT INTO `timetable` VALUES (3,'Friday','4.30pm - 6.00pm','GBS','B103/B302')",
"INSERT INTO `timetable` VALUES (4,'Tuesday','12.00pm - 1.30pm','KKL','B106')",
"INSERT INTO `timetable` VALUES (4,'Thrusday','10.00am - 1.00pm','KKL','B101')",
"INSERT INTO `timetable` VALUES (5,'Tuesday','2.00pm - 4.30pm','YKC','B101')",
"INSERT INTO `timetable` VALUES (5,'Friday','12.00pm - 2.30pm','YKC','B101')",
"INSERT INTO `timetable` VALUES (6,'Tuesday','4.30pm - 6.00pm','GBS','B103/B207')",
"INSERT INTO `timetable` VALUES (7,'Wednesday','9.00am - 12.00pm','YKC','B101')",
"INSERT INTO `timetable` VALUES (8,'Thrusday','1.30pm - 4.30pm','Widura','B101')"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_subject);
db = openOrCreateDatabase("subjects", MODE_PRIVATE, null);
db.execSQL("Create table if not exists subjects (id integer primary key, subCode text, subName text)");
Cursor cursor = db.rawQuery("select * from subjects", null);
//Access for the first time,
if (cursor.getCount() == 0) {
for (int i = 0; i < dbSubject.length; i++) {
db.execSQL(dbSubject[i]);
}
}
db.execSQL("Create table if not exists timetable (id integer, day text, time text, lecturer text, class text)");
Cursor ttCursor = db.rawQuery("select * from timetable", null);
//Access for the first time,
if (ttCursor.getCount() == 0) {
for (int i = 0; i < dbTimetable.length; i++) {
db.execSQL(dbTimetable[i]);
}
}
String sId, sCode, sName;
String output = "";
Cursor spCursor = db.rawQuery("select * from subjects", null);
Toast.makeText(this, Integer.toString(spCursor.getCount()), Toast.LENGTH_SHORT).show();
if (spCursor.getCount() > 0) {
while (spCursor.moveToNext()) {
//output = spCursor.getString(spCursor.getColumnIndex("subCode")) + " \n" + spCursor.getString(spCursor.getColumnIndex("subName"));
output = spCursor.getString(spCursor.getColumnIndex("subName"));
subjects.add(output);
}
//
}
final LinearLayout rl = (LinearLayout) findViewById(R.id.rl);
Button btn = (Button) findViewById(R.id.btn);
Button btnTt = (Button)findViewById(R.id.seeTt);
final TextView tv = (TextView) findViewById(R.id.tv);
btnTt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChooseSubject.this,ViewTimetable.class);
startActivity(intent);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Build an AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(ChooseSubject.this);
final boolean[] checkedSubjects = new boolean[subjects.size()];
for(int i = 0 ; i < subjects.size(); i++){
checkedSubjects[i] = false;
}
// Convert the array to list
//final List<String> subjects = new ArrayList<String>();
String[] subjectsOutput = new String[subjects.size()];
subjectsOutput = subjects.toArray(subjectsOutput);
final ArrayList<String> selectedItem = new ArrayList<String>();
//final List<String> subjectList = Arrays.asList(subjects);
builder.setMultiChoiceItems(subjectsOutput, checkedSubjects, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// Update the current focused item's checked status
checkedSubjects[which] = isChecked;
if(isChecked){
selectedItem.add(String.valueOf(which));
db.execSQL("Create table if not exists UserSubject (subName text)");
String query = "insert into UserSubject values ('"+ selectedItem + "');";
db.execSQL(query);
}
else {
selectedItem.remove(String.valueOf(which));
}
// Get the current focused item
String currentItem = subjects.get(which);
// Notify the current action
Toast.makeText(getApplicationContext(),
currentItem + " " , Toast.LENGTH_SHORT).show();
}
});
// Specify the dialog is not cancelable
builder.setCancelable(false);
// Set a title for alert dialog
builder.setTitle("Choose your subjects");
// Set the positive/yes button click listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do something when click positive button
tv.setText("Your subjects are \n");
for (int i = 0; i < checkedSubjects.length; i++) {
boolean checked = checkedSubjects[i];
if (checked) {
tv.setText(tv.getText() + "\n" + subjects.get(i) + "\n");
}
}
}
});
// Set the neutral/cancel button click listener
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do something when click the neutral button
}
});
AlertDialog dialog = builder.create();
// Display the alert dialog on interface
dialog.show();
}
});
}
#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_choose_subject, menu);
return true;
}
#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);
}
}
ChooseSubject.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
>
<Button
android:id="#+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose your subjects"
/>
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/btn"
android:textSize="20dp"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="See Your Timetable"
android:id="#+id/seeTt"
android:layout_gravity="right" />
</LinearLayout>
ViewTabletable.java
import android.app.ActivityGroup;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import java.util.ArrayList;
public class ViewTimetable extends ActionBarActivity {
SQLiteDatabase db;
String id, subCode, subName, day, time, lecturer, myClass;
String outputTime, outputMon, outputTue, outputWed, outputThur, outputFri;
LinearLayout layout,box;
TextView tvTime,tvDetail;
ArrayList<String> MondaySubject = new ArrayList<String>();
ArrayList<String> TuesdaySubject = new ArrayList<String>();
ArrayList<String> WednesdaySubject = new ArrayList<String>();
ArrayList<String> ThrusdaySubject = new ArrayList<String>();
ArrayList<String> FridaySubject = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_timetable);
layout = (LinearLayout)findViewById(R.id.liLayout);
db = openOrCreateDatabase("subjects", MODE_PRIVATE, null);
Cursor cursor = db.rawQuery(
"select s.id, subCode, s.subName, day, time, lecturer, class" +
" from subjects s, timetable t, UserSubject us " +
"where s.id = t.id and us.subName = s.subName",null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
box = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL);
//box.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//layoutParams.setMargins(35, 10, 35, 10);
tvTime = new TextView(this);
tvTime.setGravity(Gravity.RIGHT);
tvDetail = new TextView(this);
//box.addView(tvDay);
box.addView(tvTime);
box.addView(tvDetail);
box.setLayoutParams(layoutParams);
layout.addView(box);
id = cursor.getString(cursor.getColumnIndex("id"));
subCode = cursor.getString(cursor.getColumnIndex("subCode"));
subName = cursor.getString(cursor.getColumnIndex("subName"));
day = cursor.getString(cursor.getColumnIndex("day"));
time = cursor.getString(cursor.getColumnIndex("time"));
lecturer = cursor.getString(cursor.getColumnIndex("lecturer"));
myClass = cursor.getString(cursor.getColumnIndex("class"));
if(day.equals("Monday")){
outputMon = cursor.getString(cursor.getColumnIndex("subCode")) + "\n" +
cursor.getString(cursor.getColumnIndex("subName")) + "\n" +
cursor.getString(cursor.getColumnIndex("class")) + "\n" +
cursor.getString(cursor.getColumnIndex("lecturer")) ;
outputTime = cursor.getString(cursor.getColumnIndex("time"));
tvTime.setText(outputTime);
tvDetail.setText(outputMon);
}
if(day.equals("Tuesday")){
outputTue = cursor.getString(cursor.getColumnIndex("subCode")) + "\n" +
cursor.getString(cursor.getColumnIndex("subName")) + "\n" +
cursor.getString(cursor.getColumnIndex("class")) + "\n" +
cursor.getString(cursor.getColumnIndex("lecturer")) ;
outputTime = cursor.getString(cursor.getColumnIndex("time"));
tvTime.setText(outputTime);
tvDetail.setText(outputTue);
}
if(day.equals("Wednesday")){
outputWed = cursor.getString(cursor.getColumnIndex("subCode")) + "\n" +
cursor.getString(cursor.getColumnIndex("subName")) + "\n" +
cursor.getString(cursor.getColumnIndex("class")) + "\n" +
cursor.getString(cursor.getColumnIndex("lecturer")) ;
outputTime = cursor.getString(cursor.getColumnIndex("time"));
tvTime.setText(outputTime);
tvDetail.setText(outputWed);
}
if(day.equals("Thursday")){
outputThur = cursor.getString(cursor.getColumnIndex("subCode")) + "\n" +
cursor.getString(cursor.getColumnIndex("subName")) + "\n" +
cursor.getString(cursor.getColumnIndex("class")) + "\n" +
cursor.getString(cursor.getColumnIndex("lecturer")) ;
outputTime = cursor.getString(cursor.getColumnIndex("time"));
tvTime.setText(outputTime);
tvDetail.setText(outputThur);
}
if(day.equals("Friday")){
outputFri = cursor.getString(cursor.getColumnIndex("subCode")) + "\n" +
cursor.getString(cursor.getColumnIndex("subName")) + "\n" +
cursor.getString(cursor.getColumnIndex("class")) + "\n" +
cursor.getString(cursor.getColumnIndex("lecturer")) ;
outputTime = cursor.getString(cursor.getColumnIndex("time"));
tvTime.setText(outputTime);
tvDetail.setText(outputFri);
}
}
}
}
}
activity_view_timetable.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/liLayout"
xmlns:android="http://schemas.android.com/apk/res/android">
</LinearLayout>

Android Database EditText NumberSigned

I made an android SQLDatabase with two edittext. One save the name and the other some number. This is my activity
public class AccountActivity extends ActionBarActivity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView name ;
TextView amount;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
name = (TextView) findViewById(R.id.input_name);
amount = (TextView) findViewById(R.id.input_amount);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if (Value > 0) {
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.ACCOUNT_COLUMN_NAME));
String amo = rs.getString(rs.getColumnIndex(DBHelper.ACCOUNT_COLUMN_AMOUNT));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.btn_save);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) nam);
name.setFocusable(false);
name.setClickable(false);
amount.setText((CharSequence) amo);
amount.setFocusable(false);
amount.setClickable(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.menu_account, menu);
}
else{
getMenuInflater().inflate(R.menu.menu_main, menu);
}
}
return true;
}
#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;
}
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.btn_save);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
amount.setEnabled(true);
amount.setFocusableInTouchMode(true);
amount.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteAccount)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteAccount(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view)
{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateAccount(id_To_Update, name.getText().toString(), amount.getText().length())){
Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else{
if(mydb.insertAccount(name.getText().toString(), amount.getText().length())){
}
else{
}
Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
startActivity(intent);
}
}
}
}
And this is my xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E0EEEE"
tools:context="com.tubapps.accountdb.AccountActivity">
<EditText
android:id="#+id/input_name"
android:layout_width="fill_parent"
android:inputType="text"
android:layout_height="wrap_content"
android:hint="#string/account_name"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip" />
<EditText
android:id="#+id/input_amount"
android:layout_width="fill_parent"
android:inputType="numberSigned"
android:layout_height="wrap_content"
android:hint="#string/initial_value"
android:layout_below="#+id/input_name"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:adjustViewBounds="true"
android:orientation="horizontal"
android:showDividers="middle">
<Button
android:id="#+id/btn_cnc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FFFFFF"
android:clickable="true"
android:focusable="true"
android:text="#string/cancel" />
<Button
android:id="#+id/btn_save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="run"
android:background="#FFFFFF"
android:text="#string/save_income" />
</LinearLayout>
</RelativeLayout>
And this is my DBHelper.
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String ACCOUNT_TABLE_NAME = "accounts";
public static final String ACCOUNT_COLUMN_ID = "id";
public static final String ACCOUNT_COLUMN_NAME = "name";
public static final String ACCOUNT_COLUMN_AMOUNT = "amount";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table accounts " +
"(id integer primary key, name text,amount integer)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS accounts");
onCreate(db);
}
public boolean insertAccount (String name, Integer amount)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("amount", amount);
db.insert("accounts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from accounts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, ACCOUNT_TABLE_NAME);
return numRows;
}
public boolean updateAccount (Integer id, String name, Integer amount)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("amount", amount);
db.update("accounts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteAccount (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("accounts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllAccounts()
{
ArrayList array_list = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from accounts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(ACCOUNT_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
When I insert a number it saves just the number 3. I don't know where is the problem.
You are getting the "length" of the number, not the value on these lines:
amount.getText().length()
I suspect you should be doing something like:
Integer.valueOf(amount.getText())

Categories