I am new to android. I am developing an application in which there is a list view of students with edit and delete buttons. Like
STUDENT LIST
[ABC] [edit] [delete]
[DEF] [edit] [delete]
With this code im able to list student details in a <Textview>
public class DataBaseDemoActivity extends ListActivity {
/** Called when the activity is first created. */
SQLiteDatabase db;
Button btnInsert;
ArrayAdapter<String> students;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
db=openOrCreateDatabase("StudentDB",SQLiteDatabase.CREATE_IF_NECESSARY,null);
Cursor c=db.rawQuery("SELECT * FROM temp",null);
String[] students = new String[c.getCount()];
if (c.moveToFirst())
{
for (int i = 0; i < c.getCount(); i++)
{
students[i] = c.getString(0).toString()+" "+c.getString(1).toString();
c.moveToNext();
}
}
c.close();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, students));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}catch(SQLException e)
{
}
}
}
I need to store the id of the record with in the list view so that when i click on the edit or delete button, i'll have to find out the id and make changes on the DB. How can i set values to two fields say <TextView>[show details] and <EditText>[visibility: insisible - to save id of the record]. I am able to get the details to the <TextView> using the above code. Any suggestion will be appreciated.
UPDATE :
Layout i am using
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:inputType="text"
android:onClick="showInfo"
/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="230dip"
android:layout_height="wrap_content"
android:textSize="16sp"
android:id="#+id/studentInfo" >
</TextView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/action"
android:onClick="showInfo"
/>
</LinearLayout>
You can get the Id within cursor data fetch loop, use any HashMap<id,String> collection for it and store id along with data (text).
As per your requirement, I suggest you to use SimpleCursorAdapter instead of ArrayAdapter with ListView.
So you can manage easily your database records with your list and also get the all information related to database for particular record when List Item clicked.
Look at SimpleCursorAdapters and ListViews
Creating a custom CursorAdapter for Android
after this line..
students[i] = c.getString(0).toString()+" "+c.getString(1).toString();
student_ids[i]=Integer.parseInt(//get the id... )
//and you dont need to put it in invisible edittext...
in onclick method you will get integer "position"..and get tha value in students_ids[] at that position..
int id=students_ids[position];
Related
I have two ListView side by side in my activity and i want to only make it possible to select one item in one list at a time.
But right now if i select one item then one in the other list, the selections in both list are cleared, which is strange because when i check which listeners is called using logs everything seems to be working the way it should.
Also if i keep selecting different items at some point they start working like there was nothing in the listener because no list is cleared and i can select one item in each list. But i want to only be able to select one at a time so that's why i tried to reset the selection of the other ListView when you select an item in one of the two.
This code is at the end of the method where i initialize the ListViews.
selectedT1 and selectedT2 are initialized at -1
team1ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterV, View v, int position, long id) {
selectedPlayer = (String) adapterV.getItemAtPosition(position);
selectedT1 = position;
if(selectedT2 > -1){
team2ListView.clearChoices();
adapter2.notifyDataSetChanged();
selectedT2 = -1;
}
}
});
team2ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterV, View v, int position, long id) {
selectedPlayer = (String) adapterV.getItemAtPosition(position);
selectedT2 = position;
if(selectedT1 > -1){
team1ListView.clearChoices();
adapter1.notifyDataSetChanged();
selectedT1 = -1;
}
}
});
The xml of my listviews if it can help, they both are single choice and i have a button under them to validate the choice made but for that i need to be able to only select one of the items and not one in each list.
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_gravity="left"
android:layout_weight="0.5"
android:id="#+id/team1ListView"
android:layout_height="200dp"
android:choiceMode="singleChoice"
android:listSelector="#666666"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="0.5"
android:id="#+id/team2ListView"
android:choiceMode="singleChoice"
android:listSelector="#666666"/>
</LinearLayout>
Thanks for your time and help.
I have a Java class and two XML files which are basically just a side by side listView which takes in some values. I want to put a header or a text view above each list view ( they should stay side by side ) however every time I try to add a textView the whole project messes up and following online instructions is not working to implement a header.
public class Leaderboard extends AppCompatActivity {
private ListView UsernameList;
private ListView ScoreList;
LocalDatabase localDatabase;
/** Called when the activity is first created */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
ArrayAdapter<String> listAdapter;
ArrayAdapter<Integer> list2Adapter;
//Find the ListView resources
UsernameList = (ListView) findViewById(R.id.UsernameList);
ScoreList = (ListView) findViewById(R.id.ScoreList);
//Create and populate the list of usernames.
//This is where the information from the Database would need to be entered. and the String[] removed
String[] usernames = new String[]{"Andy", "Marie", "George"};
ArrayList<String> usernameList = new ArrayList<String>();
usernameList.addAll(Arrays.asList(usernames));
//Create and populate the list of scores
//This is where the information from the Database would need to be entered. and the Integer[] removed
Integer[] scores = new Integer[]{7, 4, 1};
ArrayList<Integer> scoreList = new ArrayList<Integer>();
scoreList.addAll(Arrays.asList(scores));
//adds the users details to the leaderboard
localDatabase = new LocalDatabase(this);
Contact contact = localDatabase.getLoggedInUser();
//Set a string to have the value of the users name.
String s = contact.name;
//Create Array Adapter using the username list
listAdapter = new ArrayAdapter<String>(this, R.layout.activity_row, usernameList);
//Add more users
listAdapter.add(s);
//Set the Array Adapter as the ListView's adapter
UsernameList.setAdapter(listAdapter);
//Create Array Adapter using the username list
list2Adapter = new ArrayAdapter<Integer>(this, R.layout.activity_row, scoreList);
//Add more users
list2Adapter.add(0);
//Set the Array Adapter as the ListView's adapter
ScoreList.setAdapter(list2Adapter);
}
}
Then the two xml files
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#color/colorPrimaryDark"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:textStyle="bold"
android:padding="10dp"
android:textSize="16sp">
</TextView>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:background="#color/colorPrimaryDark"
android:layout_height="fill_parent"
android:padding="20dp"
android:orientation="horizontal"
tools:context=".Leaderboard">
<ListView
android:id="#+id/UsernameList"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="2dp"
android:layout_weight=".60"
android:drawSelectorOnTop="false"
android:headerDividersEnabled="false">
</ListView>
<ListView
android:id="#+id/ScoreList"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="2dp"
android:layout_weight=".40">
</ListView>
</LinearLayout>
Try encapsulating the two TextViews in a LinearLayout. The linear Layout should span the entire width (match_parent), but only be as high as need be; wrap_content.
What you then want to do to have them neatly divided amongst the width of the screen, is, first off, set the LinearLayout orientation to horizontal. Then, you make the width of and both TextViews 0dp (that's right, 0dp), and their height wrap_content. Then, give both TextViews a weight of 1. The views now both take up half the space (in width) of the LinearLayout. Finally, centre the TextViews for a good looking header.
Ive kept it very broad and non-codey, but I think you should be able to google all the concepts explained above if you run into any trouble. If you really cant figure it out,i'll help you out in the comments.
I have an arraylist List<Cars> myCars = new ArrayList<Cars>(); My MainActivity layout has a listview and a button. There is one more layout ("each_car.xml") and its content is as below:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_carName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/tv_carMaker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
My Cars class has two fields,"name" and "manufacturer".
public class Cars{
String name;
String manufacturer;
}
I am populating this list(myCars) through an async-task. After the task is complete i.e. inside onPostExecute(), I am calling a method in my MainActivity which will populate a listview with the items in the list. Below is the method :-
public void populateListView(List<Cars> data){
ArrayAdapter<Cars> carAdapter = new CarAdapter(MainActivity.this, data);
ListView dataList = (ListView) findViewById(R.id.car_listView);
dataList.setAdapter(carAdapter);
}
Below is my CarAdapter class :-
public class CarAdapter extends ArrayAdapter<Cars>{
private LayoutInflater inflater;
List<Cars> dummyData = new ArrayList<Cars>();
MainActivity host;
public CarAdapter(MainActivity host, List<Cars> data)
{
super(host,R.layout.each_car,data);
inflater = host.getWindow().getLayoutInflater();
dummyData = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View itemView = convertView;
if(itemView == null)
{
itemView = inflater.inflate(R.layout.each_car,parent,false);
}
Cars currentData = dummyData.get(position);
Log.d("Testing Position","Position :- "+position);
TextView carName = (TextView) itemView.findViewById(R.id.tv_carName);
carName.setText(currentData.getName());
TextView carMaker = (TextView) itemView.findViewById(R.id.tv_carMaker);
carMaker.setText(currentData.getManufacturer());
return itemView;
}
}
This is filling out the listview with the entire List (myCars) at once.
Problem :- I want to populate the listView with one item at a time when I click the button.I am not sure how should I modify my code.
add one item in the list at a time when you click the button and call carAdapter.notifyDataSetChanged() .
create a button on main layout. Implement onclicklistener for the button and call populateListView() inside the onlick method.
Creat a new list. When you click a button add an item to a new list. call notifydatasetchanged(). When you click a button check whether the item is already added in the new list or not. Use newly created list in your adapter so that every time new item will be added.
I have a ListView that uses a custom adapter. Each element in the ListView contains a RadioButton and a TextView.
Here is my adapter, it takes an ArrayList of Employees (An object that currently only contains a name):
public class EmployeeAdapter extends ArrayAdapter<Employee> {
private ArrayList<Employee> listEmployees;
// Give the adapter the context and layout we are operating it, as well as a list of employees to put in the list.
public EmployeeAdapter(Context context, int layout, ArrayList<Employee> listEmployees) {
super(context, layout, listEmployees);
this.listEmployees = listEmployees;
}
// We override the basic getView function since our list is custom.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// If there is nothing left to put in the view, inflate the view in the rowemployee layout.
if (v == null){
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.rowemployees, null);
}
Employee i = listEmployees.get(position);
// Check if there's still an employee in the list.
if (i != null){
TextView name = (TextView) v.findViewById(R.id.text_employeename);
name.setText(i.getName());
}
// Alternate row colors.
if (position % 2 == 0) {
v.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else {
v.setBackgroundColor(Color.parseColor("#e5fff4"));
}
return v;
}
}
Here is the listview declaration in my XML layout:
<ListView android:id="#+id/employees_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="2dp"
android:paddingRight="1dp"
android:background="#drawable/borderlist"
android:choiceMode="singleChoice"
android:listSelector="#48ad82"
android:layout_below="#id/employees_header">
</ListView>
And here is the layout of every item of the ListView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/row_employee"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingTop="13dp"
android:paddingBottom="13dp"
android:descendantFocusability="blocksDescendants">
<RadioButton android:id="#+id/radio_employee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"/>
<TextView
android:id="#+id/text_employeename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_toRightOf="#id/radio_employee"
android:layout_marginTop="3dp"
android:layout_marginLeft="5dp"
android:focusable="false" />
</RelativeLayout>
I input a bunch of Employee objects into an ArrayList, which I push to the adapter, and then I set a setOnItemClickListener on the list. The listener contains this code:
OnItemClickListener onItemClickListener_employee
= new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Toast.makeText(getApplicationContext(), String.valueOf(view.isSelected()) , Toast.LENGTH_SHORT).show();
}
};
view.isSelected() always returns false. Why? I've been trying to figure out how to select an element on a list containing something else than just a TextView for a couple of hours, and the SDK documentation isn't very helpful, this is getting old.
When I press on the list's items, it seems like the TextView or the RadioButton get pressed instead. Shouldn't focusable="false" prevent this ( Android custom ListView unable to click on items )?
To get the item chosen, add the following method to your adapter (untested code):
public Employee getItemAt(int position){
return listEmployees.get(position);
}
Then in your handler, pass the position to the new adapter method above
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Employee e = adapter.getItemAt(position); //or whatever your adapter instance is named
Toast.makeText(getApplicationContext(), e.getName(), Toast.LENGTH_SHORT).show();
}
Since the view is just for displaying data, you really don't care about the view itself (unless you want to remove it, hilight it, etc).
Someone could tell me how can I create a ListView without using a ListActivity?
I need to put in my layout several other views, and I wish the layout was not fully occupied by the ListView. It must be part of the layout, not the entire layout. I want to create a normal Activity.
Code snippet:
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.savings);
//...
ListView lvPoupanca = (ListView)this.findViewById(R.id.lvPoupanca);
// the adapter
TestRepository repo = new TestRepository(this);
Cursor c = repo.getCursor();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[]{"Nome", "ValorAtual"}, new int[] {R.id.tvNome, R.id.tvValorTotal});
lvPoupancas.setAdapter(adapter);
// ...
}
Edit:
The saving.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvPoupancas"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
Hope somebody can help me.
Thanks and sorry about my bad english.
Like with any other View in any Activity...
ListView l = new ListView(this);
// OR
ListView l = (ListView) findViewById(R.id...);
...
l.setAdapter(...);
// If using first way: setContentView(l);
For example
I have replied to a similar question before. But that was in a different context. So, I'm putting some reference code here. It will help you to fix the issue.
public class ListandtextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] str = {"ONE","TWO","THREE"};
final ListView lv = (ListView) findViewById(R.id.listView1);
final TextView tv = (TextView)findViewById(R.id.tv1);
ArrayAdapter<Object> adapt = new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_list_item_1, str);
lv.setAdapter(adapt);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
tv.setText("You Clicked Something");
}
});
}
}
And the XML is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" android:textSize="20dip"/>
</LinearLayout>
By the way, before asking questions, collect as much information as possible for others to help you. If it does not work, it will be better to put the error log in the question rather than just saying it does not work.
Don't Extend ListActivity then. Extend an Activity and in onCreate() put the following code as per your requirement.
setContentView(R.layout.ur_xml);
Listview list = (ListView)findViewById(R.id.lvPoupancas);
list.setAdapter(your Adapter);