I am creating a simple tasklist app in Android Studios.
I have two activities as following (removed imports and package specifications):
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
EditText taskAdd;
Button add;
public ListView tasks;
public Integer pos = 0;
public ArrayList<String> taskArray;
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskAdd = findViewById(R.id.taskAdd);
add = findViewById(R.id.add);
tasks = findViewById(R.id.tasks);
taskArray = FileHelper.readData(this);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, taskArray);
tasks.setAdapter(adapter);
add.setOnClickListener(this);
tasks.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.add:
String entered = taskAdd.getText().toString();
if (entered != "" || entered != null || entered != "null") {
adapter.add(entered);
taskAdd.setText("");
FileHelper.writeData(taskArray, this);
Toast.makeText(this, "Task Added!", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos = position;
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivity(intent);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
processExtraData();
}
private void processExtraData(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("Value");
if (value == 1) {
taskArray.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Task Removed!", Toast.LENGTH_SHORT).show();
}
}
}
}
Pop.java (a popup)
public class Pop extends Activity implements View.OnClickListener {
Button deleteButton;
Button finishedButton;
Button timerButton;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.popwindow);
deleteButton = findViewById(R.id.deleteButton);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*0.5),(int)(height*0.5));
deleteButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(this, MainActivity.class);
i.putExtra("Value", 1);
startActivity(i);
}
}
After I click deleteButton in Pop.java, processExtraData in MainActivity.java is supposed to run. The Toast does appear, but the selected object in the ListView is not deleted. No errors are thrown either. In addition, using Log.d to check the size of taskArray confirmed that this is not just a graphical issue. Why is this the case, and how should I go about fixing it?
Thank you for replying in advance.
The issue is that you are using an object reference instead of a primitive data type, and so when you are calling taskArray.remove(pos), it is looking for pos the object rather than its denoted integer value.
Instead of:
taskArray.remove(pos);
try:
taskArray.remove(pos.intValue());
Related
I'm kind of new to android. I want to get an int value id(id of dynamically generated buttons) from class MainPage into class Note when a button is clicked. but the value of id always turns to zero in Note class.
here's the summerized code:
MainPage class:
public class MainPage extends AppCompatActivity {
public int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int j=0; j<allnotes.size(); j++) {
//generating buutons
final Button preview_text = new Button(this);
preview_text.setId(j)
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id=v.getId();
startActivity(new Intent(MainPage.this, Note.class));
}
});
}
}
}
Notes class:
public class Note extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
MainPage obj=new MainPage();
int id=obj.id
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout,Integer.toString(id) , 10000);
mySnackbar.show();
}
in snackbar message, id is always zero.
You need to add the id to the Intent you use to start the Note activity. You do this by using Intent.putExtra(...) and in Note you retrieve it via getIntent().getIntExtra(...)
Here I implemented #Riccully Answer in your code.
MainPage.java
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id = v.getId();
Intent intent = new Intent(MainPage.this, Note.class);
intent.putExtra("id_value", id);
startActivity(intent);
}
});
Note.java
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
int id = getIntent().getIntExtra("id_value", 0);
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout, Integer.toString(id), 10000);
mySnackbar.show();
}
we can do this via intent Because Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services, etc.
In Our case, we can send the v.getId() to Note.java, viaputExtra
intent.putExtra("view_id",v.getId());
and receive the value in Note.java by using
getIntent().getIntExtra("view_id", 0);
Excuse my noobness. I just don't understand how to implement it to work with my code. What I'm doing is editing a name that's in a list view. When editing the name in "EditDeleteList" and get back to the previous activity (ListView) to see the name updated within the list view, nothing happens. I have to go out of the activity completely to see the change reflected. How do I get this to update? I implement an onActivityReult() method but then get this error message "java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference" so I removed it completely. How I could get the list view to update without getting that error message?
ListView.Java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
DatabaseHelper mDatabaseHelper;
Button btnAdd;
private EditText editText;
private android.widget.ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
}
EditDeleteList.java
public class EditDeleteList extends AppCompatActivity {
private static final String TAG = "EditDeleteList";
DatabaseHelper mDatabaseHelper;
private ImageView ivDelete;
private ImageView ivApprove;
private EditText editHashtag;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_delete);
mDatabaseHelper = new DatabaseHelper(this);
editHashtag = (EditText) findViewById(R.id.editHashtag);
ivDelete = (ImageView) findViewById(R.id.ivDelete);
ivApprove = (ImageView) findViewById(R.id.ivApprove);
//get the intent extra from the ListView activity
final Intent receivedIntent = getIntent();
//get item ID passed as an extra
selectedID = receivedIntent.getIntExtra("id", -1);
//get name passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set text field to selected item text
editHashtag.setText(selectedName);
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
In the EditDeleteList.java I have an onClickListener that saves the changes and goes back to the previous activity by using finish();
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
Notify the adapter in some part of the activity lifecycle.
OnCreate() should not run when you go back (this is the reason you have to completely recreate the activity to see the list updated) so you should use OnRestart/OnStart/OnResume to notify the adapter to check for new items.
Check this image
I have a project with 4 classes: 2 activities, 1 adapter and 1 class for simple object. Names of the classes are: MainActivity, AddingItemsActivity, ItemAdapter, SimpleItem. In a layout corresponding to the MainActivity, there is a list view named SimpleListView. SimpleListView should contain SimpleItem objects. ItemAdapter is made to handle SimpleListView. Updating, adding items to SimpleListView from MainActivity is very easy. What I would like to reach is updating, adding items, which appear on the SimpleListView, from AddingItemsActivity (appear when user come back to the MainActivity). Could you tell me what should I do to reach that?
PS: I would like to ask: "how to update SimpleListView from AddingItemsActivity?" but I have read that it is not proper question, beacuse SimpleListView does not exist in AddingItemsActivity.
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button toAddingActivity = findViewById(R.id.toAddingActivitybutton);
final ListView simpleItemsListView = findViewById(R.id.SimpleListView);
final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter);
toAddingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddingItemsActivity.class);
startActivity(intent);
}
});
}
}
AddingItemsActivity
public class AddingItemsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_items);
Button addItem = findViewById(R.id.AddItembutton);
// final ListView simpleItemsListView = findViewById(R.id.SimpleListView);
// final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// first reflex try, which does not work:
// SimpleItem item = new SimpleItem("String number 1", "String number 2");
// mAdapter.add(item);
// simpleItemsListView.setAdapter(mAdapter);
}
});
}
}
ItemAdapter
public class ItemAdapter extends ArrayAdapter<SimpleItem>{
public ItemAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ItemAdapter(Context context, int resource, List<SimpleItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.simple_item_adapter, null);
}
SimpleItem item = getItem(position);
if (item != null) {
TextView tv1 = v.findViewById(R.id.adapterTextView1);
TextView tv2 = v.findViewById(R.id.adapterTextView2);
tv1.setText(item.getStr1());
tv2.setText(item.getStr2());
}
return v;
}
}
SimpleItem
public class SimpleItem {
private String str1;
private String str2;
public SimpleItem(String s1, String s2)
{
str1 = s1;
str2 = s2;
}
public String getStr1()
{
return str1;
}
public String getStr2()
{
return str2;
}
}
Use startActivityForResult to get the result as SimpleItem from AddingItemsActivity.
Intent intent = new Intent(getBaseContext(), AddingItemsActivity.class);
startActivityForResult(intent,1);
Create a SimpleItem in AddingItemsActivity, add values to it and use setResult to give simple item instance back to MainActivity
// inside on click
SimpleItem item = new SimpleItem("String number 1", "String number 2");
Intent returnIntent = new Intent();
returnIntent.putExtra("result", item);
setResult(Activity.RESULT_OK,returnIntent);
finish();`
In MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
SimpleItem result = (SimpleItem)data.getSerializableExtra("result");
// add result to the list, used by adapter
// notify adapter using notifyDataSetChanged
}
}
}//onActivityResult
Note : add public class SimpleItem implements Serializable and seems like you forgot to create and pass list to adapter instances, so simply create it
your adaper is not complete you must override getCount method and set your list.size() to it . then from your MainActivity you mast create a list of simle item and pass it to your adapter .
ArrayList<SimpleItem> items=new ArrayList<>();
final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter,items);
then you can put your list to intent and pass it to AddingItemsActivity .
Intent intent=new Intent (this,AddingItemsActivity.class);
intent.putExtra("Key",items);
startActivityForResult(intent,your request code (exam : 14));
and in AddingItemsActivity :
Bundle bundel=getIntent().getExtras();
ArrayList<SimpleItem> items=(ArrayList<SimpleItem>)bundle.get("Key");
change or add items to list and return it to MainActivity :
Intent returnIntent = new Intent();
returnIntent.putExtra("returnedList", item);
setResult(Activity.RESULT_OK,returnIntent);
finish();
and in onActivityResult of MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 14) {
if(resultCode == Activity.RESULT_OK){
// ArrayList<SimpleItem> items=(ArrayList<SimpleItem>)data.getSerializableExtra("returnedList");
items=(ArrayList<SimpleItem>)data.getSerializableExtra("returnedList");
mAdapter .notifyDataSetChanged();
}
}
}
And dont forgot implemens your simpleItem class of Serializable
try this :
MainActivity :
public class MainActivity extends AppCompatActivity {
private ArrayList<SimpleItem> items = new ArrayList<>();
private Button toAddingActivity;
private ListView simpleItemsListView;
private ItemAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toAddingActivity = (Button) findViewById(R.id.toAddingActivitybutton);
simpleItemsListView = (ListView) findViewById(R.id.SimpleListView);
mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter, items);
simpleItemsListView.setAdapter(mAdapter);
toAddingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddingItemsActivity.class);
startActivityForResult(intent, 14);
}
});
mAdapter.notifyDataSetChanged();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 14 && resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
SimpleItem item=(SimpleItem) bundle.get("reKey");
items.add(item);
mAdapter.notifyDataSetChanged();
}
}
}
ItemAdapter :
public class ItemAdapter extends ArrayAdapter<SimpleItem>{
private ArrayList<SimpleItem> items =new ArrayList<>();
private Activity activity;
private int layoutResource;
public ItemAdapter(#NonNull Activity act, int resource, #NonNull ArrayList<SimpleItem> data) {
super(act, resource, data);
items =data;
activity=act;
layoutResource=resource;
}
#Override
public int getCount() {
return items.size();
}
#Override
public SimpleItem getItem(int position) {
return items.get(position);
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
View row=convertView;
if(row==null || (row.getTag()==null)){
LayoutInflater inflater=LayoutInflater.from(activity);
row=inflater.inflate(layoutResource,null);
holder=new ViewHolder();
holder.tv1=row.findViewById(R.id.adapterTextView1);
holder.tv2=row.findViewById(R.id.adapterTextView2);
row.setTag(holder);
}else {
holder=(ViewHolder)row.getTag();
}
holder.simpleItem=items.get(position);
holder.tv1.setText(holder.simpleItem.getStr1());
holder.tv2.setText(holder.simpleItem.getStr2());
return row;
}
class ViewHolder{
TextView tv1;
TextView tv2;
SimpleItem simpleItem;
}
}
AddingItemsActivity :
public class AddingItemsActivity extends AppCompatActivity{
private Button addItem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_items);
addItem=(Button)findViewById(R.id.AddItembutton);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleItem item = new SimpleItem("String number 1", "String number 2");
Intent returnIntent = new Intent();
returnIntent.putExtra("reKey",item);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
}
}
you can change AddingItemsActivity onclick method
This is my code:
public class MainActivity extends AppCompatActivity {
ListView listView ;
ArrayList<String> StoreContacts, id;
Bundle bundle;
ArrayAdapter<String> arrayAdapter ;
Cursor cursor;
Intent intent;
String name, phonenumber ;
public static final int RequestPermissionCode = 1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listview1);
StoreContacts = new ArrayList<String>();
id = new ArrayList<String>();
EnableRuntimePermission();
GetContactsIntoArrayList();
arrayAdapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.contact_items_listview,
R.id.textView, StoreContacts
);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bundle =new Bundle();
/*SharedPreferences.Editor editor=getSharedPreferences("Suyash",MODE_PRIVATE).edit();
editor.putString("ID",id.get(i));
editor.apply();*/
intent = new Intent(MainActivity.this, SingleContact.class);
bundle.putString("ID",id.get(i));
intent.putExtra("ID",id.get(i));
startActivity(intent);
}
});
}
public void GetContactsIntoArrayList(){
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
while (cursor.moveToNext()) {
id.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)));;
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
StoreContacts.add(name + " " + ":" + " " + phonenumber);
}
cursor.close();
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(
MainActivity.this,
Manifest.permission.READ_CONTACTS))
{
Toast.makeText(MainActivity.this,"CONTACTS permission allows us to Access CONTACTS app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.READ_CONTACTS}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,"Permission Granted, Now your application can access CONTACTS.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission Canceled, Now your application cannot access CONTACTS.", Toast.LENGTH_LONG).show();
}
break;
}
}
}
on receiving end:
public class SingleContact extends AppCompatActivity {
Bundle bundle=getIntent().getExtras();
//SharedPreferences preferences=getSharedPreferences("Suyash",MODE_PRIVATE);
0String string = bundle.getString("ID",null);
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
button= (Button) findViewById(R.id.button);
//string= bundle.getString("ID");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(SingleContact.this, string, Toast.LENGTH_SHORT).show();
}
});
}
}
the crashes when I click the item.
i have tried sharedpreference too, it does the same thing. im using android studio 2.3.3.
anyone suggest what i should do.
please help
You can not get the bundle before onCreate(). Write your code something like below and it will resolve your error.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// Your bundle code.
Bundle bundle=getIntent().getExtras();
String string = bundle.getString("ID",null);
}
Probably wrong initialization of bundle data in SingleContact Activity, you should initialise inside of onCreate method
public class SingleContact extends AppCompatActivity {
Bundle bundle;
String string;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
bundle = getIntent().getExtras()
button= (Button) findViewById(R.id.button);
string= bundle.getString("ID");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(SingleContact.this, string, Toast.LENGTH_SHORT).show();
}
});
}
}
I need an answer on how to create an add button to add listview item, and a delete button to delete last added item. Look at my code. I made an add button but that item exists only for a few seconds and every time I close that page (go to other activity in usermode) it is deleted. Please let me know how can I fix this code and how can I write code for delete button. I need to know how to delete last made item. Thanks for your help in advance. I am looking forward to reply.
public class dodaj extends Activity {
ListView lv;
SearchView sv;
EditText txtinput;
ArrayList<String> arrayList;
String[] recepies={};
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dodaj);
registerClickCallback();
lv=(ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView);
txtinput=(EditText)findViewById(R.id.txtinput);
Button addbutton=(Button)findViewById(R.id.addbutton);
Button buttondel=(Button) findViewById(R.id.buttondel);
arrayList= new ArrayList<>(Arrays.asList(recepies));
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
String newItem=txtinput.getText().toString();
arrayList.add(newItem);
adapter.notifyDataSetChanged();
}
});
buttondel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
int i = arrayList.size()-1;
arrayList.remove(arrayList.get(i));
}
});
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
private void registerClickCallback(){
lv=(ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
TextView textView= (TextView) viewClicked;
if(position==0){
goToMojRecept1();
}else if(position==1){
goToMojRecept2();
}else if(position==2){
goToMojRecept3();
}else if(position==3){
goToMojRecept4();
}else if(position==4) {
goToMojRecept5();
}
}
});
}
private void goToMojRecept5() {
Intent intent = new Intent(this, MojRecept5.class);
startActivity(intent);
}
private void goToMojRecept4() {
Intent intent = new Intent(this, MojRecept4.class);
startActivity(intent);
}
private void goToMojRecept3() {
Intent intent = new Intent(this, MojRecept3.class);
startActivity(intent);
}
private void goToMojRecept2() {
Intent intent = new Intent(this, MojRecept2.class);
startActivity(intent);
}
private void goToMojRecept1() {
Intent intent = new Intent(this, MojRecept1.class);
startActivity(intent);
}