I have a listview. In it, each row had a text saying 0:00. But now, I added a button on my actionbar but then I got stuck. I don't know how to make the button create a new row, displaying 0:00
This is my code for the data in a row.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RowData rowdata_data[] = new RowData[]
{
new RowData("0:00")
};
RowdataAdapter adapter = new RowdataAdapter(this,
R.layout.listview_item_row, rowdata_data);
listView1.setAdapter(adapter);
listView1 = (ListView)findViewById(R.id.listView1);
}
this is my RowData class:
public class RowData {
String title;
public RowData(String title) {
this.title = title;
}
}
So how should I implement a button click to add another row?
Under addtionbutton: should be the method.
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle presses on the action bar items
switch (item.getItemId())
{
case R.id.additionbutton:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I don't know how to make the button create a new row
With your current solution it's not possible (in efficient way do it) because you're using static array of objects - it means array has fixed size (it means that you're assuming that size won't be changed at runtime).
But your goal is "slightly" different. You want after each click on Button increase number of objects by one. It means you don't know exactly how many rows you can have (or can be changed at runtime).
Due to things mentioned above you should (have to) use dynamic array with changeable size. For this reason you need to use as source of data List that is representation of dynamic array.
Basic algorithm:
Create new List with zero (or you can have by default one row at
start).
Then create public method in your adapter that will add new item to
collection and send request that Adapter should be refreshed (after you added new row into collection).
Assign OnClickListener to your Button and in onClick() method you'll use created method for adding new row into ListView.
Solution:
How to initialise ListAdapter:
// Activity-level variable scope
private List<RowData> items = new ArrayList<RowData>();
private RowdataAdapter adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView1 = (ListView)findViewById(R.id.listView1);
// adding first item to List, it's optional step
items.add(new RowData("0:00"));
adapter = new RowdataAdapter(this, R.layout.listview_item_row, items);
listView1.setAdapter(adapter);
}
Method for adding new row into ListAdapter:
public void addRow(RowData newRow) {
// items represents List<RowData> in your Adapter class
this.items.add(newRow);
// sends request to update ListAdapter
notifyDataSetChanged();
}
How to update Adapter after click on Button:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// add new row to Adapter
adapter.addRow(new RowData("0:00"));
}
});
Hope i helped you to solve your problem.
you need to create a dataset that you can change so you need to make your array a class wide variable so you can add to it when you need to
when you add the new row you need to notify the adapter that something changed so you do this
adapter.notifyDatasetChanged();
and that should update your list
Related
I am new to android and my code has got a bit messy. I have successfully created a list view extended from item_layout.xml. When I click on the list view It works exactly how I want it. However in each item of the list view I have a button that when clicked I want the item of the list to delete.
When researching I have come across that you need to create a customer adapter to do this however I have come so far in the project that I wouldn't even know where to start.
This code it used successfully to when the list items are clicked it works. This is just put in the Main Activity class
mylist.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
}
}
);
I populate the list using this function just outside the main activity class. It is needed to be written like this as It gets the items from a database and has to be called depending on different circumstances
private void populatelistView() {
Cursor res = userDb.getAllRows();
String[] fromFeildnames = new String[]{ DatabaseUser.KEY_1, DatabaseUser.KEY_2};
int[] toViewIds = new int[]{R.id.textViewNum, R.id.textViewItem};
SimpleCursorAdapter myCursorAdaptor;
myCursorAdaptor = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, res, fromFeildnames, toViewIds, 0);
//ListView mylist = (ListView) findViewById(R.id.listViewID);
mylist.setAdapter(myCursorAdaptor);
}
I would like to be able to get the button on each items to work by not changing much of what I have already written. I have tried just using the following code. But because it is in a different xml layout it display an error of null reference towards the item button
delete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
Toast.makeText(getApplicationContext(), "Button " + position, Toast.LENGTH_SHORT).show();
}
}
);
Please could someone help me make the button work without changing much code or give me a step by step tutorial on how to add an adapter but make my populateListView function do the same thing.
Ps. I have looked at so many tutorials about list adapters but can't find ones that are for my specific need
i don't know why but when i add items to listview i get only the last item. E.G. if i write apple and than pear i get only pear and not apple and pear.
Why?
CODE:
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("IDDD:"+iddd);
System.out.println("IDDD:"+video2.getPic());
//holder.lw.setA
String commento= (holder.tw.getText().toString());
// holder.lw.setAdapter(adapter);
ArrayList<String> arrayList= new ArrayList<String>();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrayList);
arrayList.add(commento);
// next thing you have to do is check if your adapter has changed
holder.lw.setAdapter(adapter);
adapter.notifyDataSetChanged();
System.out.println("LISTVIEW:"+arrayList);
}
});
in every click you decalre new list ArrayList<String> arrayList= new ArrayList<String>(); and it's false
you need to declate it out of the listener and in your listener just add the new items and use adapter.notifyDataSetChanged();
You are creating new list and adapter during every click so move the declaration and initialization of both, outside that function
Declare them outside getView(if Base or ArrayAdaoter) or createViewHolder (RecyclerAdapter)
initialize them inside constructor
add data to list and notify adapter
Better use view holder pattern in here where you use Existing instance of listview rather than recreating the new one all the time.
You don't need to do anything special, inside of onClick you need to get a reference to your ArrayAdapter and call the method add(T...) on it.
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("IDDD:"+iddd);
System.out.println("IDDD:"+video2.getPic());
String commento= (holder.tw.getText().toString());
ArrayAdapter adapter = (ArrayAdapter) holder.lw.getAdapter();
adapter.add(commento);
}
});
No need to even call notifyDataSetChanged because add already does that internally.
if you use this you can solve your problem
yourAdapter.(getCount()-1-position);
and this if you want to see the last items in front
public yourPoJo getItem(int position) {
return super.getItem(getCount()-1-position);
}
I am very sorry if this question already exists, but I couldn't find any answer to my problem. The idea of my application is a Shopping List. The user can see a list of food and on clicking on an item, it should automatically be added to a list.
What I already have is a ListView generated from an xml-file in a raw folder. This is my food, I haven't stored it in a SQLite Database.
What I want to do now is that when I click on an item in this list, it's added to a ListView in another Activity called "ShoppingList.java". It shouldn't open immediately, so the user has the possibility to add more items.
Now, when I click on an item, it's added to a TextView called "selection" in the same Activity on the top of the screen.
How is it possible to add an item from one Activity to another one?
Thank you very much for your help!
public class FishOk extends ListActivity {
TextView selection;
ArrayList<String> items=new ArrayList<String>();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.foodok_list);
selection=(TextView)findViewById(R.id.selection);
try {
InputStream in=getResources().openRawResource(R.raw.fish);
DocumentBuilder builder=DocumentBuilderFactory
.newInstance()
.newDocumentBuilder();
Document doc=builder.parse(in, null);
NodeList words=doc.getElementsByTagName("product");
for (int i=0;i<words.getLength();i++) {
items.add(((Element)words.item(i)).getAttribute("value"));
}
in.close();
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), 2000)
.show();
}
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lstView.setTextFilterEnabled(true);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items));
}
public void onListItemClick(ListView parent, View v, int position,
long id) {
selection.setText(items.get(position).toString());
}
public void onClick(View view) {
ListView lstView = getListView();
String itemsSelected = "Selected items: \n";
for (int i=0; i<lstView.getCount(); i++) {
if (lstView.isItemChecked(i)) {
itemsSelected += lstView.getItemAtPosition(i) + "\n";
}
}
Toast.makeText(this, itemsSelected, Toast.LENGTH_LONG).show();
}
Adding an item to the ListView of an Activity which isn't visible to the user and doesn't yet exist makes no sense. You should have a place where you'll store the data, it can be a SQLite database, a plain text file, or SharedPreferences if there's not much data. When you're clicking on a Button inside your current Activity you should store the information to your data storage, and then retrieve it to populate the ListView when the second Activity starts. Hope this helps.
Activity is a window where you can put your UI stuff so that user can interact with the application.
Now, for using the data in the activities across the application, you have to use either Collections or Database.
But as per your requirement, I think you should use Collections.
Maintain an Arraylist or a HashTable according to your data.
Pass that data from one activity to other.
OR
Maintain a singleton class and update the data in that class. Access the data from other activities.
I hope this helps you.
I am currently creating a basic news aggregator app for Android, I have so far managed to create multiple HorizontalListViews derived from this: http://www.dev-smart.com/archives/34
I am parsing all data from live JSON objects and arrays.
The process goes something like this:
1) Start app
2) Grab a JSON file which lists all feeds to display
3) Parse feed titles and article links, add each to an array
4) Get number of feeds from array and create individual HorizontalListView for each. i.e. "Irish Times".
5) Apply BaseAdapter "mAdapter" to each HorizontalListView during creation.
My baseadapter is responsible for populating my HorizontalListViews by getting each title and thumbnail.
My problem is however that all my feeds seem to contain the same articles and thumbnails. Now I am only new to Android so I'm not 100% sure whats going wrong here. See screenshot below.
Do I need to create a new BaseAdaptor for each HorizontalListview or can I use the same one to populate all my listviews with unique data.
Here's some code to help explain what I mean:
1) OnCreate method to get JSON data, parse it, get number of feeds and create each HorizontalListView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listviewdemo);
//--------------------JSON PARSE DATA------------------
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(sourcesUrl);
//Parse feed titles and article list
getFeeds(json);
//Create Listviews
for(int i = 0; i < feedTitle.size()-1; i++){
//getArticleImage(i);
addHorzListView(i);
articleArrayCount++;//Used to mark feed count for adaptor to know which array position to look at and retrieve data from.
//Each array position i.e. [1] represents a HorizontalListview and its related articles
}
}
2) addHorzListView method, used to create HorizontalListView and apply adaptor
//Method used to dynamically add HorizontalListViews
public void addHorzListView(int count){
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);
View view = getLayoutInflater().inflate(R.layout.listview, mainLayout,false);
//Set lists header name
TextView header = (TextView) view.findViewById(R.id.header);
header.setText(feedTitle.get(count));
//Create individual listview
HorizontalListView listview = (HorizontalListView) view.findViewById(R.id.listviewReuse);
listview.setAdapter(mAdapter);
//add listview to array list
listviewList.add(listview);
mainLayout.addView(view, count);
}
3) Baseadaptor itself:
private BaseAdapter mAdapter = new BaseAdapter() {
private OnClickListener mOnButtonClicked = new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(HorizontalListViewDemo.this);
builder.setMessage("hello from " + v);
builder.setPositiveButton("Cool", null);
builder.show();
}
};
#Override
public int getCount() {
return noOfArticles.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
//Each listview is populated with data here
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewitem, null);
TextView title = (TextView) retval.findViewById(R.id.title);
title.setText(getArticleTitle(position));
new DownloadImageTask((ImageView) retval.findViewById(R.id.ImageView01)) .execute(getArticleImage(position));
Button button = (Button) retval.findViewById(R.id.clickbutton);
button.setOnClickListener(mOnButtonClicked);
return retval;
}
};
The adapter mAdapter is currently displaying the articles from the last HorizontalListView that calls it.
Currently I am using the same BaseAdaptor for each ListView as I figured it populated the listview as soon as its called but i looks as though a BaseAdaptor can only be called once, I really dont know.
I want to dynamically populate feeds though without having to create a new Adaptor manually for each HorizontalListView.
Any help would be much appreciated.
So...you got the same info in 4 listview, right? In that case you only need oneAdapter populating 4 listview.
An adapter just provide the views which are visible in that moment to the listview (if it is implemented in the right way) so you can reuse the adapter if the info contained is the same.
I've had a look around, and it might be because I'm not sure what I'm looking for, but I can't find out how to do something I presume should be quite easy with android.
I have an array of data to display on the screen. This data is a class that holds a database key, name and image.
I'm currently displaying this data as an ImageView and a TextView. I loop through the array and add a new row to a TableLayout containing the image and text.
I'd like both the image and text to be clickable, changing to a new activity.
This new activity needs to know the database key of the row clicked in order to display the correct data.
Here's what I have so far:
private void fillSuggestionTable(TableLayout tabSuggestions, Suggestion[] arrToAdd)
{
for(int i = 0; i < arrToAdd.length; i++)
{
/* Create a new row to be added. */
TableRow trSuggestion = new TableRow(this);
trSuggestion.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
/* Create objects for the row-content. */
ImageView imgDisplayPicture = new ImageView(this);
ImageHandler.loadBitmap(arrToAdd[i].strImageURL, imgDisplayPicture);
imgDisplayPicture.setLayoutParams(new LayoutParams(50,50));
TextView txtArtistName = new TextView(this);
txtArtistName.setText(arrToAdd[i].strName);
txtArtistName.setTextColor(Color.parseColor("#000000"));
/* Add data to row. */
trSuggestion.addView(imgDisplayPicture);
trSuggestion.addView(txtArtistName);
/* Add row to TableLayout. */
tabSuggestions.addView(trSuggestion, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
}
Is there a reason you're using a TableView? it seems like what you want to accomplish would be much easier with a ListView & custom CursorAdapter, where the adapter can handle translating from the database to the ListView row. At that point starting a new activity that knows the database ID is trivial:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MyActivity.this, MyOtherActivity.class);
i.putExtra("database_id", id);
startActivity(i);
}
});
And in MyOtherActivity:
private int dbId;
protected void onCreate(Bundle savedInstanceState) {
//do stuff
dbId = getIntent().getIntExtra("database_id", -1); // the -1 is the default if the extra can't be found
}
To pass extra data to another Activity, you need to add extra information with the Intent.putExtra(name, value) methods.
For example, to send the Intent:
Intent i = new Intent([pass info about next Activity here]);
i.putExtra("databaseKey", databaseKey);
startActivity(i);
To get the data out again:
public void onCreate(Bundle savedInstance)
{
// Do all initial setup here
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("databaseKey"))
{
int databaseKey = extras.getInt("databaseKey");
// Load database info
}
else
{
// No data was passed, do something else
}
}
EDIT: To find out when the table's row is clicked, you'll need to implement View.OnClickListener and set the onClickListener for the TableRows you use.
For example:
/* Create a new row to be added. */
TableRow trSuggestion = new TableRow(this);
trSuggestion.setOnClickListener([listener]);
The only problem you'll have is relating a View's ID to the related database row ID. A HashMap should help.
This is a pretty simple procedure. This blog explains it in simple terms.