I have a ListView display file from SD card. I want to add a button for deleting all items from ListView and from SD card. I tried the following, but it deletes one. And after clicking the button a second time, it deletes another one.
Button delete = (Button) findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i=0;i<adapter.getCount();i++){
adapter.getItem(i);
File ff = new File(Environment.getExternalStorageDirectory().toString() + "/TestApp/" + adapter.getItem(i));
ff.delete();
}
adapter.remove(adapter.getItem(i));
adapter.notifyDataSetChanged();
}
}
You need to clear the list associated with your adapter here. Then just call notifyDataSetChanged() on your adapter. So the sample code should look like this. Just clear the list after you have deleted all associated files in your SD card.
Button buy = (Button) findViewById(R.id.delete);
buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < yourList.size(); i++){
File ff = new File(Environment.getExternalStorageDirectory().toString() + "/TestApp/" + yourList.get(i));
ff.delete();
}
// Clear your list here
yourList.clear();
// And remove the following line
// adapter.remove(adapter.getItem(i));
adapter.notifyDataSetChanged();
}
}
Place following method in you adapter:
public void clearData(){
list.clear();
notifyDataSetChanged();
}
Now Replace your code lines:
adapter.remove(adapter.getItem(i));
adapter.notifyDataSetChanged();
to This line:
adapter.clearData();
Related
I tried to get a array from an adapter from my code
here is the array that i wanted to get from my adapter, named MakananAdapter :
private int[] JumlahPesan = {0,0,0,0};
The array is changing constantly since user will be deciding the amount that they want, here is the onBindViewHolder code:
public void onBindViewHolder(#NonNull viewHolder holder, final int position) {
ImageView ivMakanan = holder.ivMakanan;
TextView tvNamaHarga = holder.tvNamaMakanan;
TextView tvKetersediaan = holder.tvKetersediaan;
TextView tvHarga = holder.tvHargaMakanan;
final TextView tvPesanan = holder.tvJumlahPesanan;
Button btnTambah = holder.btnTambah;
Button btnKurang = holder.btnKurang;
ivMakanan.setImageResource(makanans.get(position).getGambarMakanan());
tvNamaHarga.setText(makanans.get(position).getNamaMakanan());
tvKetersediaan.setText("Stok : " + makanans.get(position).getStatusMakanan());
tvHarga.setText("Harga : " + makanans.get(position).getHargaMakanan());
btnTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumlahPesan[position]++;
tvPesanan.setText(String.valueOf(JumlahPesan[position]));
}
});
btnKurang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumlahPesan[position]--;
tvPesanan.setText(String.valueOf(JumlahPesan[position]));
}
});
}
as you can see i make a button that increase and decrease the data of the array
and i tried to get the array data to my activity, but i still get error.
my activity named PilihMakananActivity.class
here is the array to save the data from the adapter
private int[] Pesanan = {0,0,0,0};
and i tried to get the data in onResume
protected void onResume() {
super.onResume();
com.example.iotforcanteen.adapter.MakananAdapter coba = null;
for (int i = 0; i<4 ; i++) {
Pesanan [i]= coba.AmbilJumlahPesanan(i);
}
}
and i tried to show it in a snackbar like this
btnKonfirmasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, Pesanan[0] + Pesanan[1] + Pesanan[2] + Pesanan[3],Snackbar.LENGTH_SHORT).show();
}
});
Im so sorry if the code is so messy, because im new to android development.so is there any way to fix this error?
It has error because you set to your adapter null value in onResume .
But in general I assume you use RecyclerView in code so the steps for using RecyclerView is important, first you must set LayoutManager for RecyclerView. Then make an adapter and set it to RecyclerView and I recommend you to do this steps in onCreate not onResume.
Here is a little example
RecyclerView recyclerView = findViewById(R.id.rec);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, list);
recyclerView.setAdapter(adapter);
Also make your array in adapter public or write getter for it. After calling setAdapter for RecyclerView, you can get your data in adapter. For example you can define a Button and in OnClickListener get the desired array(here is JumlahPesan) in adapter
you aren't initiating this adapter (null) and few lines below trying to access data from it, this is NullPointerException
com.example.iotforcanteen.adapter.MakananAdapter coba = null;
for (int i = 0; i<4 ; i++) {
Pesanan [i]= coba.AmbilJumlahPesanan(i);
}
make reference to already exitsting adapter atached to your ListView or RecyclerView, not freshly created and not initialised at all
note that onResume is called once at the beggining, thus your Pesanan won't have current data, only copy from start of Activity
maybe just get your values straightly when button pressed, without a copy of array in Activity:
btnKonfirmasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(coordinatorLayout,
adapterAttachedToView.AmbilJumlahPesanan(0) + " " +
adapterAttachedToView.AmbilJumlahPesanan(1) + " " +
adapterAttachedToView.AmbilJumlahPesanan(2) + " " +
adapterAttachedToView.AmbilJumlahPesanan(3),
Snackbar.LENGTH_SHORT).show();
}
});
note that Snackbar.make( should take View, in which Snackbar will appear, not clicked Button (you are passing v to Snackbar.make)
I am new working with this customized Dialog in android. I may not be able to clarify my problem properly by writing, So it humble request to understand what i want from given code.
In MainActivity i have Button to delete an element of an ArrayList and setting the info from the ArrayList to a Layout.
Code from CustomDialog:
public class PermissionToDelete extends Dialog implements View.OnClickListener {
public Button btnYes, btnNo;
public TextView txtPermToDelete;
public PermissionToDelete(Context context){
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.permission_delete);
initialize();
}
public void initialize(){
btnYes = findViewById(R.id.btnYes);
btnNo = findViewById(R.id.btnNo);
txtPermToDelete = findViewById(R.id.txtPermToDelete);
btnYes.setOnClickListener(this);
btnNo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnNo){
dismiss();
}
else if(v.getId() == R.id.btnYes){
MainActivity.deleteOrErase = "delete";
dismiss();
}
}
}
There is a static String variable in MainActivity named deleteOrErase.
From dialog it returns the string delete if Button Yes is clicked.
Code from MainActivity:
tv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String text = tv.getText().toString();
PermissionToDelete permissionToDelete = new PermissionToDelete(MainActivity.this);
permissionToDelete.show();
if(deleteOrErase.equals("delete")){
String index = "";
for(int i = 1; text.charAt(i) != ')'; i++){
index += text.charAt(i);
}
tasksList.remove(Integer.parseInt(index) - 1);
File rootFile = new File(rootFolder);
if(rootFile.exists()){
String[]entries = rootFile.list();
for(String s: entries){
File currentFile = new File(rootFile.getPath(),s);
currentFile.delete();
}
rootFile.delete();
}
dailyTasksLayout.removeAllViews();
makePrimaryFileAndFolder();
saveDataToFile();
setTaskList();
deleteOrErase = "";
}
But the problem is before button from dialog is clicked, if(deleteOrErase.equals("delete")) is encountered when the value of deleteOrErase is still null.
Therefore data isn't deleted at the first click.
Its need second click to delete, because now the value of deleteOrErase is "delete".
How can i delete it from first click?
Or is there any other way???
thanks dear honorable members! <3
(I don't know either i could clarify my problem or not.
Even i can't understand from mty writings :P )
I'm making an android POS and I have a problem to add a data pass to other activity. When the user is adding a new product, the product will show on the Menu activity in the Button form and has a value whatever the user input in the name and price.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addproduct);
POSDB = new DatabaseHelper(this);
prdName = (EditText)findViewById(R.id.PrdName);
prdPrice = (EditText) findViewById(R.id.PrdPrice);
btnAdd = (Button) findViewById(R.id.BtnPrdAdd);
btnBack = (Button) findViewById(R.id.BtBack);
AddProduct();
}
public void AddProduct(){
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = prdName.getText().toString().trim();
String price = prdPrice.getText().toString().trim();
if(prdName.length() != 0 && prdPrice.length() != 0)
{
boolean ADD = POSDB.addData(name,price);
if(ADD == true)
{Toast.makeText(Addproduct.this, " The product has been added", Toast.LENGTH_LONG).show();}
else
{Toast.makeText(Addproduct.this, " Something Went Wrong", Toast.LENGTH_LONG).show();}
}
else
{Toast.makeText(Addproduct.this, " Please fill up the Textfield", Toast.LENGTH_LONG).show();}
}
});
}
That depends on how do you structure the Menu Activity to get the data and how it shows it.
For example, If you are using a RecyclerView you can set it to show the data in a list of buttons, so when a new product added to the database it will be shown by RecyclerView in the button form.
Hi I'm working at my first bigger app in android studio "FlashCards". I would like it to work so after you click on the button the flashcard's textview changes its text to next random flashcard untill you see all of the them how can i do something like 'continue' to my loop from inside onClick method.
here's the loop's code:
while(i < mTestDeck.size()) {
// generates random number which will represent position in deck.
int random = randomGenerator.nextInt() % mTestDeck.size();
// if random flashcard was already shown create random number again
if (mTestDeck.get(random).wasShown())
continue;
//text view that we will operate on
TextView deckTextView = (TextView) findViewById(R.id.flashcard_text_view);
// set text
deckTextView.setText(mTestDeck.get(random).getFront());
// set mWasShown to true
mTestDeck.get(random).flashcardShown();
Button myButton = (Button) findViewById(R.id.know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTestDeck.correctAnswer();
}
});
myButton = (Button) findViewById(R.id.dont_know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
First, this way, you have a potential infinite loop. And if it can happens, it will happens! It's not a good idea to "get random item and check if it's ok or try again".
I think that it's better to keep a list with all items in a random order. You just have to iterate over it.
Something like:
int currentPosition = 0;
List<Card> items = new ArrayList<Card>(mTestDeck).shuffle();
// Call this method once in onCreate or anywhere you initialize the UI
private void function setCurrentCard() {
Card currentItem = items.get(currentPosition);
[...] // Set all UI views here
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition > items.size) {
// TODO? End?
return;
}
currentPosition++;
setCurrentCard();
}
});
}
I'm adding EditText in linear layout and it gives a view like that in image.
I'm getting this view by using this code.
public class SearchRecipe extends AppCompatActivity {
LinearLayout parentLayout;
ImageButton searchRecipe;
private int EDITTEXT_ID = 1;
private List<EditText> editTextList;
EditText editTextItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_recipe);
setActionBar();
init();
searchRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextItem = (EditText) parentLayout.findViewById(EDITTEXT_ID);
for (int i = 0; i < editTextList.size(); i++) {
Log.e("All Values=", editTextList.get(i).getText().toString());
Toast.makeText(SearchRecipe.this, editTextItem.getText().toString() + " ", Toast.LENGTH_SHORT).show();
}
}
});
}
public void init() {
parentLayout = (LinearLayout) findViewById(R.id.parent_layout); //make sure you have set vertical orientation attribute on your xml
searchRecipe = (ImageButton) findViewById(R.id.search_button);
editTextList = new ArrayList<EditText>();
TextView addMoreText = new TextView(this);
addMoreText.setText("Add More Ingredients");
addMoreText.setGravity(Gravity.CENTER);
addMoreText.setPadding(20, 20, 20, 20);
addMoreText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.add, 0);
addMoreText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextItem = new EditText(SearchRecipe.this);
editTextItem.setId(EDITTEXT_ID);
editTextList.add(editTextItem);
EDITTEXT_ID++;
editTextItem.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.cross, 0);
editTextItem.setPadding(20, 20, 20, 20);
editTextItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
parentLayout.removeView(editTextItem);
return true;
}
});
parentLayout.addView(editTextItem, 0);
}
});
parentLayout.addView(addMoreText);
}
Now the only problem I'm facing is that. I'm not getting the text from edittext properly. Let me Explain what I want to do.
Click on Add More TextView will add one more edit text.
After adding all edittexts I will click on Search button.
By clicking search button will get the data from edittexs and save in arraylist. I tried a lot but can't do this properly. will you please help me to do this thing ? I'm stuck in from many days.
if you are createing edit text run time only for this purpose then there is no need of below tow lines
editTextItem.setId(EDITTEXT_ID);
EDITTEXT_ID++;
To retrive data from each edit box follow below things
for (EditText editText : editTextList) {
/* now you can get the value from Edit-text and save in the ArrayList
or you can append it in same string*/
yourArraList.add(editText.getText().toString()));
}
Get the editext from your list editTextList
String data = editTextList.get(index).getText().toString();
Add check for editTextList should not be null or empty.
You can iterate over list using for-each loop
for (EditText editText : editTextList) {
// now you can get the value from Edit-text and save in the ArrayList
yourArraList.add(editText.getText().toString()));
}
you can do like below if view inside fragment.
public static String getText(final Activity activity) {
final StringBuilder stringBuilder=new StringBuilder();
LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);
ArrayList<String> msg = new ArrayList<String>();
for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
{
LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
EditText editText = (EditText) innerLayout.findViewById(R.id.meeting_dialog_et);
msg.add(editText.getText().toString());
}
for (int j=0;j<msg.size();j++)
{
stringBuilder.append(msg.get(j)).append(";");
}
Toast t = Toast.makeText(activity.getApplicationContext(), stringBuilder.toString(), Toast.LENGTH_SHORT);
t.show();
return stringBuilder.toString();
}
there is another way is make arraylist Edittexes and add each edittext when it added to layout. then you can get like below:
for (int i = 0; i < Edittexes.size(); i++) {
if (Edittexes.get(i) == view)
{
String text=Edittexes.get(i).getText();
}
}