Unexpected Behaviour in ListView [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am new to Android programming. I intend to make a shopping List using a ListView such that the user can strike through items on the list that he has bought. it should be such that
List is made.
He can strike through items bought.
He can add items using the EditText and the Add button at the bottom of the layout.
List is rendered after adding items like on point 3 with the stroke through items maintained.
On starting I click for many of the initial items I added in my program to have a stroke through and then I start adding items, I get an unexpected behaviour in the List. Some of the newly added items get a stroke through after I click ADD right from the outset when I havent even clicked for them to have a stroke through. Some of them dont. I dont understand this behaviour. Is it because of some property of ListView?
ArrayList<String> shoppingList = new ArrayList<>();;
ArrayList<String> strikeThroughList = null;
ArrayList<String> strikeThroughText = null;
ArrayAdapter<String> adapter = null;
ListView lv = null;
Button addBtn=null;
EditText addEdtTxt=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn=findViewById(R.id.addBtn);
addBtn.setOnClickListener(this::btnClick);
//shoppingList = new ArrayList<>();
strikeThroughList = new ArrayList<>();
strikeThroughText= new ArrayList<>();
//One way to populate List
Collections.addAll(shoppingList, "Eggs", "Yogurt", "Milk", "Bananas", "Apples", "Tide with bleach", "Cascade");
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, shoppingList);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mnu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.clrList)
{
shoppingList.clear();
lv.setAdapter(adapter);
}
return super.onOptionsItemSelected(item);
}
public void btnClick(View view) {
if(view.getId()==R.id.addBtn){ addEdtTxt=findViewById(R.id.addEdtTxt);
adapter.add(addEdtTxt.getText().toString());
adapter.notifyDataSetChanged();
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
TextView text = (TextView) view;
text.setPaintFlags(text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}

Try to with below code change while adding Views to strikeThroughView list.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//String selectedFromList = (String)(lv.getItemAtPosition(position));
TextView text = (TextView) view;
text.setPaintFlags(text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
text.setId(2);
strikeThroughView.add(text);
}

Related

Items in Spinner visible but onItemSelected Not Working

I am a beginner in Android. I have a spinner in my android code. It takes values from room database and once selected the value will be added to the listview. I have two issues
a) I am seeing values in my Spinner. But I am not able to select it and also onItemSelected for this spinner is not working
b) I would like to add a delete icon in my list view along with these values so that if the user is not interested in the value he can delete it.
Please can someone help me to resolve this?
Code is provided below:
public class MainActivity extends AppCompatActivity
{
private List<String> tasks = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private ListView consultantsList;
private Spinner spinner;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
consultantsRepository consrepo =
new consultantsRepository (getApplicationContext());
ArrayList<String> oncons = consrepo.getConsultants();
ArrayAdapter<String> consarrayadapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
oncons);
adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,tasks);
ListView consultantsList = (ListView) findViewById(R.id.ListToSend);
consultantsList.setAdapter(adapter);
spinner = (Spinner) findViewById(R.id.consSpinner);
spinner.setAdapter(consarrayadapter);
consarrayadapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener
(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected
(AdapterView<?> parent, View view, int position, long id)
{
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), item,
Toast.LENGTH_LONG).show();
tasks.add(item);
adapter.notifyDataSetChanged();
}
});
}
}
try-
String item=spinner.getSelectedItem().toString();

CursorAdapter changed style of SwipeMenuListView after scroll

I'm trying to develop an app to record debts in which I have a SwipeMenuListView from this github https://github.com/baoyongzhang/SwipeMenuListView for adding a swipe menu. Using a custom CursorAdapter, I populate the ListView with the name and total debt.
Now, I want to group each listview items depending on the due date. I've created a new column on my SQLite to add a header for each day. Now I just need to use different style for header and items of the ListView. By detecting the new column from bindView and depending on if it's a header or items, it will change, hide and show elements from the same layout.
The problem is that when I scroll the ListView, some of the listview items changed style. It get worse if I keep scrolling up and down. Here's the picture of the error from the listview. Notice that it's all in one session, the header style seems to have been used in some of the items and the header itself changed to red color which suppose to be color code for the items. If I click one of the item, it still get the correct item so I figure its a problem within the cursorAdapter but I just can't figure it out. It is not a mistake in the SQL database which I have checked.
Here's the cursorAdapter.
public class DebtCursorAdapterMain extends CursorAdapter {
public DebtCursorAdapterMain(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.debt_list_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
int x = Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.DATE_SEPARATOR_COLUMN)));
TextView tvName = (TextView) view.findViewById(R.id.tvName);
TextView tvTotal = (TextView) view.findViewById(R.id.tvTotal);
if(x == 0) {
DecimalFormat df = new DecimalFormat("#.00");
String nameText = cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COLUMN));
String totalText = "$ " + df.format(cursor.getDouble(cursor.getColumnIndex(DBHelper.TOTAL_COLUMN)));
String type = cursor.getString(cursor.getColumnIndex(DBHelper.TYPE_COLUMN));
if (tvName != null)
tvName.setText(nameText);
if (tvTotal != null)
tvTotal.setText(totalText);
if (type.equals("L"))
view.setBackgroundColor(Color.parseColor("#ff9999"));
if (type.equals("B"))
view.setBackgroundColor(Color.parseColor("#99ff99"));
}
if(x == 1){
String date = cursor.getString(cursor.getColumnIndex(DBHelper.DUE_DATE_COLUMN));
if (tvName != null && tvTotal != null) {
tvName.setText(date);
tvName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
tvTotal.setVisibility(View.GONE);
}
}
}
}
Here is the main activity in which the cursorAdapter is called.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find SwipeMenuListView
final SwipeMenuListView swipeMenuList = (SwipeMenuListView) findViewById(R.id.swipeMenuList);
// Create Debt database cursor adapter
cursorAdapter = new DebtCursorAdapterMain(this, null, 0);
// Create SwipeMenuList and set item
SwipeMenuCreator creator = createMainActivitySwipeMenu();
swipeMenuList.setMenuCreator(creator);
swipeMenuList.setAdapter(cursorAdapter);
swipeMenuList.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
// Set SwipeMenuList on item's menu click
swipeMenuList.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
....
}
});
// Swipe menu on Click function
swipeMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
....
}
});
// Initialize cursor and check database for updating top info
getLoaderManager().initLoader(0, null, this);
checkDataBase();
}
I'm still new in android development so please tell me if there's a better approach to this problem. Thanks guys.

Clicked drop-down item in AutoCompleteTextView does not respond on the first click

My app implements a HashMap, such that when a key is typed in the AutoCompleteTextView editText, and user clicks a dropdown item, the value gets displayed on a textView.
The only problem is that the clicked drop-down item does not respond on the first click (this only happens once, after the app is launched but works fine subsequently), the user MUST re-type a key and click the item before it displays the value.
Any suggestions as to how to resolve this?
Java code:
public class MainActivity extends ActionBarActivity
{
Map<String, String> map = new HashMap<String, String>();
private EditText autocomplete_searchField;
private TextView displayField;
String note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autocomplete_searchField = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);
// Gets a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);
// Gets the string array
String[] musicNote = getResources().getStringArray(R.array.music_notes_array);
// Creates the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, musicNote);
textView.setAdapter(adapter);
displayField = (TextView) findViewById(R.id.displayField);
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
displayField.setText(map.get(adapterView.getItemAtPosition(position).toString()));
String note = autocomplete_searchField.getText().toString();
displayField.setText(map.get(note));
map.put("Doe", "a deer, a female deer");
map.put("Ray", "a drop of golden sun");
}
Most of the related solutions I've seen treat buttons, but not AutoCompleteTextView drop-down items. I've also tried setting focus both in my JAVA and XML but those didn't resolve the issue.
I didn't understand very well what you are trying to do, but looking in your code, I saw a couple of wrong things in it. Perhaps it is the problem. Moreover I added some lines into your code, so the here is it:
public class MainActivity extends ActionBarActivity {
private Map<String, String> map = new HashMap<String, String>();
private AutoCompleteTextView autocomplete_searchField;
private TextView displayField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autocomplete_searchField = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);
displayField = (TextView) findViewById(R.id.displayField);
// Gets the string array
String[] musicNote = getResources().getStringArray(R.array.music_notes_array);
// Creates the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, musicNote);
autocomplete_searchField.setAdapter(adapter);
autocomplete_searchField.setThreshold(1);
autocomplete_searchField.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
autocomplete_searchField.showDropDown();
}
});
autocomplete_searchField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
displayField.setText(map.get(adapterView.getItemAtPosition(position).toString()));
}
}
}
}
Test it before do any change in order to realize if the issue was fixed. Then you do whatever you wanna do ;)

Click on list item of a ListView doesn't respond

I am implementing ListView in my code. But When I click on the items, it does not respond respond to the click in any way. Could someone help me please? Thanks in advance .
Here is the code .
public class ListaActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.provacomunicazione.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lsta);
Resources res = getResources();
String[] Authors = res.getStringArray(R.array.Lista_Nomi_E_Cognomi_Autori);
ArrayList<String> Autori = new ArrayList<String>();
for (String temp:Authors) {
Autori.add(temp);
}
Collections.sort(Autori);
ArrayList<String> AutoriLetteraSelezionata = new ArrayList<String>();
for (String temp:Autori) {
if (temp.charAt(0)=='A') {
AutoriLetteraSelezionata.add(temp);
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.textviewitem, AutoriLetteraSelezionata);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setClickable(true);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CharSequence autore = "("+((TextView)view).getText()+")";
Intent i = new Intent(ListaActivity.this, SecondaryActivity.class);
i.putExtra(EXTRA_MESSAGE, autore);
startActivity(i);
});
}
}
You should define on all of the child objects in the item listview (TextView, ImageView etc.):
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
And for the root item RelativeLayout / LinearLayout and so, define:
android:clickable="false"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false"
If you won't define those, they will "catch" the click event.
And if you have a Custom listView adapter, just check that you override:
#Override
public boolean isEnabled(int position)
{
return true;
}
In my case a problem was in fact that a ListView contained HorizontalScrollViews.
HSV consumes clicks over items and doesn't return OnItemClick to the ListView.
I solved the problem when wrote an OnClickListener inside an adapter that returns a callback to the ListView. See here: https://stackoverflow.com/a/43653085/2914140.
In the customer Item,
set every element
android:clickable="true"
android:focusable="false"
works for me

how to get text from a selected item on a list and set that text in a TextView?

I have created a list. And I need to get the text on the list item, when it is clicked. Then that text need to be set in a TextView. Following is my code and i get a force stop when I run it. Please give some ideas.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtTask = (EditText)findViewById(R.id.txtTask);
btnAdd = (Button)findViewById(R.id.btnAddTask);
selectedTask = (TextView)findViewById(R.id.textViewTask);
list = getListView();
list.setTextFilterEnabled(true);
btnAdd.setOnClickListener(this);
list.setOnKeyListener(this);
toDoItems = new ArrayList<String>();
oo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, toDoItems);
list.setAdapter(oo);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id3) {
int tmp = list.getSelectedItemPosition();
String v= toDoItems.get(tmp).toString();
selectedTask.setTag(v);
flippy.showNext();
}
});
}
Replace below 3 lines of your code in onItemClick method with my suggested code.
int tmp = list.getSelectedItemPosition();
String v= toDoItems.get(tmp).toString();
selectedTask.setTag(v);
Suggested Code
String v= toDoItems[position]; // or
String v = list.getItemAtPosition(position).toString();
selectedTask.setText(v);
After you have got the string v, you need to put the following line :
selectedTask.setText(v);
Also there is no need to put list.setOnKeyListener(this); since you need to listen for the item being clicked.

Categories

Resources