Android footer with onclickListener - android

I've setup a footer to my list view, next I'm setting up an onclicklistener to it that will play a sound and then go to my next activity but having trouble getting the onclicklistener working for the footer. I've successful done it to other activites but this one is giving me trouble I'm hoping to post the code and someone can explain what I'm doing wrong. I've tried every fix I've found online but nothing seems to work.
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class editpage extends ListActivity {
//editCount still unused at time but will grab data inputted into edittext fields
int editCount;
private dbadapter mydbhelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_list);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
private void fillData() {
Cursor e = mydbhelper.getUserWord();
startManagingCursor(e);
// Create an array to specify the fields we want to display in the list
String[] from = new String[] {dbadapter.KEY_USERWORD,};
// an array of the views that we want to bind those fields to
int[] to = new int[] {R.id.textType,};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter editadapter =
new SimpleCursorAdapter(this, R.layout.edit_row, e, from, to);
ListView list = getListView();
View footer = getLayoutInflater().inflate(R.layout.footer_layout, list, false);
list.addFooterView(footer);
setListAdapter(editadapter);
//still not used, need to get onclicklistener working since this will be used to send data to next activity
editCount = e.getCount();
}
public void onClick(View footer){
final MediaPlayer editClickSound = MediaPlayer.create(this, R.raw.button50);
editClickSound.start();
};
//This should not be needed since clicking on items in list view will not have a function but read someone to put my footer onclick in here but didn't work for me
#Override
protected void onListItemClick(ListView list, View v, int position, long id)
{
super.onListItemClick(list, v, position, id);
//final Intent intent = new Intent(this, title.class);
//startActivityForResult(intent, position);
}
TY in advance, btw if I take out the onclicklistener my page displays with the footer but can't move forward with program without getting this step fixed

if you're defining the button in XML, add android:onClick="onClick" to it

Related

How to disable a single row and change its background color in a listview, without a button (or a method if possible)?

The title of this post says it all.
This code works without any problems:
package abc.AvailableCars;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class carListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.car_list_layout);
final ListView carListview = (ListView) findViewById(R.id.list_view);
final Button dButton = (Button) findViewById(R.id.disable_button);
String[] cars = {"Maxima GXE", "Passat", "Focus SE", "Mazda6", "Avalon", :Sentra GXE"};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
carListview.setAdapter(arrayAdapter);
dButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int chosenRow = 3;
carListview.getChildAt(3).setEnabled(false);
carListview.getChildAt(3).setBackgroundColor(Color.parseColor("#3f51b5"));
}
});
}
}
This is in my listview .xml file:
<Button
android:id="#+id/disable_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable A Row"
/>
But, when I comment-out everything that belongs to the button, like below, and the Car List class is called, the app crashes with the error in the Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setEnabled(boolean)' on a null object reference:
final ListView carListview = (ListView) findViewById(R.id.list_view);
//final Button dButton = (Button) findViewById(R.id.disable_button);
String[] cars = {"Maxima GXE", "Passat", "Focus SE", "Mazda6", "Avalon"};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
carListview.setAdapter(arrayAdapter);
//dButton.setOnClickListener(new View.OnClickListener() {
//#Override
//public void onClick(View v) {
int chosenRow = 3;
carListview.getChildAt(chosenRow).setEnabled(false);
carListview.getChildAt(chosenRow).setBackgroundColor(Color.parseColor("#3f51b5"));
}
//});
}
//}
I'm not an Android newbie anymore, but this is eluding me.
I want the chosen row to be disabled and the color set as soon as the listview is shown.
How can I do this programmatically without a button?
I have tried every variation I can think of, getView(), even a fake click.
Just in case it makes a difference, this code is in a separate class and file than the MainActivity.java file, and is called in that file.
There has to be a simple answer. What do I need to change?
Please be verbose.
Thank you.
You are calling carListview.getChildAt(chosenRow) when you set up your list view, in onCreate. Your list view is not ready yet. Try moving this code to your onResume - should look something like this:
#Override
public void onResume(){
super.onResume();
arrayAdapter.notifyDataSetChanged();
int chosenRow = 3;
carListview.getChildAt(chosenRow).setEnabled(false);
carListview.getChildAt(chosenRow).setBackgroundColor(Color.parseColor("#3f51b5"));
}
This is a pretty simple case - your chosenRow number is generated by you. You might need a custom Adapter if you need it to be algorithmic or user-driven. Have a look at this tutorial.
From my understanding, since listViews are views, they have to be Overridden for some things to be changed in them.
I chose not to disable the required rows, but check for them in code.
The complete code that works is below.
Some credit goes to Raghunandan for his/her answer at-
Android - Change background color of specific item of ListView
Again, sorry, but the indentation of the code wouldn't work correctly for some reason.
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CarListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.car_list_layout);
final ListView carListview = (ListView) findViewById(R.id.list_view);
String[] cars = {"European Cars:", "Mercedes", "Passat", "Bently", "Porsche", "BMW", "Yugo","Land Rover",
"Japanese Cars:", "Maxima GXE", "Mazda6", "Avalon", "Toyota", "Honda", ""};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
//------------------------------------------
carListview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_of_cars) {
// Since listViews are views, they have to be Overrdden for some things to be changed in them.
#Override
public View getView(int rowPosition, View convertView, ViewGroup parent) {
View row = super.getView(rowPosition, convertView, parent);
//------------------------------------------
// This works. I have only tried this for two rows, the two I wanted. I expected this line to crash the app, but it didn't.
if(getItem(rowPosition).equals("European Cars:") || getItem(rowPosition).equals("Japanese Cars:")) {
// Make the two rows have a white background color.
row.setBackgroundColor(Color.WHITE); // this command WORKS fine by itself.
// row.setEnabled(false); this command caused "bleeding" over into other rows, so I will check for the rows in a condition.
} // both of the getItems end here.
else {
// All of the other rows should have this color.
row.setBackgroundColor(Color.parseColor("#EEE8AA"));
// the default color
} // else ends here.
//------------------------------------------
return row;
//------------------------------------------
} // getView ends here.
}); // carListview.setAdapter ends here.
} // onCreate ends here.
} // CarListActivity ends here.
Thanks, and I hope this helps others.

Dynamic List app add button not working

I wrote an exercise android app which consists of a text entry, an add button, and a dynamic list. Users are supposed to be able to type a string into the text entry, click on add button, and add it to the list. However, when I run this script on the emulator, nothing happens when I click on the add button. Checking the logcat doesn't help, because no logs appear when clicking on the button either. I also tried adding a breakpoint, but, again, nothing happens when I try to step over. Can someone help me on this please? I'd greatly appreciate it. Thanks.
package p.listviewexerice2;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button bt;
EditText et;
ListView lv;
ArrayAdapter<String> adapter;
ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.button);
et = (EditText) findViewById(R.id.editText);
lv = (ListView) findViewById(R.id.listView);
list = new ArrayList<>();
list.add("x");
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(getBaseContext(),list.get(position),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClick(View v){
if(v==bt){
String name = et.getText().toString();
if(name.isEmpty()){
Toast.makeText(getBaseContext(),"Empty entry",Toast.LENGTH_SHORT).show();
}
else{
list.add(name);
adapter.notifyDataSetChanged();
}
}
}
}
Can you delete lv.setOnItem.. code block and try again ?
Because you have already implements from onClickListener, so your button call the method onClick()
Instead of this:
list.add(name);
Do this:
adapter.add(name);
Explanation: you create the adapter with parameter list, allright. But since then adapter manages it's own internal list. Adapter also has built-in methods "add()" and "remove()", to manage that internal list.
Your code is almost fine, just 1 thing is missing. You have not registered the click event for your button bt. And without registering the click event the system will not be able to execute the code for onClick(View v).
so just add the below code in your onCreate()
bt.setOnClickListener(this);

How to populate Contacts from Phone to Custom Listview?

I created a Custom ListView using BaseAdapter now I want to populate this Listview with Contact Name and Number from Phone book..I am trying this..
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Rabtaye extends Activity {
ListView msgList;
ArrayList<MessageDetails> details;
AdapterView.AdapterContextMenuInfo info;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
msgList = (ListView) findViewById(R.id.MessageList);
details = new ArrayList<MessageDetails>();
MessageDetails Detail = new MessageDetails();
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
startManagingCursor(cursor);
String info[] = { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID };
for(String a:info){
Detail.setName(a);
}
Detail.setNumber("0313");
details.add(Detail);
// int to[] = { R.id.name, R.id.number };
// ListAdapter cursada = new SimpleCursorAdapter(this,
// android.R.layout.simple_expandable_list_item_2, cursor, info,
// to);
msgList.setAdapter(new CustomAdapter(details, this));
msgList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView s = (TextView) arg1.findViewById(R.id.name);
String abc = s.getText().toString();
Toast.makeText(Rabtaye.this, abc, Toast.LENGTH_LONG).show();
}
});
}
}
I used different ways, but I am not able to populate ListView with Contact Name or Number. In this code I have to statically add name and number...I am quite confuse here..little help would be greatly appreciated. Thanks in Advance. I am newbie so please go easy on me..:)
Hmmm. You're on the right track, but I think you're wandering a bit.
A ListView is a view object, not a BaseAdapter. As far as I can tell from your code, you don't need a custom adapter for your ListView.
What you should do is bind a regular CursorAdapter to your ListView, load the Contacts data you want from the Contacts Provider using a CursorLoader, then move the resulting Cursor to the CursorAdapter.
You can find the instructions for doing this in this Android training class:
Loading Data in the Background.
What do you want in your custom ListView that you can't get from ListView itself?
If you're putting more than just a single list of items into a ListView (it looks like you're doing name, number, etc.) you have to create your own custom adapter. Extend the BaseAdapter class either in your activity, or in a new class. Then you'll have to override the getView() method. This is what is called every time a new item gets inflated.
You pass your ArrayList into the BaseAdapter when you create it. The getView() method of the adapter is where you code your logic to take the data and present it as a list item. You'll have to define a new XML file as a layout for each list item that contains your TextViews and whatnot for your different children in each list item, and that's what you populate with your data.
There are a bunch of examples all over if you search for "baseadapter". Here's one that gives a pretty good intro.

(Pre)select checkboxes in a ListActivity using 'simple_list_item_checked'

I'm using the ListActivity class in conjunction with the simple_list_item_checked-layout which implements simple list items with checkboxes. Everything is working fine - clicking added items calls onListItemClick() and I can check/uncheck respective checkboxes of entries via the 'View v' parameter.
However what I wasn't able to figure out yet is, how to (pre)select checkboxes without any userinteraction?
Minimal so far working code snippet showing my intend:
package org.test;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
public class TestActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked);
list_elems.add("foobar");
//TODO: check added entry labeled "foobar"
setListAdapter(list_elems);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
CheckedTextView check = (CheckedTextView)v;
check.setChecked(!check.isChecked());
}
}
Thanks a lot in advance!
daten
This works for me:
You have to set the choicemode of the underlying ListView to single or multiple.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, Android.R.layout.simple_list_item_checked);
list_elems.add("foobar");
//TODO: check added entry labeled "foobar"
setListAdapter(list_elems);
ListView lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setItemChecked(0, true);
}
Use a SimpleListAdapter as the ListAdapter for your ListActivity. Use two columns (one for your string and the other for the checked value), and the system should take care of it by itself. Here is a good example

Dynamically add items in list view

I want to make a dynamic list view which gets the user credentials when I login for the first time and displays it in a list the next time I start the app. I know how to send the username from one intent to another. i haven't focused on the SQLite part yet, will do that later. I'm facing problems in creating the dynamic list view.
Found one very useful thread - Dynamically add elements to a listView Android
he used a button on the screen and called the method onClick to populate the list. Can i do it without the button? I want it to automatically happen once i am able to login.
how can i use the statements in my code?
listItems.add(value);
adapter.notifyDataSetChanged();
here value is the username i am getting from some other intent.
please help. thanks!
For this Just use the example given below:
For Instance you are Adding Some Strings into your List
So Create a ListArray like this
ArrayList<String> listItems = new ArrayList<String>();
now whenever you want to add certain string into list just do this thing
EditText editText = (EditText) findViewById(R.id.edit);
listItems.add("my string"); OR
listItems.add(editText.getText.toString()); //incase if you are getting string value from editText and adding it into the list
Use this Xml inside your linear layout in main.xml
<EditText android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Now when you have added one item dynamically then call this
adapter.notifyDataSetChanged();
The above will update your list and display the upadted list.
For more info about this see the following links:
http://www.androidpeople.com/android-custom-listview-tutorial-part-1
http://www.androidpeople.com/android-custom-listview-tutorial-part-2
http://www.androidpeople.com/android-custom-dynamic-listview-%E2%80%93part3
In these tutorials you can replace String[] with ArrayList as given at the top of the answer ook and when you want to add any item just simply use the second code snippet.
Thanks
sHaH
The best way to do this will be to use ArrayAdapter. When modifying the adapter it automatically refresh itself so you don't have to call notifyDataSetChanged.
You can try out this code to add elements dynamically to list view.
You can do it with out button click also.
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
//step2 : create all the variables.
EditText et;
Button b;
ListView lv;
ArrayList<string> al;
ArrayAdapter<string> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//step3 : intitalize all the variables.
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
lv = (ListView) findViewById(R.id.listView1);
al = new ArrayList<string>();//initialize array list
aa = new ArrayAdapter<string>(this,
android.R.layout.simple_list_item_1,
al);//step4 : establish communication bw arraylist and adapter
//step5 : establish communication bw adapter and dest (listview)
lv.setAdapter(aa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent,
View v, int arg2,
long arg3) {
String item = al.get(arg2);
Toast.makeText(getApplicationContext(), item, 0).show();
}
});
//step6 : button click logic
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//step i: take text from et and add to arraylist
String item = et.getText().toString();
al.add(0, item);
//step ii: notify to adapter
aa.notifyDataSetChanged();
//step iii: clr edit text
et.setText("");
}
});
}
}
For complete code check this list view example

Categories

Resources