Я ожидаю, что данные будут храниться из значения View в List view в SQLite и будут популярны в Listview при повторном открытии приложения.Я использовал этот метод на EditText
....setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {...
, чтобы сохранить данные на SQLite сразу после изменения EditText, но он не работает должным образом. Вот класс MyCustomAdapter
public class MyCustomAdapter extends ArrayAdapter<Song> {
private Context context;
private int resource;
private ArrayList<Song> listsong;
private DatabaseHelper datab;
private final String TAG = getClass().getSimpleName();
public MyCustomAdapter(Context context, int resource, ArrayList<Song> objects) {
super(context, resource, objects);
this.context=context;
this.resource=resource;
this.listsong=objects;
}
@Override
public Song getItem(int position) {
return listsong.get(position);
}
@NonNull
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
viewHolder=null;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.song_items,parent,false);
viewHolder = new ViewHolder();
viewHolder.tenbai = (TextView) convertView.findViewById(R.id.text);
viewHolder.delaytime = (EditText) convertView.findViewById(R.id.delay);
viewHolder.timeunit = (TextView) convertView.findViewById(R.id.timeunit);
//attach the TextWatcher listener to the EditText
convertView.setTag(viewHolder);
Log.d(TAG, "getView: "+(position+1));
// SELETECTED
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
Song infor = listsong.get(position);
viewHolder.tenbai.setText(infor.getTenbai());
viewHolder.timeunit.setText(infor.getTimeunit());
viewHolder.delaytime.setVisibility(View.VISIBLE);
//Fill EditText with the value you have in data source
viewHolder.delaytime.setText(infor.getDelaytime());
viewHolder.delaytime.setId(position);
//we need to update adapter once we finish with editing
viewHolder.delaytime.setOnFocusChangeListener(new
View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
listsong.get(position).setDelaytime(Caption.getText().toString());
new DatabaseHelper(context).insertSong( listsong.get(position) );
}
}
});
return convertView;
}
public class ViewHolder{
TextView tenbai;
EditText delaytime;
TextView timeunit;
}
}
Вот класс DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "songs_db";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// create notes table
db.execSQL(Song.CREATE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + Song.TABLE_NAME);
// Create tables again
onCreate(db);
}
public boolean ifExists(String tenbai)
{ SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String checkQuery = "SELECT " + Song.COLUMN_TENBAI + " FROM " + Song.TABLE_NAME + " WHERE " + Song.COLUMN_TENBAI + "= '"+tenbai + "'";
cursor= db.rawQuery(checkQuery,null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
public boolean isEmpty(String TableName){
SQLiteDatabase database = this.getReadableDatabase();
int NoOfRows = (int) DatabaseUtils.queryNumEntries(database,TableName);
if (NoOfRows == 0){
return true;
}else {
return false;
}
}
public boolean isTableExists(String tableName) {
SQLiteDatabase db = this.getWritableDatabase();
boolean isExist = false;
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);
if (cursor != null) {
if (cursor.getCount() > 0) {
isExist = true;
}
cursor.close();
}
return isExist;
}
public void insertSong(Song song) {
// get writable database as we want to write data
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Song.COLUMN_TENBAI, song.getTenbai());
values.put(Song.COLUMN_DUONGDAN, song.getDuongdan());
values.put(Song.COLUMN_DELAYTIME, song.getDelaytime());
values.put(Song.COLUMN_TIMEUNIT, song.getTimeunit());
// insert row
long id = db.insert(Song.TABLE_NAME, null, values);
// close db connection
db.close();
Log.d("Ket qua", "addStudent Successfuly");
// return newly inserted row id
}
// TAO MANG CHO RECYCLE QUAN NotesAdapter
public List<Song> getAllSongs() {
List<Song> notes = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + Song.TABLE_NAME + " ORDER BY " +
Song.COLUMN_TENBAI + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Song song = new Song();
song.setId(cursor.getInt(cursor.getColumnIndex(song.COLUMN_ID)));
song.setTenbai(cursor.getString(cursor.getColumnIndex(song.COLUMN_TENBAI)));
song.setDuongdan(cursor.getString(cursor.getColumnIndex(song.COLUMN_DUONGDAN)));
song.setDelaytime(cursor.getString(cursor.getColumnIndex(song.COLUMN_DELAYTIME)));
song.setTimeunit(cursor.getString(cursor.getColumnIndex(song.COLUMN_TIMEUNIT)));
notes.add(song);
} while (cursor.moveToNext());
}
// close db connection
db.close();
// return notes list
return notes;
}
public int getNotesCount() {
String countQuery = "SELECT * FROM " + Song.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
public int updatedelaytime(Song song) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Song.COLUMN_DELAYTIME, song.getDelaytime());
// updating row
return db.update(Song.TABLE_NAME, values, Song.COLUMN_TENBAI + " = ?",new String[]{String.valueOf(song.getTenbai())});
}
Вот класс MainActivity
public class MainActivity extends AppCompatActivity {
ImageButton btnList,btnPlay,btnStop,btnForward,btnPrev;
Button btnsave;
private MediaPlayer mp;
private TextView txtTotal,txtCurrent;
private SeekBar soundSeek;
int currentPosition = 0;
int totalDuration = 0;
int value =0;
boolean Playing = false;
String audioFile = "";
int SONG_NUMBER = 0;
int CURRENT_NUMBER= 0;
private DatabaseHelper db;
private ListView playList;
MyCustomAdapter myCustomAdapter;
public static ArrayList<Song> fileNames;
public ArrayList<Song> newlistsong;
String INTERNAL_PATH = Environment.getExternalStorageDirectory() .toString()+"/";;
String EXTERNAL_PATH = "Download";
static String AUDIO_PATH = "";
String[] DIRECTORIES = {INTERNAL_PATH,EXTERNAL_PATH};
public static int songNumber ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
btnsave = (Button) findViewById(R.id.btn_save);
btnList = (ImageButton)findViewById(R.id.imbList);
btnPlay = (ImageButton) findViewById(R.id.imageButton3);
btnStop = (ImageButton) findViewById(R.id.imageButton4);
btnForward = (ImageButton) findViewById(R.id.imageButton5);
btnPrev = (ImageButton) findViewById(R.id.imageButton2);
txtCurrent = (TextView) findViewById(R.id.textView2);
txtTotal = (TextView) findViewById(R.id.textView);
soundSeek = (SeekBar) findViewById(R.id.seekBar);
mp = new MediaPlayer();
playList = (ListView)findViewById(R.id.listView);
playList.setItemsCanFocus( true );
db = new DatabaseHelper(this);
if(!db.isTableExists( "songs" )||db.isEmpty("songs")) {
fileNames=new ArrayList<Song>( );
Collections.sort(fileNames, new Comparator<Song>() {
@Override
public int compare(Song data1, Song data2) {
return (int) data1.getTenbai().charAt(0) - (int) data2.getTenbai().charAt(0);
}
});
getFiles();
playList.setAdapter(new MyCustomAdapter( this, R.layout.song_items, fileNames ) );
}
else
{
newlistsong =new ArrayList<Song>( );
Collections.sort(newlistsong, new Comparator<Song>() {
@Override
public int compare(Song data1, Song data2) {
return (int) data1.getTenbai().charAt(0) - (int) data2.getTenbai().charAt(0);
}
});
newlistsong.addAll( db.getAllSongs() );
playList.setAdapter( new MyCustomAdapter( this, R.layout.song_items, newlistsong ));
System.out.println( "mang : " +newlistsong.size()+"phan tu: "+newlistsong.toString());
}
playList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, fileNames.get(position).getDuongdan().toString()+" vi tri "+ position, Toast.LENGTH_LONG).show();
SONG_NUMBER=position;
playMedia(fileNames.get(position).getDuongdan().toString());
}
});
setListeners();
}
public void getFiles(){
fileNames.clear();
for(int d = 0 ; d < DIRECTORIES.length ; d++){
File f = new File(DIRECTORIES[d]);
f.mkdir();
File[] files = f.listFiles();
if(files != null && files.length > 0){
for(File file : files){
if(file.isDirectory()){
scanDirectory(file);
}else{
addSong(file);
}
}
}
}
}
public void scanDirectory(File directory){
if(directory != null){
File[] listFiles = directory.listFiles();
for (File file:listFiles){
// neu muon load tat ca cac file trong folder cha
if(file.isDirectory()){
scanDirectory(file);
}else{
addSong(file);
}
}
}
}
public void addSong(File song) {
if (song.getName().endsWith( ".mp3" ) && song.getAbsolutePath().contains( EXTERNAL_PATH )) {
fileNames.add( new Song( song.getName(), song.getAbsolutePath(), "", "sec" ) );
}
}
public static String getpath(String tenbai)
{ String path = null;
for (int i=0;i<fileNames.size();i++)
{
if(fileNames.get(i).getTenbai().equals( tenbai ))
{path= fileNames.get(i).getDuongdan();}
}
return path;
}
public void save()
{
DatabaseHelper dbhelp= new DatabaseHelper(this);
for(int i=0;i<fileNames.size();i++) {
Song moderntalking= new Song();
moderntalking.setTenbai( fileNames.get(i).getTenbai());
moderntalking.setDuongdan( fileNames.get(i).getDuongdan());
moderntalking.setDelaytime( fileNames.get(i).getDelaytime());
moderntalking.setTimeunit( fileNames.get(i).getTimeunit());
System.out.println( moderntalking.getDelaytime() );
if(!dbhelp.ifExists( moderntalking.getTenbai() ))
{ dbhelp.insertSong( fileNames.get(i) );}
else
{ dbhelp.updatedelaytime( moderntalking );}
}
Toast.makeText(MainActivity.this, "saved",Toast.LENGTH_LONG).show();
}
}
Вот класс песни открытый класс Song {
public static final String TABLE_NAME = "songs";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TENBAI = "tenbai";
public static final String COLUMN_DUONGDAN = "duongdan";
public static final String COLUMN_DELAYTIME = "delaytime";
public static final String COLUMN_TIMEUNIT = "timeunit";
public Integer id;
public String tenbai;
public String duongdan;
public String delaytime;
public String timeunit;
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_TENBAI + " TEXT,"
+ COLUMN_DUONGDAN + " TEXT,"
+ COLUMN_DELAYTIME + " TEXT,"
+ COLUMN_TIMEUNIT + " TEXT"
+ ")";
public Song() {}
public Song( String tenbai, String duongdan, String delaytime, String timeunit) {
this.tenbai = tenbai;
this.duongdan = duongdan;
this.delaytime = delaytime;
this.timeunit = timeunit;
}
public Song(Integer id, String tenbai, String duongdan, String delaytime, String timeunit) {
this.id = id;
this.tenbai = tenbai;
this.duongdan = duongdan;
this.delaytime = delaytime;
this.timeunit = timeunit;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTenbai() {
return tenbai;
}
public void setTenbai(String tenbai) {
this.tenbai = tenbai;
}
public String getDuongdan() {
return duongdan;
}
public void setDuongdan(String duongdan) {
this.duongdan = duongdan;
}
public String getDelaytime() {
return delaytime;
}
public void setDelaytime(String delaytime) {
this.delaytime = delaytime;
}
public String getTimeunit() {
return timeunit;
}
public void setTimeunit(String timeunit) {
this.timeunit = timeunit;
}
}
Я хочу сохранить имя строки, путь, время задержкиВременные единицы в SQLite.Затем заставьте их правильно отображаться в CustomView Listview.Спасибо за помощь