How to populate ListView and List onclick data? - android

I have a database with Users and their data.
Then make ListView with their names.
How then set click listener to ListView assosiated with my List?
So when I click on List element strats new Activity with all User details, no only name?
package com.test.tabs;
import java.util.ArrayList;
import java.util.List;
import com.test.tabs.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class SelectFragment extends Fragment {
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_select, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MySQLiteOpenHelper db = new MySQLiteOpenHelper(getActivity());
List<User> users = db.getAllUsers();
List<String> your_array_list2 = new ArrayList<String>();
for (int i = 0; i < users.size(); i++) {
your_array_list2.add(users.get(i).getFirstName());
}
listView = (ListView) getActivity().findViewById(R.id.listView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,your_array_list2);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
});
}
}

You need to implement parcelable in your User class:
public class User implements Parcelable
{
....
}
Now you can attach/send your user to the next activity like so:
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
User user = adapter.getItem(position);
Bundle b = new Bundle();
b.putParcelable("user", user);
Intent i = new Intent(context, OtherActivity.class);
i.putExtra("bundle", b);
startActivity(i);
}
});
In the new activity call:
Bundle b = getIntent().getBundleExtra("bundle");
User user = b.getParcelable("user");

Use ListView#setOnItemClickListener(AdapterView.OnItemClickListener listener).

In my opinion, you should use Cursor Adpater to populate listview from database. On item click event for each row, you can get corresponding cursor object, pass on some details to next activity, so it can fetch more user details and display to user.
You need to understand the basics first. Have a look at this tutorial to have some idea.
Good Luck!

Related

What should I do to make the listview work in the fragment when I am getting data from the user and saving it into a SQLite database

This shows one of the fragments that has the listview code in it which worked in it's own layout but does not work in the fragment. What should I do for this to work in the fragment? I am fairly new to android app development so I do not know what to do. if you do not understand what I am trying to do, I am having the user enter data into a form and then i want that data to be displayed in the fragment as a list so they can see all the data entered from beginning to end. I have been looking all over for a solution but i cannot find one that fits what i need to do. All the information i see is for pre-saved sq lite databases.
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.database.Cursor;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import static android.R.attr.button;
public class tab3expense extends Fragment {
private static final String TAG = "tab3expense";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3expense, container, false);
return rootView;
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
listData.add(data.getString(2));
listData.add(data.getString(3));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(tab3expense.this, add_expense.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
Here is the layout file
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.dharquissandas.budget.MainActivity$PlaceholderFragment">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
In Fragment class context will be accessed by in following method getActivity(). Here I make some change in your code. You have to inflate your layout view in onCreateView(), then cast your listview components in onActivityCreated(). Please get look on the following code. Thanks in advance.
public class Tab3expense extends Fragment {
private static final String TAG = "tab3expense";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab3expense, container, false);
return rootView;
}
#Override
public void onActivityCreated( Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (ListView) rootView.findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(getActivity());
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
listData.add(data.getString(2));
listData.add(data.getString(3));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(getActivity(), add_expense.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(getActivity(),message, Toast.LENGTH_SHORT).show();
}
}
Rearrange your code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3expense, container, false);
mListView = (ListView)rootView. findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(getContext());
populateListView();
return rootView;
}

Android Activity methods in Fragment

I have a Fragment activity that I am using to make a tab bar. Inside this activity I am planning to put a table or ListViews with some random values.
Here's my code:
import com.example.mvaguimaraes.beetrackprov.R;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
public class Orders extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.orders, container, false);
ListView listView1 = (ListView) findViewById(R.id.listView1);
Order[] items = {
new Order(1, "Milk", 21.50),
new Order(2, "Butter", 15.99),
new Order(3, "Yogurt", 14.90),
new Order(4, "Toothpaste", 7.99),
new Order(5, "Ice Cream", 10.00),
};
ArrayAdapter<Order> adapter = new ArrayAdapter<Order>(this,
android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
}
The problem is that I cannot extend my Orders class to Fragment and Activity so I'm getting this errors in my code:
Cannot resolve method findViewByID(int)
ListView listView1 = (ListView) findViewById(R.id.listView1);
Cannot resolve constructor
ArrayAdapter<Order> adapter = new ArrayAdapter<Order>(this,
android.R.layout.simple_list_item_1, items);
Cannot resolve method getBaseContext()
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
Probably because they inherit something from Activity. There's any way to make them work inside the Fragment? Sorry for my noob-ness I am new to Android Development.
To open another screen after clicking on one of the items of the listview I did this right after the onItemClick public void method:
String item = ((TextView) view).getText().toString();
Intent i = new Intent(getApplicationContext(), OrderDetails.class);
i.putExtra("new_variable_name",item);
Intent browserIntent =
new Intent(Orders.this, OrderDetails.class);
startActivity(browserIntent);
startActivity(i);
I tried to replace both "getApplicationContext()" and "Orders.this" with "getActivity()" but it didn't work.
Fragments do not have a findViewById() method like Activities. Instead you call findViewById() to lookup views on the View returned from inflating the layout in onCreateView(). Also, where you need a Context you typically use the Activity the fragment is attached to by calling getActivity().
public class Orders extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.orders, container, false);
ListView listView1 = (ListView) v.findViewById(R.id.listView1);
Order[] items = {
new Order(1, "Milk", 21.50),
new Order(2, "Butter", 15.99),
new Order(3, "Yogurt", 14.90),
new Order(4, "Toothpaste", 7.99),
new Order(5, "Ice Cream", 10.00),
};
ArrayAdapter<Order> adapter = new ArrayAdapter<Order>(getActivity(),
android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getActivity(), item, Toast.LENGTH_LONG).show();
}
});
return v;
}
}

Only returns an index of -1 when there is a match

I am trying to get an index of a item in an array that is selectable in a list view. The only issue is that when i click on the item, it only returns the index of -1 which means that it doesnt match when in fact there should be a match. Thanks in advanced!
package com.goldleaf.branden.goldleafcomics;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.kosalgeek.android.json.JsonConverter;
import com.kosalgeek.genasync12.*;
import java.io.FileInputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GlimpseListFragment extends ListFragment {
List<String> glimpse = new ArrayList<String>();
List<String> titles = new ArrayList<String>();
List<UniverseListing> universalListings = new ArrayList<UniverseListing>();
public GlimpseListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_glimpse_list, container, false);
return rootView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "http://goldleafcomics.com/application/UniverseGlimpse.JSON";
PostResponseAsyncTask task = new PostResponseAsyncTask(getActivity(), new AsyncResponse() {
#Override
public void processFinish(String s) {
universalListings = new JsonConverter<UniverseListing>().toArrayList(s, UniverseListing.class);
Toast.makeText(getActivity(), "Application Data Refreshed", Toast.LENGTH_LONG).show();
ArrayList<String> glimpse = new ArrayList<String>();
for(UniverseListing value: universalListings){
glimpse.add(value.universeGlimpse);
}
ArrayList<String> titles = new ArrayList<String>();
for(UniverseListing value: universalListings){
titles.add(value.universeId);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
}
});
task.execute(url);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String value = (String)getListAdapter().getItem(position);
int index = this.titles.indexOf(value);
String value2 = Integer.toString(index);
Toast.makeText(getActivity(), value2, Toast.LENGTH_LONG).show();
}
}
you define glimpse two times, could you try to make those changes,
List<String> glimpse;
and inside onCreate initialize it
glimpse = new ArrayList<>();
and do the same for titles and universalListings.
Try using these two sections of code. You are shadowing the member variables with local variables of the same name.
public class GlimpseListFragment extends ListFragment {
List<String> glimpse;
List<String> titles;
List<UniverseListing> universalListings;
Later...
glimpse = new ArrayList<String>();
for(UniverseListing value: universalListings){
glimpse.add(value.universeGlimpse);
}
titles = new ArrayList<String>();
for(UniverseListing value: universalListings){
titles.add(value.universeId);
}
You don't need to initialize Arraylists with the class. You should typically lazily initialize them (in other words, when you need to)

How to reset the whole View by clicking the delete Button

I have made a custom View which contains an ImageView, a TextView and a delete Button.
I want to reset the particular View when I click the delete Button associated with it.
Please tell how to implement this.
Here is my MainActivity.java
package com.khurana.nikhil.list1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ListView lv;
TextView tv1, tv2;
View v1;
public String[] s = {"nikhil", "mukul", "kunal"};
public int[] img = {R.drawable.rty, R.drawable.sf, R.drawable.rty};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
CustomAdapter cad = new CustomAdapter(MainActivity.this, s, img);
lv.setAdapter(cad);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View v,int position,long id)
{
Toast.makeText(MainActivity.this,"You clicked "+s[position],Toast.LENGTH_SHORT).show();
}
});
}
}
Here is CustomAdapter.java
package com.khurana.nikhil.list1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<String>{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
return v;
}
}
((LinearLayout)yourView.getParent()).removeView(yourView);
or you can call from the layout directly
yourRelativeLayout.removeView(yourView)
I would recommend to use an ArrayList instead of a String[] in your Adapter class. It makes it a lot easier to delete or edit a View and the associated data behind it. I used this post to convert your String[] to an ArrayList, delete the item and convert back to String[].
This should work on button click:
In your Adapter class:
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
int positionToRemove = v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove); //remove the item
}
});
return v;
}
public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(i);
strings = new String[a.size()];
s1= a.toArray(strings);
notifyDataSetChanged(); //refresh your listview based on new data
}
#Override
public int getCount() {
return s1.length;
}
#Override
public String getItem(int position) {
return s1[position];
}
View visibility to GONE will not delete your view from memory as well. Please be specific, do you want to retain your view for future?
If you are working in a listview you should call notifyDataSetChanged() the adapter. your getView() method can be like:
action on button can be like this
Button bt=(Button)v.findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s1 = ArrayUtils.remove(s1, position);
s2 = ArrayUtils.remove(s2, position);
notifyDataSetChanged();
}
});
If you want the view to disappear:
yourView.setVisibility(View.GONE);
EDIT: To get the parent view of the button: Android: Making changes to a button's parent view

Adding ItemListener in Android ListView

I've a swive view along with 4 tabs which displays in my first UI. I've added ListView for each Tabs. But OnItemClickListener is not working for ListFragment. My class is extended from ListFragment and implements OnItemClickListener. What i wanted to do is that when i select a item from the list, i've to display the Toast which displays the name of item that i've selected. But its not working for me. No error occurs but not getting the things done. Can anyone help me for this. My complete code for this is below:
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class TUFragment extends ListFragment implements OnItemClickListener {
ListView list;
View rootView;
final String[] courses = new String[] { "BIM", "BBA", "BBS", "BSc-CSIT",
"BSc-IT", "BHM", "BTTM", "MBA", "MBS", "MSc-IT", "MTTM" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tu, container, false);
list = (ListView) rootView.findViewById(android.R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, courses);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
return rootView;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(this.getActivity(), "You have Selected: " + courses[arg2],
Toast.LENGTH_LONG).show();
}
}
Thankx in advance
Try this..
And also change to setListAdapter(adapter);
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
String val = ((TextView) v).getText().toString().trim();
Toast.makeText(getActivity(), "You have Selected: " + val,
Toast.LENGTH_LONG).show();
}

Categories

Resources