Each ListView item opens layout with different text - java

How my onClickListener should look like if I need to open layout with different text for each ListView item and I have a lot of ListView items (about 50)? Do I need to create new activity or layout file for each new item? Is it possible to use one activity for all items?
This is my MainActivity.java:
public class MainActivity extends Activity {
// ListView
private ListView listView;
// Adapter
ArrayAdapter<String> adapter;
String items [];
// ArrayList
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ListView data in res/values/arrays.xml
items =getResources().getStringArray(R.array.items);
listView = (ListView) findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.listItem, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
/*
I know that I can put here I can put something like this:
case 0 :Intent appInfo = new Intent(About.this, Activity1.class);
startActivity(appInfo);
break;
case 1 :Intent appInfo = new Intent(About.this, Activity2.class);
startActivity(appInfo);
break;
case 2 :Intent appInfo = new Intent(About.this, Activity3.class);
startActivity(appInfo);
break;
BUT DO I NEED REPEAT THIS MORE THAN 20 TIMES?!
*/
}
});
}
}
Some system apps like Settings has a lot of ListView and layouts and I don't believe that it has new activity for each layout.

Create a new single activity and pass the text to that activity.
Something like:
Intent intent = new Intent(About.this, <NEW_ACTIVITY>.class);
intent.putExtra("text_key", items[position]);
startActivity(intent);
on the other activity, retrieve the text like this (can be on the onCreate method):
String text = getIntent().getExtras().getString("text_key");

Related

ListView will refresh already existing item and won't add a new one

I am trying to make a To Do List app and I have an EditText field where I enter the task. When I press the "add" floating action button the first task goes in the listview perfectly but when I try to add a second task, it will change the first task to the second and so on. So the thing is that I can only have on task at a time but what I want to have is a list of tasks.
This is my onCreate method, where I declare the floating action button and set an OnClickListener for it:
DBHelper dbHelper;
ArrayAdapter<String> mAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
// Finds you button from the xml layout file
FloatingActionButton faButton = (FloatingActionButton) findViewById(R.id.fab);
// Waits for you to click the button
faButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Starts the function below
addNotification();
listView.setAdapter(mAdapter);
addToDoElement(null);
}
});
listView = (ListView)findViewById(R.id.lstTask);
}
And this is the method that adds the task from the EditText to the ListView
ArrayList<String> taskList;
public void addToDoElement(View view) {
listView = (ListView) findViewById(R.id.lstTask);
taskList = new ArrayList<>();
mAdapter = new ArrayAdapter<String>(this, R.layout.row, R.id.task_title, taskList);
listView.setAdapter(mAdapter);
//Gets TASK text from EditText
EditText mEdit = (EditText)findViewById(R.id.titlu);
Log.v("EditText", mEdit.getText().toString());
taskList.add(mEdit.getText().toString());
mEdit.setText("");
mAdapter.notifyDataSetChanged();
}
The part where you initialize your taskList and mAdapter needs to be done only once, in your onCreate method. So move this block
listView = (ListView) findViewById(R.id.lstTask);
taskList = new ArrayList<>();
mAdapter = new ArrayAdapter<String>(this, R.layout.row, R.id.task_title, taskList);
listView.setAdapter(mAdapter);
in your onCreate method. Your current code is resetting the adapter and task list on each click event.

How to do operations in ListView items and to pass that data to next activity in android?

I tried using getItem() method and in getView() method, problem not solved. How to do it in each item list view and to pass that specific item data to another activity.
Use this:
In XML:
<ListView
android:id="#+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
In Java:
First findViewById:
ListView lv = (ListView) findViewById(R.id.lv);
Then make a String list and use ArrayAdapter for static data if you are using dynamic data then make CustomAdapter:
String[] abc = new String[] {"A","B","C","D","E","F"};
List<String> abc_list = new ArrayList<String>(Arrays.asList(abc));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, abc_list);
lv.setAdapter(arrayAdapter);
Now for select an item for a particular list item use setOnItemClickListener:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem =(String)parent.getItemAtPosition(position);
Toast.makeText(this, selectedItem, Toast.LENGTH_SHORT).show();
// For next Activity use Intent
Intent intent = new Intent (this, SendDataActivityName.class);
intent.putExtra("pass_data_id_name", selectedItem);
startActivity(intent);
}
});
For basic things or dynamic data use these links:
https://www.codeproject.com/Tips/1023525/Dynamic-ListView-with-Custom-Adapter-in-Android
http://sampleprogramz.com/android/listview.php
https://www.developerfusion.com/article/145373/android-listviews-with-dynamic-data/
http://wptrafficanalyzer.in/blog/dynamically-add-items-to-listview-in-android/
https://www.survivingwithandroid.com/2012/10/android-listviewarrayadapter-and.html
https://www.android-examples.com/create-listview-in-android-programmatically/
https://www.android-examples.com/add-item-in-listview-in-android-programmatically/
https://androidexample.com/Dynamically_Create_View_Elements__-_Android_Example/index.php?view=article_discription&aid=115
To pass data to other activities:
intent.putExtra("myList",myList);
To recieve data from current activity:
ArrayList<E> myList =(ArrayList<E>)getIntent.getSerializableExtra("myList);

trying to convert a regular list view into a clickable list view

I started this program by reading in a premade database and has it display on a list, i am currently trying to convert the list to a clickable list that opens up to a new fragment. This is the code i am currently running. The commented out section is the current problem.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 =(Button) findViewById(android.R.id.button1);
db = new MyDatabase(this);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
schedule = db.getSchedule();
ListView listView = (ListView) findViewById(R.id.list);
//listView.setOnItemClickListener(this);
listView.setAdapter(new SimpleCursorAdapter(
MainActivity.this,
R.layout.row,
schedule,
new String[] {"fName", "Calories", "Protein", "Carbs" },
new int[] { R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4 },
0));
schedule = db.getSchedule();
ListView listView2 = (ListView) findViewById(R.id.list2);
listView2.setAdapter(new SimpleCursorAdapter(
MainActivity.this,
R.layout.row,
schedule,
new String[] {"fName", "Calories", "Protein", "Carbs" },
new int[] { R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4 },
0));
}
});
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Log.i("HelloListView", "You clicked Item: " + id + " at position:" + position);
// Then you start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, Activity2.class);
intent.putExtra("position", position);
// Or / And
intent.putExtra("id", id);
startActivity(intent);
}
listView.setOnItemClickListener(this); will not work because it is being applied to android.view.View.OnClickListener. I have been trying to modify b1.setOnClickListener(new View.OnClickListener(), to try to change its parameters, but I'm not getting any luck. Is there an easy solution I'm not seeing or do i need to reconstruct this code to revolve around a clickable list. Thanks!
Simple, put below code lines in onCreate() of Activity instead of button's onClick() And then implement AdapterView.OnItemClickListener to your Activity.
ListView listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Now on line listView.setOnItemClickListener(this); this refers to your activity class and implemented interface and onItemClick will work.
If your activity is a ListActivity then no need of listView.setOnItemClickListener(this); this line.
Change the Activity to ListActivity and override the method onListItemClick of ListActivity class. Put all the code in the onItemClick of listener to
onListItemClick.

How to add list.java into main.java in android

I am working on android media player. In main.java it includes main.xml and list.java includes
list.xml , I used intent to call list.java (when I press imagebutton) into main.java , But when I press imagebutton list.xml comes up new window I want to show in bottom of the main.xml
In main.java image button calls list.java into main.java
songslist_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(main.this, list.class);
Toast.makeText(main.this, "Song List", Toast.LENGTH_SHORT).show();
startActivityForResult(i, 100);
//Intent i = new Intent(main.this, list.class);
//startActivity(i);
}
});
/////////////////////////
public class list extends ListActivity
{
// Songs list
public ArrayList<HashMap<String, String>> songsLists = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list);//list.xml
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
SongList plm = new SongList();
// get all songs from sdcard
this.songsLists = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsLists.size(); i++)
{
// creating new HashMap
HashMap<String, String> song = songsLists.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.song_item, new String[] { "songTitle" }, new int[] {R.id.song_title });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
//lv = (ListView) findViewById (R.layout.list);
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// getting listitem index
int songIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),main.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
setResult(100, in);
// Closing PlayListView
finish();
}
});
}
}
Is Your main.java class an activity? Your list ist even an activity, so You started a new one, that will be shown in a new window. I think You need another aproach to do this. Read this tutorials first:
http://www.vogella.com/articles/AndroidListView/article.html
http://windrealm.org/tutorials/android/android-listview.php
A possibillity to do such thing is to integrate a simple listView into your main.xml layout and hide this view until button will be pressed.
EDIT
for example:
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainListView">
</ListView>
put this into Your main.xml, maybe below Your button. Then You can reference the listview in your main.java:
mainListView = (ListView) findViewById( R.id.mainListView );
But there is a lot more to do, so I recommend You to read the tutorials to get a clear conception about how to build a listView.

Deleted item still showing on the Result page.

I'm able to edit or delete single item without any problem but when I click delete button after edit an item, the item is still showing on the ListView even though it has been deleted from the database.
ListViewActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_requests);
requestsList = new ArrayList<HashMap<String, String>>();
new LoadAllRequests().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String request_id = ((TextView) view.findViewById(R.id.request_id)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewRequestActivity.class);
// sending rid to next activity
in.putExtra(TAG_ID, request_id);
// starting new activity and expecting some response back
startActivityForResult(in, 55);
}
});
}
Instead of closing and reopening the activity, you should use invalidateViews
yourListView.invalidateViews();
You have to sign the adapter to the listview again
You can also try refreshing the activity. I believe that it is ListViewActivity.restart();

Categories