I am using Tab Layout. I am showing data in ListView inside ListFragment. Data is showing in ListView but problem is when we press tabb again, same data will add in Listview. So every time continue same data add in listView.
Code here-
public class HomeFragments extends ListFragment {
int[] ust_icon = {R.drawable.title,R.drawable.t2,R.drawable.t2};
String[] live_on = {"NA","NA","NA"};
String[] total_subtopics = {"3","3","3"};
String[] title = {"semiconductor devices ##","Equations of state ##","pn junction ##"};
String[] pos = {"1","5","6"};
String[] completed_subtopics = {"3","3","3"};
String[] live = {"false","false","false"};
String[] id = {"13","14","15"};
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
public HomeFragments() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_fragments, container, false);
HashMap<String, String> map = new HashMap<String, String>();
for (int i=0;i<3;i++)
{
map = new HashMap<String, String>();
map.put("ust_icon", Integer.toString(ust_icon[i]));
map.put("live_on",live_on[i]);
map.put("total_subtopics",total_subtopics[i]);
map.put("title",title[i]);
map.put("pos",pos[i]);
map.put("completed_subtopics",completed_subtopics[i]);
map.put("live",live[i]);
map.put("id",id[i]);
data.add(map);
}
String[] from = {"ust_icon","live_on","total_subtopics","title","pos","completed_subtopics","live","id"};
int[] to = {R.id.img1,R.id.txt1,R.id.txt2,R.id.txt3,R.id.txt4,R.id.txt5,R.id.txt6,R.id.txt7};
adapter = new SimpleAdapter(getActivity(),data, R.layout.list1, from, to);
setListAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
}
}
how to resolve this issue Please help....
I think I have your answer. Just wait for me a couple minute when I got home and then I’ll answer you ok?
Edit:
Try to construct your data and set your adapter in onActivityCreated()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_fragments, container, false);
return view;
}
and
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
HashMap<String, String> map = new HashMap<String, String>();
for (int i=0;i<3;i++)
{
map = new HashMap<String, String>();
map.put("ust_icon", Integer.toString(ust_icon[i]));
map.put("live_on",live_on[i]);
map.put("total_subtopics",total_subtopics[i]);
map.put("title",title[i]);
map.put("pos",pos[i]);
map.put("completed_subtopics",completed_subtopics[i]);
map.put("live",live[i]);
map.put("id",id[i]);
data.add(map);
}
String[] from = {"ust_icon","live_on","total_subtopics","title","pos","completed_subtopics","live","id"};
int[] to = {R.id.img1,R.id.txt1,R.id.txt2,R.id.txt3,R.id.txt4,R.id.txt5,R.id.txt6,R.id.txt7};
adapter = new SimpleAdapter(getActivity(),data, R.layout.list1, from, to);
setListAdapter(adapter);
}
if the code above not working, try to replace this:
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
by this: ArrayList<HashMap<String,String>> data;
and then in your onCreateView : data = new ArrayList<HashMap<String, String>>();
Try adding condition to your code like i did below.i just created boolean variable called check.if tab opens first time it will set listview as well as set it's value to true.now condition wont run and you will not get listview element add again and again
public class HomeFragments extends ListFragment {
int[] ust_icon = {R.drawable.title,R.drawable.t2,R.drawable.t2};
String[] live_on = {"NA","NA","NA"};
String[] total_subtopics = {"3","3","3"};
String[] title = {"semiconductor devices ##","Equations of state ##","pnjunction ##"};
String[] pos = {"1","5","6"};
String[] completed_subtopics = {"3","3","3"};
String[] live = {"false","false","false"};
String[] id = {"13","14","15"};
public static final boolean check = false;
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
public HomeFragments() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_fragments, container, false);
HashMap<String, String> map = new HashMap<String, String>();
for (int i=0;i<3;i++)
{
map = new HashMap<String, String>();
map.put("ust_icon", Integer.toString(ust_icon[i]));
map.put("live_on",live_on[i]);
map.put("total_subtopics",total_subtopics[i]);
map.put("title",title[i]);
map.put("pos",pos[i]);
map.put("completed_subtopics",completed_subtopics[i]);
map.put("live",live[i]);
map.put("id",id[i]);
data.add(map);
}
if(check == false)
{
String[] from = {"ust_icon","live_on","total_subtopics","title","pos","completed_subtopics","live","id"};
int[] to = {R.id.img1,R.id.txt1,R.id.txt2,R.id.txt3,R.id.txt4,R.id.txt5,R.id.txt6,R.id.txt7};
adapter = new SimpleAdapter(getActivity(),data, R.layout.list1, from, to);
setListAdapter(adapter);
check = true;
}
return view;
}
#Override
public void onStart() {
super.onStart();
}
I want to populate a spinner instead of a ListView with data from Firebase.
The code below works fine with ListView. But how can I replace the ListView with a spinner? Hope someone can help me with this.
My research:
Firebase data to Spinner
Populatate the spinner from Firebase database
Here is my Main Activity:
public class Ansattliste extends AppCompatActivity {
DatabaseReference databaseAnsatt;
ListView lvansattliste;
Button btnleggtilansatt;
List<Ansatt> listansatt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ansattliste);
databaseAnsatt = FirebaseDatabase.getInstance().getReference("Ansatte");
lvansattliste = (ListView)findViewById(R.id.lvansattliste);
listansatt = new ArrayList<>();
btnleggtilansatt = (Button)findViewById(R.id.btnleggtilansatt);
btnleggtilansatt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent leggtil = new Intent(Ansattliste.this, Leggtilansatt.class);
startActivity(leggtil);
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseAnsatt.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
listansatt.clear();
for (DataSnapshot ansattSnapshot : dataSnapshot.getChildren()) {
final Ansatt ansatt = ansattSnapshot.getValue(Ansatt.class);
listansatt.add(ansatt);
final listAnsatt adapter = new listAnsatt(Ansattliste.this, listansatt);
lvansattliste.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled (DatabaseError databaseError){
}
});
}
}
And my Adapter:
public class listAnsatt extends ArrayAdapter<Ansatt> {
private Activity context;
private List<Ansatt> listansatt;
public listAnsatt(Activity context, List<Ansatt> listansatt) {
super(context, R.layout.list_ansatt, listansatt);
this.context = context;
this.listansatt = listansatt;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_ansatt, null, true);
TextView tvansattnavn = (TextView) listViewItem.findViewById(R.id.tvansattnavn);
TextView tvansaattnr = (TextView) listViewItem.findViewById(R.id.tvansattnr);
Ansatt ansatt = listansatt.get(position);
tvansattnavn.setText(ansatt.getAnsattnavn());
tvansaattnr.setText(ansatt.getAnsattnr());
return listViewItem;
}
Firebase:
Firebase
You'd do something like following (I've adapted from Kotlin code I have here so possibility of some syntax errors)...have assumed for illustration that getAnsattnavn() is value you want to show in spinner. You'd still have listansatt which presumably you'd look up when item is selected in spinner.
In onDataChange:
List<String> optionList = new ArrayList<>();
for (DataSnapshot ansattSnapshot : dataSnapshot.getChildren()) {
final Ansatt ansatt = ansattSnapshot.getValue(Ansatt.class);
optionList.add(ansatt.getAnsattnavn());
listansatt.add(ansatt);
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, optionList);
spinnerControl.setAdapter(adapter);
MainFragment:
public class MainFragment extends Fragment {
RecyclerView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
// URL Address
String url = "http:";
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String x = "/aaa/bbb/omer/000";
String []tokens = x.split("/aaa/bbb/");
for (String t: tokens)
Toast.makeText(getActivity(), t, Toast.LENGTH_SHORT).show();
View view =inflater.inflate(R.layout.fragment_main, container, false);
listview = (RecyclerView) view.findViewById(R.id.listview);
listview.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
listview.setLayoutManager(llm);
new JsoupListView().execute();
return view;
}
// Title AsyncTask
private class JsoupListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Diziler Yükleniyor");
// Set progressdialog message
mProgressDialog.setMessage("Yükleniyor...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Connect to the Website URL
Document doc = Jsoup.connect(url).get();
// Identify Table Class "worldpopulation"
for (Element table : doc.select("div[class=col-sm-12 col-xs-12 pad0 middle]")) {
// Identify all the table row's(tr)
for (Element row : table.select("div[class=col-sm-12 col-xs-12 pad0 streamingBoxWrap mNewsItem]:gt(0)")) {
HashMap<String, String> map = new HashMap<String, String>();
// Identify all the table cell's(td)
Elements tds = row.select("a");
// Identify all img src's
Elements imgSrc = row.select("img[src]");
// Get only src from img src
String imgSrcStr = imgSrc.attr("src");
Elements aSrc = row.select("a[href]:gt(1)");
String aSrcStr = aSrc.attr("href");
// Retrive Jsoup Elements
// Get the first td
map.put("rank", aSrcStr);
// Get the second td
map.put("country", tds.get(1).text());
// Get the third td
map.put("population", tds.get(2).text());
// Get the image src links
map.put("flag", imgSrcStr);
// Set all extracted Jsoup Elements into the array
arraylist.add(map);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
listview.setAdapter(adapter);
listview.setItemAnimator(new DefaultItemAnimator());
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
ListViewAdapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
final TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.singleitemview, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainFragment.RANK));
country.setText(resultp.get(MainFragment.COUNTRY));
population.setText(resultp.get(MainFragment.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainFragment.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
DiziFragment myFragment3 = new DiziFragment();
Bundle bundle = new Bundle();
bundle.putString("gun",resultp.get(MainFragment.POPULATION));
bundle.putString("flag",resultp.get(MainFragment.FLAG));
myFragment3.setArguments(bundle);
android.support.v4.app.FragmentTransaction fragmentTransaction = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,myFragment3);
fragmentTransaction.commit();
}
});
return itemView;
}
}
Gradle build
I want to list items with recyclerview. Help me Please.
Turkish:kodda listview ile liteliyordu ben ise recyclerview ile listelemek istiyorum.
edit my code
adapter:
public class SimpleRecyclerAdapter extends RecyclerView.Adapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public SimpleRecyclerAdapter(Context context,ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int position) {
final TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.singleitemview, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainFragment.RANK));
country.setText(resultp.get(MainFragment.COUNTRY));
population.setText(resultp.get(MainFragment.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainFragment.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
DiziFragment myFragment3 = new DiziFragment();
Bundle bundle = new Bundle();
bundle.putString("gun",resultp.get(MainFragment.POPULATION));
bundle.putString("flag",resultp.get(MainFragment.FLAG));
myFragment3.setArguments(bundle);
android.support.v4.app.FragmentTransaction fragmentTransaction = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,myFragment3);
fragmentTransaction.commit();
}
});
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
return itemView; is eroor
If you are using recycler view then your adapter should also extends recycler view instead of Base Adapter. For eg.
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeedItem feedItem = feedItemList.get(i);
//Download image using picasso library
Picasso.with(mContext).load(feedItem.getThumbnail())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle()));
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}
This is what i have tried, but my ListView doesn't get filled. I use a custom adapter because i wan't to change the background color of the items that't got a boolean value = true. I am using Android Studio.
Hope someone can help.
i'm new to android.
public class ShoppingListActivity extends ActionBarActivity {
private TextView header;
private ListView listView;
private CustomArrayAdapter arrayAdapter;
private ShoppingList shoppingList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
header = (TextView)findViewById(R.id.textView2);
//get reference to ListView
listView = (ListView)findViewById(R.id.shoppingListItemsView);
shoppingList = (ShoppingList) getIntent().getSerializableExtra(Globals.CHOSENLISTKEY);
arrayAdapter = new CustomArrayAdapter(this, R.layout.custom_list_view, shoppingList.getItemList());
listView.setAdapter(arrayAdapter);
header.setText(shoppingList.toString());
Button btnShop = (Button) findViewById(R.id.btnShop);
btnShop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ShoppingListActivity.this, SelectStoreActivity.class);
startActivity(intent);
}
});
}
public void setData() {
for(int i = 0; i < shoppingList.getItemList().size(); i++) {
arrayAdapter.add(shoppingList.getItemList().get(i));
}
}
}
public class CustomArrayAdapter extends ArrayAdapter<Entry> {
private int resource;
private ArrayList<Entry> list;
public CustomArrayAdapter(Context context, int resource, ArrayList<Entry> list) {
super(context, resource);
this.resource = resource;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parentGroup) {
View view = convertView;
Entry entry = list.get((position));
if(view == null) {
LayoutInflater layoutInflater = ((Activity) getContext()).getLayoutInflater();
view = layoutInflater.inflate(resource, parentGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.customName);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
return view;
}
}
To show data in ListView rows call setText method of TextView which is return from getView method:
TextView textView = (TextView) view.findViewById(R.id.customName);
// get Text from entry and pass it to setText method
String strTextViewData=entry.getItem()...;
textView.setText(strTextViewData);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
I m trying to use searchView with LazyList. In my lazyAdapter I m updating my arraylist , this works smoothly but my listview doesn't update with arrayList. This is my filer method. I suppose notifyDataSetChanged does not work.Please help how can I refresh my listview?
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
//list.clear();
list = new ArrayList<HashMap<String, String>>();
if (charText.length() == 0) {
list.addAll(arraylist);
}
else
{
for (HashMap<String, String> map : arraylist)
{
if (map.get("radio").toString().toLowerCase(Locale.getDefault()).contains(charText))
{
list.add(map);
}
}
}
notifyDataSetChanged();
}
The variable list holds a different object after the third line. You are changing this new ArrayList but the adapter still remembers the old one. Instead of
list = new ArrayList<HashMap<String, String>>();
write
list.clear();
You then work with the same object as before.
LazyList 's listview can not refresh with new arraylist
Because you are not adding new list in current Adapter of Listview before calling notifyDataSetChanged() :
Add list to adapter using addAll method:
listviewAdapter.addAll(list);
//notify data-source change to adapter
notifyDataSetChanged();
if addAll method not available then create a method in Adapter class and pass list as parameter then call add method:
public void addAll(ArrayList<HashMap<String, String>> data) {
for(String item: data) {
add(item);
}
notifyDataSetChanged();
}
public class MovieListAdapter extends BaseAdapter {
private Context context;
ArrayList<HashMap<String, String>> movielist;
private ArrayList<HashMap<String, String>> listAdapter;
public MovieListAdapter(Context context, ArrayList<HashMap<String, String>> movielist) {
this.context = context;
this.movielist = movielist;
this.listAdapter = new ArrayList<HashMap<String, String>>();
this.listAdapter.addAll(movielist);
}
#Override
public int getCount() {
return movielist.size();
}
#Override
public Object getItem(int position) {
return movielist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View griView = inflater.inflate(R.layout.movie_listitem, null);
TextView textview = (TextView) griView.findViewById(R.id.catname);
textview.setText(movielist.get(position).get("name"));
textview.setSelected(true);
ImageView imageView = (ImageView) griView.findViewById(R.id.catimage);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels / 3;
int height = metrics.widthPixels / 3;
// System.out.println(movielist.get(position).getMoviepicture());
if (movielist.get(position).get("image").equals("")) {
imageView.setImageResource(R.drawable.blankart);
} else {
Picasso.with(context)
.load(movielist.get(position).get("image"))
.resize(width, height).placeholder(R.drawable.blankart)
.noFade().into(imageView);
}
return griView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
movielist.clear();
if (charText.length() == 0) {
movielist.addAll(listAdapter);
} else {
for (HashMap<String, String> si : listAdapter) {
if (si.get("name").toLowerCase(Locale.getDefault())
.contains(charText)) {
movielist.add(si);
}
}
}
notifyDataSetChanged();
}
}
make you adapter like this