recyclerview sqlite database, data deleted on recyclerview but not deleting in database - sqlite

I want to delete both recyclerview and sqlite database, but the only recyclerview gets deleted.
When submitting a new record, the deleted records are visible.
Data is not deleted in the SQLite database.
How to delete data in SQLite database using recyclerview in android.
Here is my code.
AdapterClass
package com.example.recyclerviewsqlite;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHoder> {
private ArrayList<Model> modelArrayList;
private Context context;
DBmain dBmain;
public MyAdapter(ArrayList<Model> modelArrayList, Context context) {
this.modelArrayList = modelArrayList;
this.context = context;
}
#NonNull
#Override
public MyAdapter.ViewHoder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singledata, parent, false);
return new ViewHoder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.ViewHoder holder, int position) {
Model model = modelArrayList.get(position);
holder.txtname.setText(model.getSname());
holder.txtsub.setText(model.getSsubject());
//delete data
holder.txtimag.setOnClickListener(new View.OnClickListener() {
int newPosition = holder.getAdapterPosition();
#Override
public void onClick(View v) {
dBmain = new DBmain(context);
dBmain.delete(newPosition);
modelArrayList.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, modelArrayList.size());
}
});
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
public class ViewHoder extends RecyclerView.ViewHolder {
private TextView txtname, txtsub;
private ImageView icon, txtimag;
public ViewHoder(#NonNull View itemView) {
super(itemView);
txtname = (TextView) itemView.findViewById(R.id.txtname);
txtsub = (TextView) itemView.findViewById(R.id.txtsub);
icon = (ImageView) itemView.findViewById(R.id.icon);
txtimag = (ImageView) itemView.findViewById(R.id.txtimg);
}
}
}
Database Class
package com.example.recyclerviewsqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class SqliteHelper extends SQLiteOpenHelper {
public static final String DBNAME="student";
public static final String TABLENAME="college";
public static final int VER=1;
public SqliteHelper(#Nullable Context context) {
super(context, DBNAME, null, VER);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query="create table "+TABLENAME+"(id integer primary key, name text, subject text)";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query="drop table if exists "+TABLENAME+"";
db.execSQL(query);
}
public void delete(int id) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//deleting row
sqLiteDatabase.delete(TABLENAME, "id=" + id, null);
sqLiteDatabase.close();
}
}

for this check this soluion
public void remove(String Id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(PE.TABLE_NAME, PE.COLUMN_PLACE_ID + "=\"" + Id+"\"", null) ;
}
and call this method when u want to delete
private void delete(int position){
Dbhelper dbHelper = new Dbhelper(MainActivity.this);
dbHelper.removePlace(arraylist.get(position).getPlaceId());
arraylist.remove(position);
mAdapter.notifyDataSetChanged();
}

Related

I want to store my data in Realm database in Android Studio but it is not working

I want to store my data in realm but it is not working, it show me error when I click on save button where I add toast. There is no error found, but data is not saving.
My MainActivity Class
package com.deitel.realmrecyclerviewspinnerpriority;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import io.realm.Realm;
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
Realm realm;
EditText text_name;
EditText text_details;
Button btn_save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
realm=Realm.getDefaultInstance();
Realm.init(getApplicationContext());
text_name = findViewById(R.id.text_name);
text_details = findViewById(R.id.text_details);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savedata(text_name.getText().toString(),text_details.getText().toString());
}
});
}
private void savedata(final String name, final String datails){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgrealm) {
// Number maxid=bgrealm.where(ModelClass.class).max("id");
// int newkey=(maxid==null) ? 1 : maxid.intValue()+1;
ModelClass user = bgrealm.createObject(ModelClass.class);
user.setName(name);
user.setDetails(datails);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
Realm Class Where I initilize configutation etc.
package com.deitel.realmrecyclerviewspinnerpriority;
import android.app.Application;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration configuration=new RealmConfiguration.Builder().name("RealmData.realm").build();
Realm.setDefaultConfiguration(configuration);
}
}
Model Class.
package com.deitel.realmrecyclerviewspinnerpriority.Modelclass;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class ModelClass extends RealmObject {
#PrimaryKey
private String Name;
private String Details;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDetails() {
return Details;
}
public void setDetails(String details) {
Details = details;
}
}
I think you are not setting primary key,
Try below approach
private void savedata(final String name, final String datails){
try(Realm mRealm = Realm.getDefaultInstance()){
ModelClass user = new ModelClass();
int newkey=(maxid==null) ? 1 : maxid.intValue()+1;
user.setId(newkey);
user.setName(name);
user.setDetails(datails);
mRealm.executeTransaction(rlm-> {
rlm.insertOrUpdate(user);
});
}
}
insertOrUpdate inserts a new record if PK doesn't exists else update it.

OnClickListener in ListView updates a different item on the list

I have a ListView in my Fragment class. This ListView has three items, and every item in the ListView has two buttons, btn+ and btn-, and a TextView.
When I run the app and press the btn+ in the first item, I don't know why but the value of the TextView in the last item is incremented. When I click the btn-, again the value of the last TextView is decremented.
This is my adapter:
package com.example.lie_.tablayout;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import java.util.ArrayList;
/**
* Created by Ali on 17/08/2017.
*/
public class MenuListPizzaAdapter extends BaseAdapter {
View vv;
TextView txtOrderNUM;
int counter=0;
private ArrayList <BuyMenuListPizza> BuyMenuListPizza;
private Context C;
public MenuListPizzaAdapter(Context c, ArrayList<BuyMenuListPizza> BuyMenuListPizza) {
this.BuyMenuListPizza = BuyMenuListPizza;
this.C=c;
}
#Override
public int getCount() {
return BuyMenuListPizza.size();
}
#Override
public Object getItem(int i) {
return BuyMenuListPizza.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View View, ViewGroup parent)
{
if (View == null) {
View = LayoutInflater.from(C).inflate(R.layout.buy_menu_list_pizza, parent, false);
}
TextView txtitemname = (TextView)View.findViewById(R.id.txtitemname);
SimpleRatingBar ratingbar = (SimpleRatingBar)View.findViewById(R.id.ratingbar);
final TextView txtitemcontent = (TextView)View.findViewById(R.id.txtitemcontent);
ImageView btnOrderADD = (ImageView)View.findViewById(R.id.btnOrderADD);
ImageView btnOrderDEL = (ImageView)View.findViewById(R.id.btnOrderDEL);
ImageView imgitem = (ImageView)View.findViewById(R.id.imgitem);
txtitemname.setText(BuyMenuListPizza.get(position).getName());
ratingbar.setRating(BuyMenuListPizza.get(position).getRating());
txtitemcontent.setText(BuyMenuListPizza.get(position).getContents());
btnOrderADD.setImageResource(BuyMenuListPizza.get(position).getImgplus());
btnOrderDEL.setImageResource(BuyMenuListPizza.get(position).getImgminues());
imgitem.setImageResource(BuyMenuListPizza.get(position).getImgpizza());
Toast.makeText(parent.getContext(),"Position getView : " + position,Toast.LENGTH_LONG).show();
txtOrderNUM = (TextView)View.findViewById(R.id.txtOrderNUM);
txtOrderNUM.setText(BuyMenuListPizza.get(position).getCount() + "");
btnOrderADD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int coun= BuyMenuListPizza.get(position).getCount();
coun++;
txtOrderNUM.setText( coun+"");
}
});
btnOrderDEL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int coun= BuyMenuListPizza.get(position).getCount();
coun--;
if(coun<0){
}
else
txtOrderNUM.setText(coun+"");
}
});
return View;
}
}
This is my Fragment class :
public class Pizza extends Fragment {
TextView txtOrderNUM;
ArrayList<BuyMenuListPizza> arrayList;
ListView MenuPizzaList;
Context c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.pizza, container, false);
MenuPizzaList = ( ListView)android.findViewById(R.id.MenuPizzaList);
arrayList=BuyMenuListPizzaCollection.getBuyMenuListPizza();
MenuPizzaList.setAdapter(new MenuListPizzaAdapter(container.getContext(),arrayList));
// MenuPizzaList.setOnItemClickListener(new oncitemlicklistener());
return android;
}
Please don't say go to xml file and change attribute because I changed that and my code is running and OnClickListener is ok but it doesn't work correctly.
I have searched for more than several days and I didn't find anything.
i found problem solving use : notyficationitemselected(getadapterposition)

SharedPreferences within a fragment

Once the user selects an item from a list in another fragment it brings you to this fragment. And I'm having issues trying to save the users rating that was selected. when the user goes back it should be the same rating that was previously selected.
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.Arrays;
public class infoFragment extends Fragment {
TextView degrees;
ImageView image;
String stringtext;
String [] hold;
private RatingBar rating;
SharedPreferences wmbPreference1;
SharedPreferences.Editor editor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.info_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
image = (ImageView) view.findViewById(R.id.imageView);
why can i not use "this"
rating =((RatingBar) view.findViewById(R.id.ratingBar)).setOnRatingBarChangeListener(this);
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
degrees =(TextView)view.findViewById(R.id.textView);
}
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
final int numStars = ratingBar.getNumStars();
editor = wmbPreference1.edit();
editor.putInt("numStars", numStars);
editor.commit();
int ratings = wmbPreference1.getInt("numStars", 0);
}
public void setText(final String string) {
Character[] hold;
if(string == "apple"){
String[] word = { " A \n", "B\n" };
degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
image.setImageResource(R.drawable.APPLE);
}
Should I call onRatingChanged within the conditional statement for it to save?
if(string == "orange"){
String[] word = { " AA\n", "AB\n" };
degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
image.setImageResource(R.drawable.bruce);
}
}
public void sentText(){
new MyTask().execute();
}
private class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
Bundle b = getArguments();
stringtext = b.getString("text");
return null;
}
protected void onPostExecute(String result){setText(stringtext);
}
}
}
Your Fragment should implement OnRatingBarChangeListener:
public class infoFragment extends Fragment implements OnRatingBarChangeListener
The other thing is that setOnRatingChangeListener does not return a value, so you can't assign the return value to rating as you did.
You should do:
rating = (RatingBar) view.findViewById(R.id.ratingBar);
rating.setOnRatingBarChangeListener(this);

Android Flipboard App animation

I'm Implementing Flipboard Animation in my activity pageIndicatorActivity its showing an error i.e The method Page(NoteViewAdapter) in the type FlipViewController is not applicable for the arguments
(PageIndicatorActivity.NoteViewAdapter)
this is the error I'm facing
here is my code
package com.horizontalscrollviewwithpageindicator;
import java.util.ArrayList;
import com.aphidmobile.flip.FlipViewController;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class PageIndicatorActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
ArrayList<String> notes = new ArrayList<String>();
notes.add("Come");
notes.add("On");
notes.add("Flip");
notes.add("Me");
//You can also use FlipViewController.VERTICAL
FlipViewController flipView = new FlipViewController(this, FlipViewController.HORIZONTAL);
//We're creating a NoteViewAdapter instance, by passing in the current context and the
//values to display after each flip
flipView.Page(new NoteViewAdapter(this, notes));
setContentView(flipView);
}
public abstract class NoteViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<String> notes;
public NoteViewAdapter(Context currentContext, ArrayList<String> allNotes) {
inflater = LayoutInflater.from(currentContext);
notes = allNotes;
}
#Override
public int getCount() {
return notes.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View layout = convertView;
if (convertView == null) {
layout = inflater.inflate(R.layout.activity_main, null);
}
//Get's value from our ArrayList by the position
String note = notes.get(position);
TextView tView = (TextView) layout.findViewById(R.id.note);
tView.setText(note);
return layout;
}
}
private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
R.drawable.antartica3, R.drawable.antartica4,
R.drawable.antartica5, R.drawable.antartica6,
R.drawable.antartica7, R.drawable.antartica8 };
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Where I can find example of SQLite database file or dump of it? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I really need a sqlite database file for studies.
I'm creating an application in C# and I need a database with many tables, field, views, indexes, constraints and so on. And I don't want to create it myself using sqlite command line tool.
So I suppose may be someone can say where I can find such file, may be different applications or examples, or even can send me their own database file. I will appreciate any help.
There is a nice sample database called Chinook. It's trying to be the modern example to replace NorthWind. They have versions for different database servers including SQLite.
Homepage, DB diagram, etc.. http://chinookdatabase.codeplex.com/
Github (seems more updated than CodePlex) https://github.com/lerocha/chinook-database
Latest SQLite download to date of post: https://chinookdatabase.codeplex.com/releases/view/55681#fileDownload6
Download SQLite Sample Database to get the Chinook database file directly http://www.sqlitetutorial.net/sqlite-sample-database/
More SQLite related projects and samples on CodePlex http://www.codeplex.com/site/search?query=sqlite&ac=8
Also, check this sample in the SQLite .NET client forums (attached to first post)
Getting the Microsoft EFQuerySamples project to work with SQLite
Maybe a GUI tool to create database stuff will make starting easier, check this one, free for personal use
http://www.sqliteexpert.com/
Personally, I create SQLite databases for testing NHibernate mappings. Usually I create my classes and mappings then use the mappings to generate schema to a new SQLite file (or in memory database, more often) and use that. Most NHibernate introduction articles do that as well.
SQLite is whidely used by many applications so I am pretty sure very lot examples can be found on your computer. For example, on my Win10 PC if I search in "c:\Users\Konstantin" (my profile) for files with:
file name mask: *.sqlite;*.db
text inside: SQLite format 3
I am currently getting 785 results. Most of them, which have that text in the beginning - it is 99% SQLite database files. Particularly I see that it is used by skype, viber, dropbox, office and firefox.
I used sqlightCrud operation
First creat database class.
package com.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
public class DataBaseSampleActivity {
/** for database */
static final String DataBaseName = "EmployeDB";
/** for employee table */
static final String EmployeTable = "Employees";
static final String ColEmpID = "EmpId";
static final String ColEmpName = "EmpName";
static final String ColEmpAge = "EmpAge";
static final String ColDept = "Dept";
/** for department table */
static final String DeptTable = "Department";
static final String ColDeptID = "DeptId";
static final String ColDeptName = "DeptName";
public static final int DATABASE_VERSION = 2;
//private static final String KEY_ROWID = "_id";
private static final String EMPLOYEE_TABLE_CREATE ="Create table " + EmployeTable +
//"(_id INTEGER UNIQUE," + [old code]
"("+ColEmpID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
ColEmpName + " VARCHAR(15) ," +
ColEmpAge + " INT(15) ," +
ColDept + " VARCHAR(15)) ";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DataBaseSampleActivity(Context ctx){
Log.i("test****", "**test***");
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context){
super(context, DataBaseName , null, DATABASE_VERSION);
Log.i("context","context");
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(EMPLOYEE_TABLE_CREATE);
Log.i("************", "table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("tag", "Upgrading database from version " + oldVersion + " to "+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + EmployeTable);
onCreate(db);
}
};
public DataBaseSampleActivity open() throws SQLException{
db = DBHelper.getWritableDatabase();
Log.i("open", "message");
return this;
}
public void close(){
DBHelper.close();
}
//public long insert(Integer empid, String empname, Integer empage, String empdept) {
public long insert(String empname, Integer empage, String empdept) {
Log.i("**** suruchitest **** ","*** test ***");
ContentValues initialValues = new ContentValues();
//initialValues.put(ColEmpID, empid);
initialValues.put(ColEmpName, empname);
initialValues.put(ColEmpAge, empage);
initialValues.put(ColDept, empdept);
return db.insert(EmployeTable, null, initialValues);
}
public Cursor getEmpValues(){
Cursor mCursor = db.query(EmployeTable, null, null, null, null, null, null);
return mCursor;
}
public boolean deleteEmpList(long rowId){
Toast.makeText(context, "deleted", 2000).show();
return db.delete(EmployeTable, ColEmpID +" = " + rowId, null) > 0;
}
public boolean updateEmplist(String empname, Integer empage, String empdept, Integer rowid){
ContentValues initialValues = new ContentValues();
Log.i("##### "+rowid,""+empname+" "+empage+" "+empdept);
//initialValues.put(ColEmpID, rowid);
initialValues.put(ColEmpName,empname);
initialValues.put(ColEmpAge,empage);
initialValues.put(ColDept,empdept);
try{
int b = db.update(EmployeTable, initialValues, ColEmpID+ " = " + rowid, null);
Log.i("update", "up "+rowid+" ddd "+b);
return true;
}catch (Exception e){
Log.d("asdfasdfsadfasdf", "_--___--__--_=-_");
return false;
}
}
}
2. create Main Activity
package com.db;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button buttonsubmit;
EditText empid,empname,empage,empdept;
String emp_name, emp_dept;
//Integer emp_id,emp_age;
Integer emp_age;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonsubmit = (Button) findViewById(R.id.btnSubmit);
buttonsubmit.setOnClickListener(this);
// empid =(EditText) findViewById(R.id.empid);
empname =(EditText) findViewById(R.id.empname);
empage =(EditText) findViewById(R.id.empage);
empdept =(EditText) findViewById(R.id.empdpt);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBaseSampleActivity dbObj = new DataBaseSampleActivity(getApplicationContext());
// String Emp_ids = empid.getText().toString();
// emp_id = Integer.parseInt(Emp_ids);
//emp_id = empid.getText().toString();
String Emp_ages = empage.getText().toString();
emp_age = Integer.parseInt(Emp_ages);
//emp_age = empage.getText().toString();
emp_name = empname.getText().toString();
emp_dept = empdept.getText().toString();
try {
Log.i("try", "message");
dbObj.open();
//long temp = dbObj.insert(emp_id, emp_name, emp_age, emp_dept);
long temp = dbObj.insert(emp_name, emp_age, emp_dept);
//Toast.makeText(getApplicationContext(), "temp"+temp, 3000).show();
dbObj.close();
Intent intent = new Intent(this,ShowListView.class);
startActivity(intent);
} catch (Exception e) {
// TODO: handle exception
Log.i("catch", "message");
}
}
}
2. Create listclass to show tha data
package com.db;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ShowListView extends Activity {
ArrayList<String> arrname = new ArrayList<String>();
ArrayList<String> arrage = new ArrayList<String>();
ArrayList<String> arrdept = new ArrayList<String>();
ArrayList<Integer> arrRowId = new ArrayList<Integer>();
ArrayList<Integer> arrDelId = new ArrayList<Integer>();
Array[] arr;
Button deleteBtn;
Button btnadd;
int index = 0;
public int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emplist);
//Toast.makeText(getApplicationContext(), "LIST VIEW", 5000).show();
ToGetCursorValues();
}
public void ToGetCursorValues(){
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
try {
Cursor cur = db.getEmpValues();
cur.moveToFirst();
arrRowId.clear();
arrname.clear();
arrage.clear();
arrdept.clear();
while (!cur.isAfterLast()) {
arrRowId.add(cur.getInt(cur.getColumnIndex(db.ColEmpID)));
arrname.add(cur.getString(cur.getColumnIndex(db.ColEmpName)));
arrage.add(cur.getString(cur.getColumnIndex(db.ColEmpAge)));
arrdept.add(cur.getString(cur.getColumnIndex(db.ColDept)));
cur.moveToNext();
}
//Log.i("#####","col "+arrlist.size());
//Toast.makeText(getApplicationContext(), "* "+arrname.size()+","+arrage.size()+","+arrdept.size(), 5000).show();
//Toast.makeText(getApplicationContext(), "***** "+arrRowId.get(0), 2000).show();
} catch (Exception e) {
// TODO: handle exception
}
ListView lst = (ListView) findViewById(R.id.mylist);
lst.setAdapter(new ListAdapter(getApplicationContext()));
db.close();
}
public class ListAdapter extends BaseAdapter implements OnCheckedChangeListener,OnClickListener{
private LayoutInflater inflater = null;
public ListAdapter(Context c){
Log.i("Context","Context");
inflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//return 0;
return arrname.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder{
TextView empnameview;
TextView empageview;
TextView empdeptview;
CheckBox empchkbox;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i("*view","view*");
ViewHolder vh;
//ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
Log.i("*null1*","*null1*");
vh = new ViewHolder();
convertView = inflater.inflate(R.layout.customlist, null);
Log.i("*null2*","*null2*");
pos = position;
vh.empnameview = (TextView) convertView.findViewById(R.id.ename);
vh.empageview = (TextView) convertView.findViewById(R.id.eage);
vh.empdeptview = (TextView) convertView.findViewById(R.id.edept);
vh.empchkbox = (CheckBox) convertView.findViewById(R.id.ckekDelete);
Log.i("*null3*","*null3*");
vh.empnameview.setText(arrname.get(position));
vh.empnameview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(ShowListView.this,UpdateDB.class);
String name = arrname.get(position);
int age = Integer.parseInt(arrage.get(position));
String dept = arrdept.get(position);
int rowid = arrRowId.get(position);
intent.putExtra("KeyName" , name);
intent.putExtra("Keyage" , age);
intent.putExtra("Keydept" , dept);
intent.putExtra("Rowid", rowid);
startActivity(intent);
}
});
vh.empageview.setText(arrage.get(position));
vh.empdeptview.setText(arrdept.get(position));
vh.empchkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "OnChecked"+position, 2000).show();
if(buttonView.isChecked()){
arrDelId.add(arrRowId.get(position));
//Toast.makeText(getApplicationContext(), "OnChecked"+position, 2000).show();
// DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
// db.open();
// db.deleteEmpList(arrRowId.get(position));
// Toast.makeText(getApplicationContext(), "delet", 3000).show();
// db.close();
//
}
else{
for(int i=0;i<arrDelId.size();i++){
if(arrRowId.get(position) == arrDelId.get(i)){
arrDelId.remove(i);
}
}
}
}
});
Log.i("******", "complete");
} else {
Log.i("*not*","*not*");
vh = (ViewHolder) convertView.getTag();
}
deleteBtn = (Button) findViewById(R.id.delBtn);
deleteBtn.setOnClickListener(this);
btnadd = (Button) findViewById(R.id.addBtn);
btnadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent inte = new Intent(ShowListView.this, MainActivity.class);
startActivity(inte);
}
});
// imageView.setImageResource(thumbarr[position]);
return convertView;
}
public View getView1(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i=0;i<arrDelId.size();i++){
//Toast.makeText(getApplicationContext(), "OnDeleteClick "+i, 2000).show();
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
db.deleteEmpList(arrDelId.get(i));
//Toast.makeText(getApplicationContext(), "delet", 3000).show();
db.close();
}
ToGetCursorValues();
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
}
}
}
3. for update
package com.db;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateDB extends Activity implements OnClickListener{
Intent intnt;
EditText editname,editage,editdept;
Button updateBtn;
int row_id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editname = (EditText) findViewById(R.id.empname);
editage = (EditText) findViewById(R.id.empage);
editdept = (EditText) findViewById(R.id.empdpt);
updateBtn = (Button) findViewById(R.id.btnSubmit);
updateBtn.setText("Update");
intnt = getIntent();
editname.setText(intnt.getStringExtra("KeyName"));
editage.setText(""+intnt.getIntExtra("Keyage",0));
editdept.setText(intnt.getStringExtra("Keydept"));
row_id = intnt.getIntExtra("Rowid", 0);
updateBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "update", 3000).show();
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
String empname = editname.getText().toString();
int empage = Integer.parseInt(editage.getText().toString());
String empdept = editdept.getText().toString();
//db.deleteEmpList(row_id);
db.updateEmplist(empname, empage, empdept,row_id);
//Toast.makeText(getApplicationContext(), "delet", 3000).show();
db.close();
Intent list = new Intent(UpdateDB.this,ShowListView.class);
startActivity(list);
}
});
// Toast.makeText(getApplicationContext(), "update "+intnt.getIntExtra("Keyage",0), 3000).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}

Resources