After adding the removal on long click part, i tried to add a call option the same way, but it didn't work.
I wrote the code here in the second box (first box is without the call option changes that didn't work) and highlighted the changes I tried with // signs.
This is the code: (i will add my attempts of creating the long click removal if you want)
public static final int PICK_CONTACT = 1;
private ArrayList<String> contactList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_work__contacts);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
//you may fill it here e.g. from your db
contactList=new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
final ListView lv = (ListView) findViewById(R.id.ContactListView);
lv.setAdapter(arrayAdapter);
lv.setLongClickable(true);
lv.setClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
arrayAdapter.notifyDataSetChanged();
arrayAdapter.remove(arrayAdapter.getItem(pos));
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
arrayAdapter.add(name + "-" + phoneNumber);
arrayAdapter.notifyDataSetChanged();
}
break;
}
}
}
}
public static final int PICK_CONTACT = 1;
private ArrayList<String> contactList;
private ArrayAdapter<String> arrayAdapter;
// private ArrayList<Integer> contactList2;
// private ArrayAdapter<Integer> arrayAdapter2;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_work__contacts);
Button btnPickContact = (Button) findViewById(R.id.btnPickContact);
btnPickContact.setOnClickListener(new View.OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
//you may fill it here e.g. from your db
contactList=new ArrayList<String>();
// contactList2=new ArrayList<Integer>();
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, contactList);
// arrayAdapter2 = new ArrayAdapter<Integer>(this,
// android.R.layout.simple_list_item_1, contactList2);
final ListView lv = (ListView) findViewById(R.id.ContactListView);
lv.setAdapter(arrayAdapter);
lv.setLongClickable(true);
lv.setClickable(true);
// final ListView lv2 = (ListView) findViewById(R.id.ContactListView);
// lv.setAdapter(arrayAdapter2);
// lv.setLongClickable(true);
// lv.setClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
arrayAdapter.notifyDataSetChanged();
arrayAdapter.remove(arrayAdapter.getItem(pos));
Log.v("long clicked","pos: " + pos);
return true;
}
});
// lv2.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> parent, View view,
// int position, long id) {
//
//String url = "tel:"+position;
// Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
// startActivity(intent);
//
//}
//});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT): {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
//Phone Name
Cursor c = managedQuery(contentUri, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Phone Number
String contactId = contentUri.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone._ID + "=?", new String[] { contactId },
null);// < - Note, not CONTACT_ID!
startManagingCursor(cursor);
Boolean numbersExist = cursor.moveToFirst();
int phoneNumberColumnIndex = cursor
.getColumnIndex(Phone.NUMBER);
String phoneNumber = "";
// Integer iInteger = new Integer(phoneNumberColumnIndex);
while (numbersExist) {
phoneNumber = cursor.getString(phoneNumberColumnIndex);
phoneNumber = phoneNumber.trim();
numbersExist = cursor.moveToNext();
}
stopManagingCursor(cursor);
//Set
arrayAdapter.add(name + " - " + phoneNumber);
arrayAdapter.notifyDataSetChanged();
// arrayAdapter2.add(iInteger);
// arrayAdapter2.notifyDataSetChanged();
}
break;
}
}
}
}
Anybody has an idea why it didn't work ?
Thank you
I think the best way is to implement a long click listener as you already did.
After that, I suggest you to show a message dialog for user to confirm. I share you a method to do this :
private AlertDialog showCustomDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo, final int selectedIndex) {
AlertDialog.Builder customDialog = new AlertDialog.Builder(act);
customDialog.setTitle(title);
customDialog.setMessage(message);
customDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
picURL.remove(selectedIndex);
}
});
customDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return customDialog.show();
}
Last thing : I see you're removing from the adapter, but not in the list. Maybe this is what causing your error ?
Related
I am trying to update my recyclerView by notifyDataSetChanged(). But it's not working. I have to close my specific fragment and open it to see the changes.
This is MyFragment where I call recyclerView
BottomSheetFragment.java
// showing Playlist Names
recyclerPlayListViewName =
bottomView.findViewById(R.id.recycler_play_list_view_name);
playlists = new ArrayList<Playlist>();
PlayListMethodHolder.getplaylistList(getContext(), playlists);
playlistAdapter = new PlaylistAdapter(bottomView.getContext(), playlists,
"bottomsheet");
recyclerPlayListViewName.setHasFixedSize(true);
recyclerPlayListViewName.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerPlayListViewName.setAdapter(playlistAdapter);
playlistAdapter.notifyDataSetChanged();
This is AdapterClass where I call to delete the playlist method.
PlaylistAdapter.java
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
long plistID = playlists.get(position).getId();
switch (item.getItemId()) {
case R.id.pPlay:
break;
case R.id.pRename:
String dpType = "playlistRename";
PlayListPopDialog popDialog = new PlayListPopDialog(mContext,
dpType, plistID, playlists);
popDialog.show();
break;
case R.id.pDelete:
PlayListMethodHolder.deletePlaylist(mContext, plistID);
break;
And This is another DialogView where I call Create PlayList
PlayListPopDialog.java
findViewById(R.id.btn_playlist_save).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtCreateNamePlaylist = findViewById(R.id.edt_create_name_playlist);
String playlistName = edtCreateNamePlaylist.getText().toString().trim();
if (!(playlistName.isEmpty())) {
boolean state = PlayListMethodHolder
.doPlaylistExists(getContext(), playlistName);
if (!state) {
PlayListMethodHolder.createPlaylist(getContext(), playlistName);
dismiss();
} else {
Toast.makeText(getContext(), "This name is already exists.",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "Empty name", Toast.LENGTH_SHORT).show();
}
}
});
Finally, this is a class for holding all methods of creating or deleting PlayLists
PlayListMethodHolder.java
public class PlayListMethodHolder {
public static void createPlaylist(Context context, String playlistName) {
String[] projectionName = new String [] {
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME,
MediaStore.Audio.Playlists.DATA,
};
ContentValues nameValues = new ContentValues();
nameValues.put(MediaStore.Audio.Playlists.NAME, playlistName);
nameValues.put(MediaStore.Audio.Playlists.DATE_ADDED,
System.currentTimeMillis());
nameValues.put(MediaStore.Audio.Playlists.DATE_MODIFIED,
System.currentTimeMillis());
Uri uri = context.getApplicationContext().getContentResolver()
.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, nameValues);
if (uri != null) {
context.getApplicationContext().getContentResolver()
.query(uri, projectionName, null, null, null);
context.getApplicationContext().getContentResolver().notifyChange(uri, null);
}
}
// Delete single playlist from list
public static void deletePlaylist (#NonNull final Context context, long playlistId){
String playlistid = String.valueOf(playlistId);
ContentResolver resolver = context.getContentResolver();
String where = MediaStore.Audio.Playlists._ID + "=?";
String[] whereVal = {playlistid};
resolver.delete(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, where,
whereVal);
return ;
}
// get Playlist names
public static void getplaylistList(Context context, ArrayList<Playlist> plist) {
Cursor playlistCursor = context.getContentResolver().query(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
null,
null,
null,
null);
if (playlistCursor != null && playlistCursor.moveToFirst()) {
//get columns
int idColumn = playlistCursor.getColumnIndex
(MediaStore.Audio.Playlists._ID);
int titleColumn = playlistCursor.getColumnIndex
(MediaStore.Audio.Playlists.NAME);
do {
long thisId = playlistCursor.getLong(idColumn);
String thisTitle = playlistCursor.getString(titleColumn);
plist.add(new Playlist(thisId, thisTitle));
} while (playlistCursor.moveToNext());
}
}
Tap to see PlayList Design View
I've create a custom ListView with title and artist TextView, and with play and stop Button. The problem is that when I press play or stop Button, audio file doesn't start. How is it possible?
I've uploaded my custom Adapter and my AudioToSendActivity class:
AudioAdapter.java
public class AudioAdapter extends ArrayAdapter<String> {
private Context mContext;
private List<String> audioList;
public AudioAdapter(#NonNull Context context, ArrayList<String> list) {
super(context, 0 , list);
mContext = context;
audioList = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.audio_row, parent, false);
String audio = audioList.get(position);
String[] items = audio.split("\n");
String title = "", artist = "";
if (items.length > 1) {
title = items[0];
}
if (items.length > 2) {
artist = items[1];
}
ImageView imageAudio = (ImageView) listItem.findViewById(R.id.audio_image);
TextView titleView = (TextView) listItem.findViewById(R.id.audio_title);
titleView.setText(title);
TextView artistView = (TextView) listItem.findViewById(R.id.audio_artist);
artistView.setText(artist);
return listItem;
}
}
AudioToSendActivity.java
public class AudioToSendActivity extends AppCompatActivity {
private ArrayList<String> arrayList;
private ListView listView;
private ArrayAdapter<String> adapter;
private static final int PERMISSION_REQUEST = 1;
private Button sendButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_to_send);
listView = findViewById(R.id.audio_list_view);
sendButton = findViewById(R.id.send_audio);
if(ContextCompat.checkSelfPermission(AudioToSendActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(AudioToSendActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(AudioToSendActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
else {
ActivityCompat.requestPermissions(AudioToSendActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
}
else {
upload();
}
}
private void upload() {
listView = findViewById(R.id.audio_list_view);
arrayList = new ArrayList<>();
getAudio();
adapter = new AudioAdapter(this, arrayList); //AudioAdapter<String>(this, arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// open music player to play desired song
}
});
}
public void getAudio() {
ContentResolver contentResolver = getContentResolver();
Uri audioUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor audioCursor = contentResolver.query(audioUri, null, null, null, null);
if(audioCursor != null && audioCursor.moveToFirst()) {
int audioTitle = audioCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int audioArtist = audioCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
do {
String currentTitle = audioCursor.getString(audioTitle);
String currentDate = audioCursor.getString(audioArtist);
arrayList.add(currentTitle + "\n" + currentDate);
}
while (audioCursor.moveToNext());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode) {
case PERMISSION_REQUEST: {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(ContextCompat.checkSelfPermission(AudioToSendActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
upload();
}
}
else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
}
}
Thanks in advance to everyone.
try this. Get the uri of your file and set it like this:
//for example
public void getAudio() {
ContentResolver contentResolver = getContentResolver();
Uri audioUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor audioCursor = contentResolver.query(audioUri, null, null, null, null);
if(audioCursor != null && audioCursor.moveToFirst()) {
int audioTitle = audioCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int audioArtist = audioCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
//get the song path here and ...
int audiodata = audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do {
String currentTitle = audioCursor.getString(audioTitle);
String currentDate = audioCursor.getString(audioArtist);
//And here
String currentPath = audioCursor.getString(audioPath);
//And add it to your list however you like
arrayList.add(currentTitle + "\n" + currentDate + "\n" + currentPath);
}
while (audioCursor.moveToNext());
}
}
And then retrieve the path and make a uri from it and the rest:
Uri myAudioUri = Uri.parse("file:///" + currentPath);
//or
Uri myAudioUri = Uri.parse(currentPath);
//didn't have time to check the lines above
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(this, myAudioUri);
mp.prepare();
mp.start();
I have a problem with creating two tables in sqlite and display them in RecyclerView and more specifically with one table. I add to the question a screenshot of the application so that you can understand what the problem is.
I have 3 activities: FirstActivity, in which there are two buttons (Monday and Tuesday) -> from this activity we go to MainActivity, on the button selection (Monday) -> save data in table_MON and after selection button (Tuesday) in the table_Tue. The problem is that everything works correctly, when we press the button (Monday) we can save the training, edit and delete it. However, when we go to the button (Tuesday) we can only add training, but we can't edit or delete them. However, I have no idea why? I am already looking at this problem for a week and I have no idea what is going on, maybe a fresh look will help solve the problem.
My database consists of two tables: tableMon and tableTue, but I use the same columns in it (exercises, weight etc ..), and separate _id, and I do not know if this can be a problem. Perhaps the problem is that I use MainActivity in both cases?
Screenshot App:
FirstActivity
enter image description here
Click button Monday --> MainActivity.class
enter image description here
Click button Tuesday --> MainActivity.class
enter image description here
Button Tuesday --> DetailActivity and her is the problem I can't update and delete training.
enter image description here
FirstActivity.class
public class FirstActivity extends AppCompatActivity {
Button buttonMon, buttonTue;
public static final String BUTTON_KEY1 = "BUTTON_KEY";
public static final String BUTTON_KEY2 = "BUTTON_KEY2";
public static final String BUTTON_VALUE = "1";
public static final String BUTTON_VALUE2 = "2";
public static boolean WAS_RUNNING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
buttonMon = (Button) findViewById(R.id.buttonMonday);
buttonTue = (Button) findViewById(R.id.buttonTuesday);
WAS_RUNNING = false;
//OPEN THE SAME MAINACTIVITY
buttonMon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WAS_RUNNING = true;
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
intent.putExtra(BUTTON_KEY1, BUTTON_VALUE);
startActivity(intent);
} });
//OPEN THE SAME MAINACTIVITY
buttonTue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WAS_RUNNING = true;
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra(BUTTON_KEY2, BUTTON_VALUE2);
startActivity(i);
} });}}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private ArrayList<Training> trainingArrayList = new ArrayList<Training>();
private EditText editTextExercise, editTextWeight, editTextRepeat, editTextSeries;
private Button buttonSave, buttonBack;
private Dialog dialog;
private String value;
private String value2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();}});
if(bundle == null)
{return;}
value = bundle.getString(FirstActivity.BUTTON_KEY1);
value2 = bundle.getString(FirstActivity.BUTTON_KEY2);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
if(value != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
myAdapter = new MyAdapter(this, trainingArrayList);
//Refresh MON TABLE
refreshMonTable();
}else if(value2 != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
myAdapter = new MyAdapter(this, trainingArrayList);
//Refresh TUE TABLE
refreshTueTable(); }}
public void showDialog()
{
dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_layout);
editTextExercise = (EditText) dialog.findViewById(editTextExerciseDialog);
editTextWeight = (EditText) dialog.findViewById(editTextWeightDialog);
editTextRepeat = (EditText) dialog.findViewById(editTextRepeatDialog);
editTextSeries = (EditText) dialog.findViewById(editTextSeriesDialog);
buttonSave = (Button) dialog.findViewById(buttonSaveDialog);
buttonBack = (Button) dialog.findViewById(buttonBackDialog);
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();}});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(value != null) {
saveDataMon(editTextExercise.getText().toString(),
String.valueOf(editTextWeight.getText().toString()),
String.valueOf(editTextRepeat.getText().toString()),
String.valueOf(editTextSeries.getText().toString()));
} else if(value2 != null) {
saveDataTue(editTextExercise.getText().toString(),
String.valueOf(editTextWeight.getText().toString()),
String.valueOf(editTextRepeat.getText().toString()),
String.valueOf(editTextSeries.getText().toString()));
}}});
dialog.show();}
private void saveDataMon(String exercise, String weight, String repeat, String series)
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
long result = adapter.addMon(exercise, weight, repeat, series);
if (result > 0) {
editTextExercise.setText("");
editTextWeight.setText("");
editTextRepeat.setText("");
editTextSeries.setText("");
dialog.dismiss();
} else {
Snackbar.make(editTextExercise, "Unable to save!", Snackbar.LENGTH_SHORT).show();}
adapter.closeDB();
refreshMonTable();}
private void saveDataTue(String exercise, String weight, String repeat, String series)
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
long result = adapter.addTue(exercise, weight, repeat, series);
if (result > 0) {
editTextExercise.setText("");
editTextWeight.setText("");
editTextRepeat.setText("");
editTextSeries.setText("");
dialog.dismiss();
} else {
Snackbar.make(editTextExercise, "Unable to save!", Snackbar.LENGTH_SHORT).show();
}
adapter.closeDB();
refreshTueTable();}
private void refreshMonTable()
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
trainingArrayList.clear();
Cursor cursor = adapter.getAllTreningMon();
if(cursor != null)
{ if(cursor.moveToFirst())
{
do {
int id = cursor.getInt(0);
String cwiczenie = cursor.getString(1);
String ciezar = cursor.getString(2);
String powtorzenia = cursor.getString(3);
String serie = cursor.getString(4);
Training training = new Training(id, cwiczenie, ciezar, powtorzenia, serie);
trainingArrayList.add(training);
}while (cursor.moveToNext());}}
recyclerView.setAdapter(myAdapter);
adapter.closeDB(); }
private void refreshTueTable()
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
trainingArrayList.clear();
Cursor cursor = adapter.getAllTreningTue();
if(cursor != null)
{ if(cursor.moveToFirst())
{
do {
int id = cursor.getInt(0);
String exercise = cursor.getString(1);
String weight = cursor.getString(2);
String repeat = cursor.getString(3);
String series = cursor.getString(4);
Training training = new Training(id, exercise, weight, repeat, series);
trainingArrayList.add(training);
}while (cursor.moveToNext());}}
recyclerView.setAdapter(myAdapter);
adapter.closeDB();
}
#Override
protected void onResume() {
super.onResume();
if(value != null) {
//REFRESH
refreshMonTable();
} else if(value2 != null) {
refreshTueTable();}}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Exit?")
.setMessage("Do you want to exit?")
.setNegativeButton("No", null)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.super.onBackPressed();
}
}).create().show();}}
DetailActivity.class
public class DetailActivity extends AppCompatActivity {
private EditText editTextExerciseDetail, editTextWeightDetail, editTextRepeatDetail, editTextSeriesDetail;
private Button buttonUpdate;
private Button buttonDelete;
String mon;
String tue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Bundle intent = getIntent().getExtras();
if(intent == null)
{return;}
mon = intent.getString(MyAdapter.KEY_MON);
tue = intent.getString(MyAdapter.KEY_TUE);
final int idT = intent.getInt("id");
String cwiczenie = intent.getString("exercise");
String ciezar = intent.getString("weight");
String powtorzenia = intent.getString("repeat");
String serie = intent.getString("series");
editTextExerciseDetail = (EditText) findViewById(R.id.exerciseEditTxtDetail);
editTextWeightDetail = (EditText) findViewById(R.id.weightEditTextDetail);
editTextRepeatDetail = (EditText) findViewById(R.id.repeatEditTextDetail);
editTextSeriesDetail = (EditText) findViewById(R.id.seriesEditTextDetail);
buttonUpdate = (Button) findViewById(R.id.updateBtn);
buttonDelete = (Button) findViewById(R.id.deleteBtn);
editTextExerciseDetail.setText(cwiczenie);
editTextWeightDetail.setText(ciezar);
editTextRepeatDetail.setText(powtorzenia);
editTextSeriesDetail.setText(serie);
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mon != null) {
updateMon(idT, editTextExerciseDetail.getText().toString(),
editTextWeightDetail.getText().toString(),
editTextRepeatDetail.getText().toString(),
editTextSeriesDetail.getText().toString());
} else if(tue != null) {
updateTue(idT, editTextExerciseDetail.getText().toString(),
editTextWeightDetail.getText().toString(),
editTextRepeatDetail.getText().toString(),
editTextSeriesDetail.getText().toString());}}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
builder.setMessage("Do you want delete this training?")
.setTitle("Delete")
.create();
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mon != null) {
deleteMon(idT);
}else if(tue != null){
deleteTue(idT);}}});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}});
builder.show();}});}
//Update MON TABLE
private void updateMon(int id, String newExercise, String newWeight, String newRepeat, String newSeries)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.updateMon(id, newExercise, newWeight, newRepeat, newSeries);
if(result > 0)
{
editTextExerciseDetail.setText(newExercise);
editTextWeightDetail.setText(newWeight);
editTextRepeatDetail.setText(newRepeat);
editTextSeriesDetail.setText(newSeries);
this.finish();
Snackbar.make(editTextExerciseDetail, "Updated Succesfully", Snackbar.LENGTH_SHORT).show();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to updated", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();
}
//Update TUE TABLE
private void updateTue(int id, String newExercise, String newWeight, String newRepeat, String newSeries)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.updateTue(id, newExercise, newWeight, newRepeat, newSeries);
if(result > 0)
{
editTextExerciseDetail.setText(newExercise);
editTextWeightDetail.setText(newWeight);
editTextRepeatDetail.setText(newRepeat);
editTextSeriesDetail.setText(newSeries);
this.finish();
Snackbar.make(editTextExerciseDetail, "Updated Succesfully", Snackbar.LENGTH_SHORT).show();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to updated", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();}
//DELETE MON TABLE
private void deleteMon(int id)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.deleteMon(id);
if(result>0)
{
this.finish();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to deleted", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();
}
//DELETE TUE TABLE
private void deleteTue(int id)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.deleteTue(id);
if(result>0)
{
this.finish();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to deleted", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();}
#Override
protected void onResume() {
super.onResume();}
#Override
protected void onRestart() {
super.onRestart();}}
DBHelper.class
public class DBHelper extends SQLiteOpenHelper {
//DB
static final String DB_NAME = "training_db";
static final int DB_VERSION = '1';
//TABLES
static final String TB_NAME_MON = "training_tb_mon";
static final String TB_NAME_TUE = "training_tb_tue";
//COLUMNS
static final String ROW_ID_MON = "id_Mon";
static final String ROW_ID_TUE = "id_Tue";
//ROW
static final String EXERCISE = "exercise";
static final String WEIGHT = "weight";
static final String REPEAT = "repeat";
static final String SERIES = "series";
static final String CREATE_TB_MON = "CREATE TABLE training_tb_mon (id_Mon INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "exercise TEXT NOT NULL, weight TEXT NOT NULL, repeat TEXT NOT NULL, series TEXT NOT NULL);";
static final String CREATE_TB_TUE = "CREATE TABLE training_tb_tue (id_Tue INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "exercise TEXT NOT NULL, weight TEXT NOT NULL, repeat TEXT NOT NULL, series TEXT NOT NULL);";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TB_MON);
db.execSQL(CREATE_TB_TUE);
}catch (Exception e) {
e.printStackTrace();
}}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME_MON);
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME_TUE);
onCreate(db);
}}
DBAdapter.class
public class DBAdapter {
Context c;
DBHelper dbHelper;
SQLiteDatabase db;
public DBAdapter(Context c) {
this.c = c;
dbHelper = new DBHelper(c);
}
//OPEN DATABASE
public DBAdapter openDatabase() {
try {
db = dbHelper.getWritableDatabase();
}catch (SQLiteException e) {
e.printStackTrace();
}
return this;
}
//CLOSE DATABASE
public void closeDB()
{
try{
dbHelper.close();
}catch (SQLiteException e){
e.printStackTrace();
}}
//Add training Mon
public long addMon(String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
return db.insert(DBHelper.TB_NAME_MON, DBHelper.ROW_ID_MON, contentValues);
}catch (SQLiteException e) {
e.printStackTrace(); }
return 0;}
//Add training Tue
public long addTue(String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
return db.insert(DBHelper.TB_NAME_TUE, DBHelper.ROW_ID_TUE, contentValues);
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0;
}
//REFRESH TABLE MON
public long updateMon(int id, String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
contentValues.put(DBHelper.ROW_ID_MON, id);
return db.update(DBHelper.TB_NAME_MON, contentValues, DBHelper.ROW_ID_MON + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace(); }
return 0;
}
//REFRESH TABLE TUE
public long updateTue(int id, String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
contentValues.put(DBHelper.ROW_ID_TUE, id);
return db.update(DBHelper.TB_NAME_TUE, contentValues, DBHelper.ROW_ID_TUE + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0;
}
//DELETE ROW TABLE MON
public long deleteMon(int id)
{
try{
return db.delete(DBHelper.TB_NAME_MON, DBHelper.ROW_ID_MON + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0; }
//DELETE ROW TABLE TUE
public long deleteTue(int id)
{
try{
return db.delete(DBHelper.TB_NAME_TUE, DBHelper.ROW_ID_TUE + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();}
return 0;}
//ALL TRAINING TABLE MON
public Cursor getAllTreningMon() {
try{
String[] columns = {DBHelper.ROW_ID_MON, DBHelper.EXERCISE, DBHelper.WEIGHT, DBHelper.REPEAT, DBHelper.SERIES};
return db.query(DBHelper.TB_NAME_MON, columns, null, null, null, null, null);
}catch (SQLiteException e)
{
e.printStackTrace();
}
return null;
}
//ALL TRAINING TABLE TUE
public Cursor getAllTreningTue() {
try{
String[] columns = {DBHelper.ROW_ID_TUE, DBHelper.EXERCISE, DBHelper.WEIGHT, DBHelper.REPEAT, DBHelper.SERIES};
return db.query(DBHelper.TB_NAME_TUE, columns, null, null, null, null, null);
}catch (SQLiteException e)
{
e.printStackTrace();
}
return null;}}
MyAdapter.class
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<Training> training;
public static String KEY_MON = "KEY_MON";
public static String KEY_TUE = "KEY_TUE";
public static String VALUE_MON = "10";
public static String VALUE_TUE = "20";
public <T extends Training> MyAdapter(Context c, ArrayList<Training> training) {
this.c = c;
this.training = training;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(c).inflate(R.layout.card_view_model, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
if (FirstActivity.WAS_RUNNING)
{Intent intent = new Intent(c, DetailActivity.class);
intent.putExtra(KEY_MON, VALUE_MON);
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
} else if (FirstActivity.WAS_RUNNING)
{Intent intent2 = new Intent(c, DetailActivity.class);
intent2.putExtra(KEY_TUE, VALUE_TUE);
intent2.putExtra("id", training.get(position).getId());
intent2.putExtra("exercise", training.get(position).getExercise());
intent2.putExtra("weight", training.get(position).getWeight());
intent2.putExtra("repeat", training.get(position).getRepeat());
intent2.putExtra("series", training.get(position).getSeries());
c.startActivity(intent2);
}}});}
#Override
public int getItemCount() {
return training.size();}}
Training.class
public class Training {
int id;
String exercise;
String weight;
String repeat;
String series;
public Training(int id, String exercise, String weight, String repeat, String series) {
this.id = id;
this.exercise = exercise;
this.weight = weight;
this.repeat = repeat;
this.series = series;
}
public int getId() {return id;}
public void setId(int id) { this.id = id;}
public String getExercise() {return exercise; }
public void setExercise(String exercise) {this.exercise = exercise;}
public String getWeight() {return weight;}
public void setWeight(String weight) {this.weight = weight; }
public String getRepeat() {return repeat;}
public void setRepeat(String repeat) { this.repeat = repeat;}
public String getSeries() {return series;}
public void setSeries(String series) {this.series = series;}}
In your MyAdapter class, in the onItemClick method, within the onBindViewHolder method, the second check, for Tue processing, would never run.
You have :-
if (FirstActivity.WAS_RUNNING) {
.......
} else if (FirstActivity.WAS_RUNNING) {
.......
}
i.e. you are saying if FirstActivity was not running and the FirstActivity was running then do your stuff.
i.e. the else will only be entered if FirstActivity were not running, in which case the if (FirstActivity.WAS_RUNNING) would never be true.
Perhaps have 2 booleans MONDAY_WAS_RUNNING and TUESDAY_WAS RUNNING (you could use just the existing boolean by setting that to false in the buttonTue listener doing the Tuesday processing in the else (without an if) ).
e.g. :-
FirstActivity class :-
public static boolean MONDAY_WAS_RUNNING;
public static boolean TUESDAY_WAS_RUNNING;
..........
buttonMon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MONDAY_WAS_RUNNING = true;
TUESDAY_WAS_RUNNING = false;
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
intent.putExtra(BUTTON_KEY1, BUTTON_VALUE);
startActivity(intent);
} });
buttonTue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TUESDAY_WAS_RUNNING = true;
MONDAY_WAS_RUNNING = false;
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra(BUTTON_KEY2, BUTTON_VALUE2);
startActivity(i);
} });}}
MyAdapter :-
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
if (FirstActivity.MONDAY_WAS_RUNNING)
{Intent intent = new Intent(c, DetailActivity.class);
intent.putExtra(KEY_MON, VALUE_MON);
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
} else if (FirstActivity.TUESDAY_WAS_RUNNING)
{Intent intent2 = new Intent(c, DetailActivity.class);
intent2.putExtra(KEY_TUE, VALUE_TUE);
intent2.putExtra("id", training.get(position).getId());
intent2.putExtra("exercise", training.get(position).getExercise());
intent2.putExtra("weight", training.get(position).getWeight());
intent2.putExtra("repeat", training.get(position).getRepeat());
intent2.putExtra("series", training.get(position).getSeries());
c.startActivity(intent2);
}}});}
However I'd probably go for :-
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
Intent intent = new Intent(c, DetailActivity.class);
if (FirstActivity.MONDAY_WAS_RUNNING) {
intent.putExtra(KEY_MON, VALUE_MON);
} else {
intent.putExtra(KEY_TUE, VALUE_TUE);
}
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
});
}
Note! the above code has not been checked, rather it is in-principle code
I can make my database save images. They are display in the listView
but when i close the app, the data are erased.
DataBaseHandler.java:
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "Preguntas_y_Respuestas_Manager",
TABLE_PyR = "PreguntasYRespuestas",
KEY_ID = "id",
KEY_PREGUNTA = "pregunta",
KEY_RESPUESTA = "respuesta",
KEY_IMAGEURI = "imagen";
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_PyR + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_PREGUNTA + " TEXT," + KEY_RESPUESTA + " TEXT, " + KEY_IMAGEURI + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PyR);
onCreate(db);
}
public void createPregunta_y_Respuesta(PreguntasYRespuestas pYr) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PREGUNTA, pYr.getPregunta());
values.put(KEY_RESPUESTA, pYr.getRespuesta());
values.put(KEY_IMAGEURI,pYr.get_imageUri().toString());
db.insert(TABLE_PyR, null, values);
db.close();
}
public PreguntasYRespuestas getPyR(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_PyR, new String[]{KEY_ID, KEY_PREGUNTA, KEY_RESPUESTA, KEY_IMAGEURI}, KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
PreguntasYRespuestas preg_y_resp = new PreguntasYRespuestas(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Uri.parse(cursor.getString(3)));
db.close();
return preg_y_resp;
}
public void deletePregunta(PreguntasYRespuestas pyr) {
SQLiteDatabase db = getWritableDatabase();
int cant = db.delete("PreguntasYRespuestas", "id=" + KEY_ID, null);
}
public int getPreguntasCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_PyR, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int UpdatePregunta(PreguntasYRespuestas pyr) {
SQLiteDatabase db = getReadableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PREGUNTA, pyr.getPregunta());
values.put(KEY_RESPUESTA, pyr.getRespuesta());
values.put(KEY_IMAGEURI, pyr.get_imageUri().toString());
int rowsAffected = db.update(TABLE_PyR, values, KEY_ID + "=?", new String[]{String.valueOf(pyr.getId())});
db.close();
return rowsAffected;
}
public List<PreguntasYRespuestas> getAllPreguntas() {
List<PreguntasYRespuestas> pyr = new ArrayList<PreguntasYRespuestas>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_PyR, null);
if (cursor.moveToFirst()) {
do {
pyr.add(new PreguntasYRespuestas(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),Uri.parse(cursor.getString(3))));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return pyr;
}
}
RegistroDePreguntas_Cuestionario.java:
public class RegistroDePreguntas_Cuestionario extends AppCompatActivity {
private static final int EDIT = 0, DELETE = 1;
public Button agregar, iniciar;
public ImageView imagen;
public EditText et_pregunta, et_respuesta;
public ListView listView_preguntas;
Uri imageUri = null;
DataBaseHandler dbHandler;
int longClickedItemIndex;
ArrayAdapter<PreguntasYRespuestas> preguntasAdapter;
List<PreguntasYRespuestas> mListaPreguntas = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro_de_preguntas__cuestionario);
agregar = (Button) findViewById(R.id.agregar);
et_pregunta = (EditText) findViewById(R.id.Et_pregunta);
et_respuesta = (EditText) findViewById(R.id.Et_respuesta);
imagen = (ImageView)findViewById(R.id.imageView);
iniciar = (Button) findViewById(R.id.iniciar);
listView_preguntas = (ListView) findViewById(R.id.listview_preguntas);
dbHandler = new DataBaseHandler(getApplicationContext());
TabHost tabHost = (TabHost) findViewById(R.id.tabHost_Preg_Cuest);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.Creador);
tabSpec.setIndicator("Crear");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("visualizacion");
tabSpec.setContent(R.id.Visualizacion);
tabSpec.setIndicator("Ver");
tabHost.addTab(tabSpec);
registerForContextMenu(listView_preguntas);
listView_preguntas.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
});
iniciar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegistroDePreguntas_Cuestionario.this, ActivityCuestionario.class));
}
});
agregar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PreguntasYRespuestas pyr = new PreguntasYRespuestas(dbHandler.getPreguntasCount(), String.valueOf(et_pregunta.getText()), String.valueOf(et_respuesta.getText()),imageUri);
if (!preguntaExists(pyr)) {
dbHandler.createPregunta_y_Respuesta(pyr);
mListaPreguntas.add(pyr);
preguntasAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Tu pregunta ha sido aƱadida", Toast.LENGTH_SHORT).show();
et_pregunta.setText("");
et_respuesta.setText("");
imageUri = null;
return;
}
Toast.makeText(getApplicationContext(), "Ya existe una pregunta igual, no pueden haber 2 preguntas iguales", Toast.LENGTH_SHORT).show();
}
});
imagen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Contact Image"),1);
}
});
et_pregunta.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
agregar.setEnabled(String.valueOf(et_pregunta.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (dbHandler.getPreguntasCount() != 0) {
mListaPreguntas.addAll(dbHandler.getAllPreguntas());
populateList();
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.edit);
//Icon made by [http://www.flaticon.com/authors/madebyoliver] from www.flaticon.com
menu.setHeaderTitle("Opciones");
menu.add(Menu.NONE, DELETE, menu.NONE, "Eliminar pregunta");
}
public void onActivityResult(int reqCode, int resCode, Intent data){
if (resCode==RESULT_OK){
if (reqCode==1){
imageUri = data.getData();
imagen.setImageURI(data.getData());
}
}
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
dbHandler.UpdatePregunta(mListaPreguntas.get(longClickedItemIndex));
preguntasAdapter.notifyDataSetChanged();
break;
case DELETE:
dbHandler.deletePregunta(mListaPreguntas.get(longClickedItemIndex));
mListaPreguntas.remove(longClickedItemIndex);
preguntasAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean preguntaExists(PreguntasYRespuestas pyr) {
String pregunta = pyr.getPregunta();
int preguntaCount = mListaPreguntas.size();
for (int i = 0; i < preguntaCount; i++) {
if (pregunta.compareToIgnoreCase(mListaPreguntas.get(i).getPregunta()) == 0)
return true;
}
return false;
}
public void populateList() {
preguntasAdapter = new mListAdapter();
listView_preguntas.setAdapter(preguntasAdapter);
}
public class mListAdapter extends ArrayAdapter<PreguntasYRespuestas> {
public mListAdapter() {
super(RegistroDePreguntas_Cuestionario.this, R.layout.listview_item, mListaPreguntas);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
PreguntasYRespuestas currentPregunta = mListaPreguntas.get(position);
TextView tv_pregunta = (TextView) view.findViewById(R.id.tv_pregunta);
tv_pregunta.setText(currentPregunta.getPregunta());
TextView tv_respuesta = (TextView) view.findViewById(R.id.tv_respuesta);
tv_respuesta.setText(currentPregunta.getRespuesta());
ImageView imageView_Lista = (ImageView) view.findViewById(R.id.imageView_Lista);
imageView_Lista.setImageURI(currentPregunta.get_imageUri());
return view;
}
}
}
I want to have an option for user to upload two images and retrieve image after saved on database, i am new to android programming, I am trying this since four days, googled alot, but could not find out exact solution.
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME
+ " (name,number,skypeId,address) values (?,?,?,?)";
public DataManipulator(Context context) {
DataManipulator.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulator.context);
DataManipulator.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulator.db.compileStatement(INSERT);
}
public long insert(String name, String number, String skypeId,
String address) {
this.insertStmt.bindString(1, name);
this.insertStmt.bindString(2, number);
this.insertStmt.bindString(3, skypeId);
this.insertStmt.bindString(4, address);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id", "name",
"number", "skypeId", "address" }, null, null, null, null,
"name asc");
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public void delete(int rowId) {
db.delete(TABLE_NAME, null, null);
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "
+ TABLE_NAME
+ " (id INTEGER PRIMARY KEY, name TEXT, number TEXT, skypeId TEXT, address TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
my SaveData.java file
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save);
View add = findViewById(R.id.Button01add);
add.setOnClickListener(this);
View home = findViewById(R.id.Button01home);
home.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.Button01home:
Intent i = new Intent(this, DatabaseSample.class);
startActivity(i);
break;
case R.id.Button01add:
View editText1 = (EditText) findViewById(R.id.name);
View editText2 = (EditText) findViewById(R.id.number);
View editText3 = (EditText) findViewById(R.id.skypeId);
View editText4 = (EditText) findViewById(R.id.address);
String myEditText1 = ((TextView) editText1).getText().toString();` `
String myEditText2 = ((TextView) editText2).getText().toString();
String myEditText3 = ((TextView) editText3).getText().toString();
String myEditText4 = ((TextView) editText4).getText().toString();
this.dh = new DataManipulator(this);
this.dh.insert(myEditText1, myEditText2, myEditText3, myEditText4);
showDialog(DIALOG_ID);
break;
}
}
protected final Dialog onCreateDialog(final int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Information saved successfully ! Add Another Info?")
.setCancelable(false)
.setPositiveButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
SaveData.this.finish();
}
})
.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
dialog = alert;
break;
default:
}
return dialog;
}
}
and CheckData.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = name[1] + " - " + name[2] + " - " + name[3] + " - " + name[4];
stg1[x] = stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stg1);
this.setListAdapter(adapter);
selection = (TextView) findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
selection.setText(stg1[position]);
}
}
For saving image in database table you need to convert it to byte array and then you can put it in a contentValue. You can make a method for saving image as shown below-
protected long saveBitmap(SQLiteDatabase database, Bitmap bmp)
{
int size = bmp.getRowBytes() * bmp.getHeight();
ByteBuffer b = ByteBuffer.allocate(size); bmp.copyPixelsToBuffer(b);
byte[] bytes = new byte[size];
b.get(bytes, 0, bytes.length);
ContentValues cv=new ContentValues();
cv.put(CHUNK, bytes);
this.id= database.insert(TABLE, null, cv);
}
For fetching back that record you can do it like this-
byte[] bb = cursor.getBlob(cursor.getColumnIndex(/*Your column index for saving image*/));