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();
}
I have got an error about no such talbe: Account while I am calling data from database.
My database name is "account.db" and table name is "Account". There are two columns, first is "name" and second is "email".
I am writing in kotlin language. Please look at below for my DBHelper and DBManager.
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.Build
import android.widget.Toast
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
import java.util.ArrayList
class DbManager {
var DB_PATH = ""
var DB_NAME = "account.db"
val dbVersion = 1
//CREATE TABLE IF NOT EXISTS MyNotes (ID INTEGER PRIMARY KEY,title TEXT, Description TEXT);"
// val sqlCreateTable = "CREATE TABLE IF NOT EXISTS " + dbTable + " (" + colID + " INTEGER PRIMARY KEY," +
// colTitle + " TEXT, " + colDes + " TEXT);"
var sqlDB: SQLiteDatabase? = null
constructor(context: Context) {
var db = DBHelper(context)
sqlDB = db.writableDatabase
}
inner class DBHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, dbVersion) {
var mDatabase: SQLiteDatabase? = null
var mContext: Context? = null
//Todo: Get All Data users
fun getAllUsers(): List<Account>?{
val temp = ArrayList<Account>()
val db = writableDatabase
var c: Cursor?
try {
c = db.rawQuery("SELECT * FROM Account ", null)
if (c == null) return null
c.moveToFirst()
do {
val account = Account(c.getString(c.getColumnIndex("name")), c.getString(c.getColumnIndex("email")))
temp.add(account)
} while (c.moveToNext())
c.close()
} catch (e: Exception) {
}
db.close()
return temp
}
fun createDataBase() {
//Todo: Create Database
val isDBExist = checkDataBase()
if (isDBExist) { } else {
this.readableDatabase
try {
copyDataBase()
Toast.makeText(this.mContext, "Copy has been finished.", Toast.LENGTH_SHORT).show()
} catch (ex: Exception) {
}
}
}
init {
if (Build.VERSION.SDK_INT > 17) {
DB_PATH = context.applicationInfo.dataDir + "/databases/"
} else {
DB_PATH = "/data/data/" + context.packageName + "/databases/"
}
this.mContext = mContext
}
override fun close() {
if (mDatabase != null)
mDatabase!!.close()
super.close()
}
fun checkDataBase(): Boolean {
//Todo: Check Database
var tempDB: SQLiteDatabase? = null
try {
val path = DB_PATH + DB_NAME
tempDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY)
} catch (ex: Exception) {
}
if (tempDB != null)
tempDB.close()
return if (tempDB != null) true else false
}
fun copyDataBase() {
//Todo:Copy Database
try {
val myInput = mContext!!.assets.open(DB_NAME)
val outputFileName = DB_PATH + DB_NAME
val myOutput = FileOutputStream(outputFileName)
val buffer = ByteArray(1024)
var length: Int
length= myInput.read(buffer)
while (length > 0) {
myOutput.write(buffer, 0, length)
}
myOutput.flush()
myOutput.close()
myInput.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
fun openDataBase() {
//Todo: Open Database
val path = DB_PATH + DB_NAME
mDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE)
}
override fun onCreate(db: SQLiteDatabase) {
createDataBase()
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if(oldVersion>=newVersion){
copyDataBase()
}
}
// companion object {
// var DB_PATH = ""
// var DB_NAME = "account.db"
// }
}
}
Here is my MainActivity.kt
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.row.*
import kotlinx.android.synthetic.main.row.view.*
import java.util.ArrayList
class MainActivity : AppCompatActivity() {
var lstUsers=ArrayList<Account>()
lateinit var dbHelper: DBHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dbHelper = DBHelper(applicationContext)
dbHelper.createDataBase()
}
fun buGetData(v: View){
//Todo: Load Data from db set to listview
LoadData()
}
fun LoadData(){
val accout = dbHelper.getAllUsers()
//this.listView.removeAllViews()
//List View
for (list in accout!!) {
lstUsers.add(list)
}
var myNotesAdapter= MyAdapter(this, lstUsers)
listView.adapter=myNotesAdapter
}
inner class MyAdapter:BaseAdapter {
var listMyAdapter = ArrayList<Account>()
var context:Context?=null
constructor(context:Context, listMyAdapter:ArrayList<Account>):super(){
this.listMyAdapter=listMyAdapter
this.context=context
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var myView=layoutInflater.inflate(R.layout.row,null)
var myAc=listMyAdapter[position]
myView.txtUser.text = myAc.userName
myView.txtEmail.text = myAc.email
return myView
}
override fun getItem(position: Int): Any {
return listMyAdapter[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return listMyAdapter.size
}
}
}
The error has shown like the picture below.
Please help me to solve it. Best regards, Sai Tawng Pha
I have solved my problem with update a few line of code. I want to share for other people.
If some one want to read exist Database file from Assests folder with Kotlin. Please have look below.
MainActivity.kt
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.row.*
import kotlinx.android.synthetic.main.row.view.*
import java.util.ArrayList
class MainActivity : AppCompatActivity() {
var lstUsers=ArrayList<Account>()
var dbHelper: DBHelper? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dbHelper = DBHelper(this)
dbHelper!!.createDatabase()
}
fun buGetData(v: View){
lstUsers = this.dbHelper!!.getAllUsers() as ArrayList<Account>
this.container.removeAllViews()
//List View
for (account in lstUsers) {
// val inflater = baseContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
// val addView = inflater.inflate(R.layout.row, null)
var addView = layoutInflater.inflate(R.layout.row,null)
addView.txtUser.text = account.userName
addView.txtEmail.text = account.email
//add View
container.addView(addView)
}
}
}
DBHelper.kt
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class DbHelper extends SQLiteOpenHelper {
private static String DB_PATH= "";
private static String DB_NAME= "account.db";
private SQLiteDatabase mDatabase;
private final Context mContext;
public DbHelper(Context context) {
super(context, DB_NAME, null, 11);
this.mContext = context;
if(Build.VERSION.SDK_INT >= 17){
this.DB_PATH = context.getApplicationInfo().dataDir+"/databases/";
Log.e("Path:", DB_PATH);
}else {
this.DB_PATH = "/data/data/"+context.getPackageName()+"/databases/";
Log.e("Path:", DB_PATH);
}
}
#Override
public synchronized void close() {
if(mDatabase != null){
mDatabase.close();
}
super.close();
}
private boolean checkDatabase(){
//Todo: Check Database
SQLiteDatabase tempDB = null;
try {
String path = DB_PATH+DB_NAME;
tempDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}catch (Exception ex){}
if(tempDB!=null){
tempDB.close();
}
return tempDB!=null?true:false;
}
public void copyDatabase(){
//Todo: Copy Database
try {
InputStream myInput = mContext.getAssets().open(DB_NAME);
String outputFileName = DB_PATH+DB_NAME;
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer,0,length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void openDatabase(){
//Todo: Open Database
String path = DB_PATH+DB_NAME;
mDatabase = SQLiteDatabase.openDatabase(path,null, SQLiteDatabase.OPEN_READWRITE);
}
public void createDatabase(){
//Todo: Create Database
boolean isDBExist = checkDatabase();
if (isDBExist){
}else {
this.getReadableDatabase();
try {
copyDatabase();
}catch (Exception e){throw new Error("Copy Database Error");}
}
}
public List<Account>getAllUsers(){
//Todo: Get All Users
List<Account> temp = new ArrayList<Account>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM Account", null);
if (c==null) return null;
c.moveToFirst();
do {
Account account = new Account(c.getString(c.getColumnIndex("name")),(c.getString(c.getColumnIndex("email"))));
temp.add(account);
}while (c.moveToNext());
c.close();
}catch (Exception e){}
db.close();
return temp;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/buGetData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Get Data" />
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/buGetData"
android:layout_centerHorizontal="true"
android:layout_marginTop="-15dp"
android:orientation="vertical"></LinearLayout>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="TextView"
android:textSize="18sp" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="TextView" />
</LinearLayout>
Please look the screenshot below.
Note: Please replace your Database file from Assets folder and change the name of your database name and table name from DBHelper.kt at createDataBase Function.
I hope, it will be useful for you.
I really don't know where I am going wrong. According to the documentation I am doing everything right. I am doubtful if it's happening just because I am using TabbedActivity and dealing with fragments, but still I don't know how it's wrong.
Please look into the code and help me out. I have been struggling a lot to achieve this task of retrieving and displaying data from FIREBASE.
And being a beginner in this, it's quite hard for me to figure it out.
MainActivity.Java
package com.example.souravkumar.sqaurewallpapers;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
int count=0;
public FloatingActionButton mAddImage;
private StorageReference mStorage;
public DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
String stringUri;
Long date;
private static final int GALLERY_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mStorage = FirebaseStorage.getInstance().getReference();
mAddImage = (FloatingActionButton) findViewById(R.id.addImage);
mAddImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
Uri uri = data.getData();
StorageReference filePath = mStorage.child("Wallpapers").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_LONG).show();
Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Adding image to the database
stringUri= downloadUrl.toString();
date = System.currentTimeMillis();
addImageToDatabase (stringUri, date);
}
});
}
}
private void addImageToDatabase(String downloadUrl, Long date){
image_details id= new image_details(downloadUrl, date);
String key = mDatabase.push().getKey();
mDatabase.child(key).child("URL").setValue(id.getUrl());
mDatabase.child(key).child("Date").setValue(id.getDate());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
GridView gridView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fragment_popular, container, false);
return rootView;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
View rootView = inflater.inflate(R.layout.fragment_recent, container, false);
return rootView;
} else
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "POPULAR";
case 1:
return "RECENT";
case 2:
return "PROFILES";
}
return null;
}
}
}
Popular.Java
package com.example.souravkumar.sqaurewallpapers;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
/**
* Created by Sourav Kumar on 11/3/2017.
*/
public class popular extends FragmentActivity {
private RecyclerView recyclerView;
private DatabaseReference myRef;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myRef = FirebaseDatabase.getInstance().getReference();
FirebaseRecyclerAdapter<image_details,BlogViewHolder> recyclerAdapter=new FirebaseRecyclerAdapter<image_details,BlogViewHolder>(
image_details.class,
R.layout.individual_row,
BlogViewHolder.class,
myRef
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, image_details model, int position) {
viewHolder.setUrl(model.getUrl());
viewHolder.setDate(model.getDate());
}
};
recyclerView.setAdapter(recyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
TextView textView;
ImageView imageView;
public BlogViewHolder(View itemView) {
super(itemView);
mView=itemView;
textView = (TextView)itemView.findViewById(R.id.date);
imageView = (ImageView)itemView.findViewById(R.id.imageView);
}
public void setDate(Long date) {
textView.setText(date.toString());
}
public void setUrl(String url) {
Picasso.with(mView.getContext())
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView);
}
}
}
image_details.Java
package com.example.souravkumar.sqaurewallpapers;
/**
* Created by Sourav Kumar on 10/29/2017.
*/
public class image_details {
String url;
Long date;
image_details(){}
public image_details(String url, Long date){
this.url = url;
this.date = date;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
}
fragment_popular.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"
tools:context="com.example.souravkumar.sqaurewallpapers.popular">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerView">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
individual_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="150dp"
android:layout_height="280dp"
android:id="#+id/imageView"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date"
android:id="#+id/date"/>
</LinearLayout>
</android.support.v7.widget.CardView>
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;
}
}
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
}
}