How can I add a delete notes funcation to my app - java

I'm creating a app that is for notes. I'm trying to figure out how to create a function that will delete the Note by having an option in a menu inside of the edit portion of the app that you can press and then it will delete the note. Can someone please point me in the right direction to doing something like this? I have included my code below for both my main activity Java file and my editor activity file
Main
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_note) {
// Going from MainActivity to NotesEditorActivity
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set == null) {
notes.add("Welcome To Notes!!!!!");
} else {
notes = new ArrayList(set);
}
// Using custom listView Provided by Android Studio
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Going from MainActivity to NotesEditorActivity
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int itemToDelete = i;
// To delete the data from the App
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
}).setNegativeButton("No", null).show();
return true;
}
});
}
}
Editer
public class NoteEditorActivity extends AppCompatActivity {
int noteId;
static ArrayList<String> notes = new ArrayList<>();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == R.id.add_note) {
}
int id = item.getItemId();
if(id == android.R.id.home){
Intent i= new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//To have the back button!!
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_note_editor);
EditText editText = findViewById(R.id.editText);
Intent intent = getIntent();
noteId = intent.getIntExtra("noteId", -1);
if (noteId != -1) {
editText.setText(MainActivity.notes.get(noteId));
} else {
MainActivity.notes.add("");
noteId = MainActivity.notes.size() - 1;
MainActivity.arrayAdapter.notifyDataSetChanged();
}
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// add your code here
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
MainActivity.notes.set(noteId, String.valueOf(charSequence));
MainActivity.arrayAdapter.notifyDataSetChanged();
// Creating Object of SharedPreferences to store data in the phone
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
#Override
public void afterTextChanged(Editable editable) {
// add your code here
}
});
}
}

Related

How to save a listview using shared preference

I've made a simple shopping list app where the user can add items to the listview. My problem is when I leave the app the items do not save. I think I need to use a shared preference but haven't had much look implementing it (I'm fairly new to coding) If anyone knows how to implement the shared preference so my items will save it would be much appreciated.
My code:
public class CreateAList extends AppCompatActivity {
//ArrayList for data
private ArrayList<String> list = new ArrayList<>();
ListView list_view;
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alist);
//find view by id
list_view = findViewById(R.id.list_view);
arrayAdapter = new ArrayAdapter(CreateAList.this, android.R.layout.simple_list_item_1,list);
list_view.setAdapter(arrayAdapter);
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {
//Inflating is the process of adding a view(.xml) to activity on runtime
PopupMenu popupMenu = new PopupMenu(CreateAList.this,view);
popupMenu.getMenuInflater().inflate(R.menu.pop_up_menu,popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.item_update:
//function for update
AlertDialog.Builder builder = new AlertDialog.Builder(CreateAList.this);
View v = LayoutInflater.from(CreateAList.this).inflate(R.layout.item_dialog,null,false);
builder.setTitle("Update Item");
final EditText editText = v.findViewById(R.id.editItem);
editText.setText(list.get(i));
//set custom view to dialog
builder.setView(v);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
if (!editText.getText().toString().isEmpty()){
list.set(i, editText.getText().toString().trim());
arrayAdapter.notifyDataSetChanged();
Toast.makeText(CreateAList.this, "Item Updated", Toast.LENGTH_SHORT).show();
}else{
editText.setError("add item here!");
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
});
builder.show();
break;
case R.id.item_delete:
//function for delete
Toast.makeText(CreateAList.this, "Item Deleted", Toast.LENGTH_SHORT).show();
list.remove(i);
arrayAdapter.notifyDataSetChanged();
break;
}
return true;
}
});
popupMenu.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_item:
//function to add
addItem();
break;
}
return true;
}
//method for adding item
private void addItem() {
AlertDialog.Builder builder = new AlertDialog.Builder(CreateAList.this);
builder.setTitle("Add new Item");
View v = LayoutInflater.from(CreateAList.this).inflate(R.layout.item_dialog,null,false);
builder.setView(v);
final EditText editItem = v.findViewById(R.id.editItem);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (!editItem.getText().toString().isEmpty()){
list.add(editItem.getText().toString().trim());
arrayAdapter.notifyDataSetChanged();
}else{
editItem.setError("Add Item Here!");
}
}
});
}
It would be a good idea to go through a tutorial for shared preference. This way you will learn more. Also look for SQLite database that Android provides to store data. I think that will be much better approach if you have simple objects in your list view.
Here is a good tutorial : https://medium.com/#evancheese1/shared-preferences-saving-arraylists-and-more-with-json-and-gson-java-5d899c8b0235
void putSharedPreferencesStringSet(String key, Set value)
{
SharedPreferences.Editor edit = getContext().getSharedPreferences("SHARED_PREFERENCE_NAME", 0).edit();
edit.putStringSet(key, value);
edit.apply();
}
void putSharedPreferencesStringSet(String key, String value)
{
SharedPreferences.Editoredit = getContext().getSharedPreferences("SHARED_PREFERENCE_NAME", 0).edit();
edit.putString(key, value);
edit.apply();
}
String getSharedPreferencesString(String key)
{
SharedPreferences prefs = AppConstants.appContext.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, 0);
return prefs.getString(key, 0);
}
void removeSharedPreferencesString(String key)
{
SharedPreferences edit = AppConstants.appContext.getSharedPreferences(AppConstants.SHARED_PREFERENCE_NAME, 0);
edit.remove(key);
edit.apply();
}
//the above functions are about add , get and remove sharedPrefrences
Another way if you need to use database when ever you add items in to your cart

Attempt to invoke virtual method 'java.lang.String java.util.HashSet.toString(). getting null pointer exception

android studio doesnt show any error while typing, this error comes only when running. Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.util.HashSet.toString()' on a null object reference
problem should be in one of these three lines
HashSet set = (HashSet) sharedPreferences.getStringSet("notes", null);
Log.i("test", set.toString());
if (set == null) {
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_note) {
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
Log.i("test", set.toString());
if (set == null) {
notes.add("Example note");
} else {
notes = new ArrayList(set);
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int itemToDelete = i;
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
}
)
.setNegativeButton("No", null)
.show();
return true;
}
});
}
}
//2nd class
public class NoteEditorActivity extends AppCompatActivity {
int noteId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_editor);
EditText editText = (EditText) findViewById(R.id.editText);
Intent intent = getIntent();
noteId = intent.getIntExtra("noteId", -1);
if (noteId != -1) {
editText.setText(MainActivity.notes.get(noteId));
} else {
MainActivity.notes.add("");
noteId = MainActivity.notes.size() - 1;
MainActivity.arrayAdapter.notifyDataSetChanged();
}
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
MainActivity.notes.set(noteId, String.valueOf(charSequence));
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.robpercival.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
// problem is here. "set" object is null.
Log.i("test", set.toString());
if (set == null) {
notes.add("Example note");
} else {
notes = new ArrayList(set);
}
change to
if (set == null) {
notes.add("Example note");
} else {
notes = new ArrayList(set);
// suggestion use Log.d("test", set.toString()); since d -> debug, i->
// information
Log.i("test", set.toString());
}
You have to test if its null befote using it
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set == null) {
notes.add("Example note");
} else {
Log.i("test", set.toString());
notes = new ArrayList(set);
}

ListView Adapter - OnClick to launch a new Activity & OnLongClick to launch a ContextActionBar

Onclick and OnlongClick doesn't work, I am using AppCompatActivity to support KitKat. I am not sure why it's not working. Is it the adapter OR the view? I know I am using deprecated adapter, but I am using it for a purpose.
The code below:
public class MainActivity extends AppCompatActivity {
ActionMode mActionMode;
private CartDbAdapter dba;
private Cursor cursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
databaseview();
}
else {
setContentView(R.layout.cart);
dba = new CartDbAdapter(this);
dba.open();
}
private void databaseview(){
cursor = dba.fetchAllBooks();
ListView listView = (ListView) findViewById(list);
startManagingCursor(cursor);
String [] from = new String[] {BookContract.TITLE , BookContract.AUTHORS };
int [] to = new int [] {android.R.id.text1 , android.R.id.text2 };
SimpleCursorAdapter databaseAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, cursor, from, to);
listView.setAdapter(databaseAdapter);
listView.setOnLongClickListener(longListener);
listView.setOnClickListener(clickListener);
}
View.OnLongClickListener longListener = new View.OnLongClickListener() {
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
mActionMode = MainActivity.this.startSupportActionMode(callback);
view.setSelected(true);
return true;
}
};
View.OnClickListener clickListener = new View.OnClickListener(){
public void onClick(View view) {
Intent viewIntent = new Intent(MainActivity.this, BookActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable(BookActivity.KEY, dba.fetchBook(view.getId()));
viewIntent.putExtras(bundle);
startActivity(viewIntent);
}
};
private ActionMode.Callback callback = new ActionMode.Callback() {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextbar_menu, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
mode.finish();
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
Thank you!
I just solved this issue by using setOnItemClickListener and setOnItemLongClickListener with ListView Adapter..
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(arg0.getContext(), ((TextView)arg1).getText(), Toast.LENGTH_SHORT).show();
return false;
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View itemView, int index,
long id) {
}
});

How can I limit each item in a ListView to one line?

In a ListView populated by an ArrayList, how can I limit the number of characters per list item or limit each list item to only one line of text? It's a notes app. all my code is below.
ListView:
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="end"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:singleLine="true"/>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
static ArrayList<String> note;
ListView listView;
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
static Set<String> set;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
setTitle("Notely");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notes.add("");
SharedPreferences sharedPreferences = getSharedPreferences("mypackage", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
} else {
set.clear();
}
set.addAll(notes);
arrayAdapter.notifyDataSetChanged();
sharedPreferences.edit().remove("notes").apply();
sharedPreferences.edit().putStringSet("notes", set).apply();
Intent i = new Intent(getApplicationContext(), EditNote.class);
i.putExtra("noteId", notes.size() - 1);
startActivity(i);
}
});
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences = this.getSharedPreferences("mypackage", Context.MODE_PRIVATE);
set = sharedPreferences.getStringSet("notes", null);
notes.clear();
if (set != null) {
notes.addAll(set);
} else {
notes.add("Example note");
set = new HashSet<String>();
set.addAll(notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), EditNote.class);
i.putExtra("noteId", position);
startActivity(i);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
notes.remove(position);
SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("mypackage", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
} else {
set.clear();
}
set.addAll(notes);
sharedPreferences.edit().remove("notes").apply();
sharedPreferences.edit().putStringSet("notes", set).apply();
arrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
}
EditNote.java
public class EditNote extends AppCompatActivity implements TextWatcher{
int noteId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("Write a Note");
EditText editText = (EditText) findViewById(R.id.editText);
Intent i = getIntent();
noteId = i.getIntExtra("noteId", -1);
if (noteId != -1) {
editText.setText(MainActivity.notes.get(noteId));
}
editText.addTextChangedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.notes.set(noteId, String.valueOf(s));
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getSharedPreferences("mypackage", Context.MODE_PRIVATE);
if (MainActivity.set == null) {
MainActivity.set = new HashSet<String>();
} else {
MainActivity.set.clear();
}
MainActivity.set.addAll(MainActivity.notes);
sharedPreferences.edit().remove("notes").apply();
sharedPreferences.edit().putStringSet("notes", MainActivity.set).apply();
}
#Override
public void afterTextChanged(Editable s) {
}
}
You are currently using a built-in layout (android.R.layout.simple_list_item_1) for each item in your List View. It sounds like you want to customize this. So you need to create your own layout with a <TextView> with appropriate attributes, including
android:maxLines="1"
android:ellipsize="end"
Setting the maxLines to one and ellipsize to end is not going to work when you apply those settings to the ListView itself. Instead, you have a layout you are inflating for your ListView items. I am assuming that it contains a TextView since you want to have a single line with ellipsis instead of a TextView whose content grows vertically. Add these lines to the TextView within your List item layout. Again, this layout is the one you are inflating for each ListView item.
android:maxLines="1"
android:ellipsize="end"
You will then use this layout to create your adapter. Also note that you call setAdapter() twice, which is unnecessary.

Why does my listview only respond when it's text is clicked?

I have a custom listview. The problem is, however, the only part of the listview that is clickable is the text (nowhere to the right/ empty space). I have also added some of my java code.
This is the xml file I use in the arrayAdapter:
?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text"
android:maxLines="1"
android:ellipsize="end"
android:textSize="50sp">
</TextView>
MainActivity.java
public class MainActivity extends AppCompatActivity {
static ArrayList<String> note;
ListView listView;
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
static Set<String> set;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
setTitle("Notely");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notes.add("");
SharedPreferences sharedPreferences = getSharedPreferences("mypackage", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
} else {
set.clear();
}
set.addAll(notes);
arrayAdapter.notifyDataSetChanged();
sharedPreferences.edit().remove("notes").apply();
sharedPreferences.edit().putStringSet("notes", set).apply();
Intent i = new Intent(getApplicationContext(), EditNote.class);
i.putExtra("noteId", notes.size() - 1);
startActivity(i);
}
});
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences = this.getSharedPreferences("mypackage", Context.MODE_PRIVATE);
set = sharedPreferences.getStringSet("notes", null);
notes.clear();
if (set != null) {
notes.addAll(set);
} else {
notes.add("Example note");
set = new HashSet<String>();
set.addAll(notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
arrayAdapter = new ArrayAdapter(this, R.liststyle, notes);
listView.setAdapter(arrayAdapter);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), EditNote.class);
i.putExtra("noteId", position);
startActivity(i);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
notes.remove(position);
SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("mypackage", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
} else {
set.clear();
}
set.addAll(notes);
sharedPreferences.edit().remove("notes").apply();
sharedPreferences.edit().putStringSet("notes", set).apply();
arrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
}
To react to selections in the list, set an OnItemClickListener to your ListView. like below, for more about ListView
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
Hi you can use onItemclicklistener and if you look alternate solution then you can click on main layout on adapter.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
}
});
Set the TextView width to match_parent

Categories

Resources