Custom ListView show only one record - android

Hello my customlist view shows only one record. Everything is fine it shows multiple records in console but when ever i try to show the records in ListView it shows only last record its overriding first record, currently there are two records which are showing in my console but in ListView it shows only last record, I am searching for solution since yesterday , I have spend more then 6 hours to solve this problem.
Cart_Adapter.java
public class Cart_Adapter extends BaseAdapter {
Activity activity;
ArrayList<ProductBean> list;
String abc;
public Cart_Adapter(Activity activity, ArrayList<ProductBean> list) {
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v=view;
if(v==null){
LayoutInflater layoutInflater= (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=layoutInflater.inflate(R.layout.cartxml,null);
}
TextView title=(TextView) v.findViewById(R.id.title);
TextView size=(TextView) v.findViewById(R.id.size);
TextView color=(TextView) v.findViewById(R.id.color);
Button remove=(Button) v.findViewById(R.id.remove);
ImageView imageView=(ImageView) v.findViewById(R.id.imageView);
title.setText(list.get(i).getTitle());
size.setText(list.get(i).getSize());
color.setText(list.get(i).getColor());
ArrayList<ImagesBean> aa =list.get(i).getImagesList();
if(aa!=null){
for(i=0; i<aa.size(); i++) {
abc = String.valueOf(aa.get(i).getImgone());
System.out.println("--testing" + abc);
}
}
System.out.println("===="+abc);
if(abc !=null ) {
imageView.setImageBitmap(getBitmapFromString(abc));
// imageView.setImageBitmap(getBitmapFromString(list.get(i).getImagesList()));
}else{}
return v;
}
private Bitmap getBitmapFromString(String encode){
byte[] b = Base64.decode(encode,Base64.DEFAULT);
return BitmapFactory.decodeByteArray(b,0,b.length);
}
}
class from where I am getting database record
ArrayList<String> arrayList=mydatabase.getpid(userid);
System.out.println("--outside"+arrayList);
for(int i =0; i<arrayList.size(); i++) {
String l = arrayList.get(i);
final String ll = l.toString().replace("[", "").replace("]", "").replace(" ", "");
System.out.println("--before loop" + ll);
for (String s : ll.split(",")) {
int pid = Integer.parseInt(s);
myadapter = new Cart_Adapter(Cart.this, mydatabase.getproduct_details(pid));
lv.setAdapter(myadapter);
}
}
Activity_cart.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bhm.ishopping.Cart">
<android.support.constraint.ConstraintLayout
android:id="#+id/customlayout"
android:layout_width="410dp"
android:layout_height="63dp"
android:layout_marginStart="8dp"
android:background="#39a423"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.617"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/textView15"
android:layout_width="86dp"
android:layout_height="29dp"
android:layout_marginStart="320dp"
android:textColor="#android:color/holo_blue_bright"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="16dp" />
</android.support.constraint.ConstraintLayout>
<TextView
android:id="#+id/textView19"
android:layout_width="171dp"
android:layout_height="34dp"
android:layout_marginEnd="120dp"
android:layout_marginTop="76dp"
android:text="Your Cart Detail"
android:textColor="#android:color/black"
android:textSize="22sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/lv"
android:layout_width="373dp"
android:layout_height="411dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/customlayout" />
<Button
android:id="#+id/submit"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_marginStart="76dp"
android:layout_marginTop="40dp"
android:text="Submit Your Order"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/lv" />
</android.support.constraint.ConstraintLayout>
Cart.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="99dp"
android:layout_height="87dp"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/remove"
android:layout_marginStart="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background" />
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView"
android:layout_marginStart="15dp"
android:layout_toEndOf="#+id/imageView"
android:text="Ttile"
android:textColor="#android:color/background_dark"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.456"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView17"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/textView16"
android:layout_marginTop="102dp"
android:text="Color"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView16" />
<TextView
android:id="#+id/textView18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView17"
android:layout_below="#+id/textView17"
android:text="Size"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView17" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/size"
android:layout_alignTop="#+id/remove"
android:text="TextView"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/color"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignStart="#+id/size"
android:text="TextView"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title" />
<TextView
android:id="#+id/size"
android:layout_width="wrap_content"
android:layout_height="21dp"
android:layout_above="#+id/textView18"
android:layout_marginEnd="26dp"
android:layout_toStartOf="#+id/remove"
android:text="TextView"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/color" />
<Button
android:id="#+id/remove"
android:layout_width="46dp"
android:layout_height="67dp"
android:layout_alignBottom="#+id/size"
android:layout_alignParentEnd="true"
android:layout_marginEnd="13dp"
android:background="#5d8f37"
android:text="X"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
console output show two records
enter code here System.out: ===pids1 System.out: ==database record[ProductBean{id='', title='ddd', color='dff', size='Select Size', type='Shart', cost='ddf', imagesList=null System.out: ===pids2 System.out: ==database record[ProductBean{id='', title='aa', color='aa', size='Select Size', type='Select Type', cost='aa', imagesList=null}]

You need to make your cartxml hight to android:layout_height="wrap_content"
like below code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
EDIT
ArrayList<ProductBean> list= new ArrayList();
ArrayList<String> arrayList=mydatabase.getpid(userid);
System.out.println("--outside"+arrayList);
myadapter = new Cart_Adapter(Cart.this, list);
lv.setAdapter(myadapter);
for(int i =0; i<arrayList.size(); i++) {
String l = arrayList.get(i);
final String ll = l.toString().replace("[", "").replace("]", "").replace(" ", "");
System.out.println("--before loop" + ll);
for (String s : ll.split(",")) {
int pid = Integer.parseInt(s);
list.addAll(mydatabase.getproduct_details(pid));
}
}
myadapter.notifyDataSetChanged().

for (String s : ll.split(",")) {
int pid = Integer.parseInt(s);
myadapter = new Cart_Adapter(Cart.this, mydatabase.getproduct_details(pid));
lv.setAdapter(myadapter);
}
You are setting adapter inside loop .Which is totally wrong . Put this code outside Loop .
And one more thing Its time to upgrade to RecyclerView . Its easy and better implementation of ViewHolder Pattern .
ArrayList<String> arrayList=mydatabase.getpid(userid);
ArrayList<String> dataList=new ArrayList();;
for(int i =0; i<arrayList.size(); i++) {
String l = arrayList.get(i);
final String ll = l.toString().replace("[", "").replace("]", "").replace(" ", "");
System.out.println("--before loop" + ll);
for (String s : ll.split(",")) {
// Do your stuff add data to list here
dataList.add(stringToAdd);
}
}
myadapter = new Cart_Adapter(Cart.this, dataList);
lv.setAdapter(myadapter);
Do this way and if your dataset is not building properly then i thing you are using wrong dataset for your list . Or probably you need an ExpandableListView . Figure out the dataSet first currently which is 'ArrayList'.

Print your list size in getCount(), to be sure if list is being sent inside. Check your item's layout_height, it should be wrap_content.

Because you are setting adapter each items in loop.
for (String s : ll.split(",")) {
int pid = Integer.parseInt(s);
myadapter = new Cart_Adapter(Cart.this, mydatabase.getproduct_details(pid));
lv.setAdapter(myadapter);
}
}
so it will take last pid from the iteration and will fetch product details which you are setting in card adapter.
Wrong part is: you are calling setAdapter() with each iteration in the loop
Solution:
Collect the list of records in loop, you can keep adding product details in the array list and then set the final list outside loop in the adapter.

Check your cartxml layout file. The root RelativeLayout height will be wrap_content otherwise it will take all the available space for a single item. Use android:layout_width="wrap_content" for RelativeLayoutin in your cartxml

Related

Linear View in ScrollView with Array Adapter growing up instead of down on new items

I have an Java Android project I am working on wherein I have a LinearLayout that is managed by an array adapter.
My issue is when I add a new item to the array adapter and update the view the List of items is growing upwards instead of down as is visible in the images below.
Why is this now growing down? and how can i make it do so?
Code follows pics
Main Activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<AnalogClock
android:id="#+id/clockMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.1" />
<TextView
android:id="#+id/dateMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/clockMain"
/>
<TextView
android:id="#+id/titleMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/annie_use_your_telescope"
android:text="#string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/dateMsg"
app:layout_constraintVertical_bias="0.05"
android:textSize="30sp"
android:textColor="#color/colorPrimaryDark"
/>
<ListView
android:id="#+id/taskList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintVertical_bias="0.5"
android:nestedScrollingEnabled="true"
/>
<Button
android:id="#+id/addNewTask"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_new_task"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintVertical_bias="0.95"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
Task List
<?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="wrap_content"
>
<TextView
android:id="#+id/taskDesc"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:textSize="15sp"
android:text="testing task"
android:layout_weight="1"
/>
<TextView
android:id="#+id/taskDate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="this is bull shit"
android:layout_weight="1"
/>
<TextView
android:id="#+id/taskTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="some more bullish"
android:layout_weight="1"
/>
</LinearLayout>
inflator
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflater.inflate(R.layout.task_list, null);
TextView taskDesc = (TextView) view.findViewById(R.id.taskDesc);
TextView taskDate = (TextView) view.findViewById(R.id.taskDate);
TextView taskTime = (TextView)view.findViewById(R.id.taskTime);
taskDesc.setText(tasks.get(i).description);
taskDate.setText(tasks.get(i).taskDate.toString());
taskTime.setText(tasks.get(i).taskTime.toString());
return view;
}
import java.util.ArrayList;
public class TaskAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<Task> tasks;
public TaskAdapter(Context applicationContext, ArrayList<Task> tasks) {
this.context = applicationContext;
this.tasks = new ArrayList<>(tasks);
inflater = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return tasks.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflater.inflate(R.layout.task_list, null);
TextView taskDesc = (TextView) view.findViewById(R.id.taskDesc);
TextView taskDate = (TextView) view.findViewById(R.id.taskDate);
TextView taskTime = (TextView)view.findViewById(R.id.taskTime);
taskDesc.setText(tasks.get(i).description);
taskDate.setText(tasks.get(i).taskDate.toString());
taskTime.setText(tasks.get(i).taskTime.toString());
return view;
}
}
Can you add the array adapter you are using(how you are inserting data in arrayadapter) and where you are passing the array to listview.

RecyclerView not populating, likely a silly adapter problem

I used a working RecyclerView as a template for another, but I made some sort of mistake in its implementation and I can't find it. Here is the code that initializes the view:
mMessageThreadList = new ArrayList<>();
mRecyclerView = findViewById(R.id.chat_list_recycler_view);
private void initRecyclerView() {
Log.d(TAG, "initRecyclerView Called");
//Initializes and sets up adapter
mAdapter = new ChatListRecyclerViewAdapter(mThreadList);
mRecyclerView.setAdapter(mAdapter);
Query query = mThreadCollection;
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
switch (documentChange.getType()) {
case ADDED:
Thread thread = documentChange.getDocument().toObject(Thread.class);
Log.d(TAG, "Last Message: " + thread.getLastMessage().getMessage());
mThreadList.add(thread);
mAdapter.notifyDataSetChanged();
}
}
}
});
}
Note that the print log statement in the SnapshotListener does contain a value when printed so the information is returning from Firebase, it's just not displaying. Which makes me think my problem is with my Adapter/Viewholder:
public class ChatListRecyclerViewAdapter extends RecyclerView.Adapter<ChatListRecyclerViewAdapter.ChatListViewHolder> {
private List<Thread> threadList;
ChatListRecyclerViewAdapter(List<Thread> threadList) {
this.threadList = threadList;
}
#NonNull
#Override
public ChatListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_list_row, parent, false);
return new ChatListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ChatListViewHolder holder, int position) {
// This method fills fields with data for each list item
Log.d(TAG, "onBindViewholder called");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM hh:mm a");
final Thread thread = threadList.get(position);
char initial = thread.getPartnerName().charAt(0);
char uppercaseInitial = Character.toUpperCase(initial);
Log.d(TAG, thread.getLastMessage() + " " + thread.getPartnerID());
holder.partnerName.setText(thread.getPartnerName());
holder.authorInitial.setText(uppercaseInitial);
holder.lastMessageText.setText(thread.getLastMessage().getMessage());
holder.lastMessageTime.setText(simpleDateFormat.format(thread.getLastMessage().getTimestamp()));
}
#Override
public int getItemCount() {
return threadList.size();
}
//Viewholder stores the information about the layout and content of each list item, and serves as a template for each item of a RecyclerView
public class ChatListViewHolder extends RecyclerView.ViewHolder {
TextView partnerName;
TextView authorInitial;
TextView lastMessageText;
TextView lastMessageTime;
LinearLayout listTextHolder;
public ChatListViewHolder(View itemView) {
super(itemView);
partnerName = itemView.findViewById(R.id.partner_name);
authorInitial = itemView.findViewById(R.id.partner_initial);
lastMessageText = itemView.findViewById(R.id.last_message);
lastMessageTime = itemView.findViewById(R.id.last_message_time);
listTextHolder = itemView.findViewById(R.id.list_text_holder);
}
}
}
chat_list_row.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/single_thread_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="#color/colorPrimaryDark">
<TextView
android:id="#+id/partner_initial"
android:background="#drawable/chat_list_circle"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_alignParentStart="true"
android:gravity="center"
android:text="A"
android:textSize="36sp"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/last_message_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:padding="5dp"
android:fontFamily="#font/nunito_extralight"
android:text="#string/sample_time"
android:textColor="#android:color/darker_gray"
android:textSize="12sp"
android:typeface="normal" />
<LinearLayout
android:id="#+id/list_text_holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/partner_initial"
android:layout_centerVertical="true"
android:orientation="vertical">
<TextView
android:id="#+id/partner_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="5dp"
android:fontFamily="#font/nunito"
android:text="#string/sample_name"
android:textColor="#color/white"
android:textSize="14sp"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/last_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:fontFamily="#font/nunito_extralight"
android:gravity="start"
android:text="#string/sample_message"
android:textColor="#android:color/darker_gray"
android:textSize="12sp"
android:typeface="normal" />
</LinearLayout>
</RelativeLayout>
Edit: Layout of the Activity that RecyclerView appears in. I also edit above code to show where the variable is attached to the view:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorPrimaryDark"
android:paddingLeft="0dp"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="0dp"
android:paddingBottom="0dp"
tools:context="org.andrewedgar.theo.ChatListActivity">
<include
android:id="#+id/chat_list_toolbar"
layout="#layout/toolbar" />
<android.support.v7.widget.RecyclerView
android:id="#+id/chat_list_recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/chat_list_toolbar" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/new_check_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:src="#drawable/ic_person_pin_circle_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
Seems like you have missed to add layout manager of RecyclerView. Would you please add this and try again
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
Your recyclerview is not showing any data because the list in adapter is still empty. After fetching data from firebase you are adding to mThreadList, which is still with activity and not adapter. To update the list in adapter you can add a method in adapter class and pass the list to adapter and notifyDataseChanged there.
Activity:
//after firebase task...
mAdapter.updateData(mThreadList);
Adapter: add new method
void updateData(List<Thread> threadList){
this.threadList = threadList;
notifyDatasetChanged(); //notify adapter that new list is added
}

how to set the specific row item option(visible, invisible) in listview in android

frist my english skill weak.
description>
this is list view.
ㅡㅡㅡㅡㅡㅡㅡㅡ
ㅣㅡㅡㅡㅡㅡㅣㅢ <-- this is button , i init set invisible
ㅣㅡㅡㅡㅡㅡㅣㅢ
ㅣㅡㅡㅡㅡㅡㅣㅢ
ㅣㅡㅡㅡㅡㅡㅣㅢ
ㅣㅡㅡㅡㅡㅡ ////// <-- i want make visible button
ㅣㅡㅡㅡㅡㅡ ////// <-- specific position
I make the custom ListView
ListView row contains texts, Button.
The Button is set invisible option in xml file.
then, I want set the visible specific row button.
I tried that and failed
after make ArrayList for ListView, marking matching position like this
for(i=0; i<arraylist.size(); i++){
int t41=Integer.parseInt(arraylist.get(i).getm());
if(month == t41){
confirm_replay[i]=true;
temp55=i;
}
}
I can set the textValue. through adapter.getItem(int position).
but i don't know, how to control specific button.
also try add button into adapter. failed..
also search question in google but my eng skill bad. failed
add my code.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:paddingTop="10dp"
android:text="match day(weekend)"
android:textSize="28dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:background="#2d000000"
android:layout_width="match_parent"
android:layout_height="3dp">
</LinearLayout>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/m"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:paddingLeft="10dp"
android:id="#+id/d"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/yoil"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/time"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/vsTeam"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/league"
android:paddingLeft="10dp"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/공갈"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button_youtube"
android:text="다시보기"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/m"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:paddingLeft="10dp"
android:id="#+id/d"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/yoil"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/time"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/vsTeam"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/league"
android:paddingLeft="10dp"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/공갈"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button_youtube"
android:text="다시보기"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>
</LinearLayout>
</LinearLayout>
</b>
adapter
class MlistViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<MatchInfomation> matchinformationlist = null;
private ArrayList<MatchInfomation> arraylist;
public MlistViewAdapter(Context context,
List<MatchInfomation> matchinformationlist) {
mContext = context;
this.matchinformationlist = matchinformationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<MatchInfomation>();
this.arraylist.addAll(matchinformationlist);
}
public class ViewHolder {
TextView m;
TextView d;
TextView yoil;
TextView vsTeam;
TextView time;
TextView league;
}
#Override
public int getCount() {
return matchinformationlist.size();
}
#Override
public MatchInfomation getItem(int position) {
return matchinformationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.activity_match_list, null);
button_youtube.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_SEARCH);
intent.setPackage("com.google.android.youtube");
intent.putExtra("query", "Android");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
});
// Locate the TextViews in listview_item.xml
holder.m = (TextView) view.findViewById(R.id.m);
holder.d = (TextView) view.findViewById(R.id.d);
holder.yoil = (TextView) view.findViewById(R.id.yoil);
holder.vsTeam = (TextView) view.findViewById(R.id.vsTeam);
holder.time = (TextView) view.findViewById(R.id.time);
holder.league = (TextView) view.findViewById(R.id.league);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.m.setText(matchinformationlist.get(position).getm());
holder.d.setText(matchinformationlist.get(position).getd());
holder.yoil.setText(matchinformationlist.get(position).getyoil());
holder.vsTeam.setText(matchinformationlist.get(position).getvsTeam());
holder.time.setText(matchinformationlist.get(position).gettime());
holder.league.setText(matchinformationlist.get(position).getleague());
return view;
}
}
If you want to adjust a specific row, you can use the position parameter in your getView() method in adapter. For instance;
if(position==55){
holder.m.setVisibility(View.GONE);
}
I'm not sure i understand your question.
If i'm right you juste want your button to be invisble for specific row. To do so add the specific line at the end of your getView method
yourButton.setVisibility(View.INVISIBLE)
If you want to hide the entire row, the best way will probably be to change your adapter to diplay only row with content.
before setting the values to the view check the condition whatever you want like:-
if condition is true then set your view visible
else set your view invisible
if(true){
button.setVisibility(View.VISIBLE);
}else{
button.setVisibility(View.GONE);
}

My gridview shows only one row

//My xml code
<ScrollView
android:id="#+id/scrollview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="35dp">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:background="#android:color/background_light"
android:gravity="center"
android:paddingBottom="5dp" >
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:text="Venue, Date"
android:textSize="12sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_below="#+id/textView4"
android:text="Description"
android:textSize="12sp"
android:paddingBottom="5dp" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="14dp"
android:src="#drawable/demo" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="Event of the Week" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView7"
android:layout_marginLeft="14dp"
android:text="Event Name" />
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView6"
android:layout_marginTop="14dp"
android:horizontalSpacing="10dp"
android:numColumns="2"
android:paddingBottom="5dp"
android:verticalSpacing="10dp" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView5"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="Today&apos;s Events" />
</RelativeLayout>
</ScrollView>
//MainActivity
class LoadProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EventHome.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
PROFILE_URL = "http://www.example.com/filter_event_android.php?pin="+phone;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("All Events: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#SuppressLint("InlinedApi") #Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try{
event = new JSONObject(json);
final ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
JSONArray user = event.getJSONArray("events");
String contains=json.toString();
if(contains.contains("id"))
{
for (int i = 0; i < user.length(); i++) {
JSONObject object = user.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", object.getString("id"));
map.put("name", object.getString("name"));
map.put("date_d", object.getString("date_d"));
map.put("location", object.getString("location"));
map.put("images", "http://www.example.com/"+object.getString("images"));
arraylist.add(map);
}
String[] from = {"name", "date_d", "location", "images"};
int[] to = {R.id.textView1, R.id.textView2, R.id.textView3, R.id.iv_flag};
ListAdapter adapters = new MyAdapter(EventHome.this,arraylist,R.layout.list_event_home,from,to);
gv1.setAdapter(adapters);
}
else
{
gv1.setVisibility(View.GONE);
TextView dynamicTextView = new TextView(EventHome.this);
dynamicTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
dynamicTextView.setText("No events available");
}
gv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(EventHome.this,EventSingle.class);
i.putExtra("event_id", arraylist.get(arg2).get("id"));
startActivity(i);
}
});
}catch(Exception e)
{
e.printStackTrace();
}
}
}
//MyAdapter.java
public class MyAdapter extends SimpleAdapter{
public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to){
super(context, data, resource, from, to);
}
public View getView(int position, View convertView, ViewGroup parent){
// here you let SimpleAdapter built the view normally.
View v = super.getView(position, convertView, parent);
// Then we get reference for Picasso
ImageView img = (ImageView) v.getTag();
if(img == null){
img = (ImageView) v.findViewById(R.id.iv_flag);
v.setTag(img); // <<< THIS LINE !!!!
}
// get the url from the data you passed to the `Map`
#SuppressWarnings("rawtypes")
String url = (String) ((Map)getItem(position)).get("images");
// do Picasso
Picasso.with(v.getContext()).load(url).into(img);
// return the view
return v;
}
}
The above layout shows only one row values in my gridview. But i have morethan 5 values for gridview. Why is it not showing the other values. I tried a lot but no use. Does anyone have solution.
This is probably caused by having GridView inside of ScrollView. Since both layouts are scrollable this causes a lot of problems, in your case the height of GridView cannot be properly determined and the scroll events are eaten by the ScrollView.
With ListView you can simply declare the ListView as root element and then add other scrollable content as headers or footers. GridView natively does not support this but fortunately there is subclass implementation of HeaderGridView which solves this problem.
What you should do is put only the HeaderGridView to your xml inflated by the activity.
<?xml version="1.0" encoding="utf-8"?>
<your.package.HeaderGridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:horizontalSpacing="10dp"
android:numColumns="2"
android:verticalSpacing="10dp" />
and then implement the RelativeLayout as a header view in different xml (for example header.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:background="#android:color/background_light"
android:gravity="center"
android:paddingBottom="5dp">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:text="Venue, Date"
android:textSize="12sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_below="#+id/textView4"
android:text="Description"
android:textSize="12sp"
android:paddingBottom="5dp" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="14dp"
android:src="#drawable/demo" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="Event of the Week" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView7"
android:layout_marginLeft="14dp"
android:text="Event Name" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView5"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="Today&apos;s Events" />
</RelativeLayout>
In your activity you add the header to your HeaderGridView
HeaderGridView gridView = (HeaderGridView) findViewById(R.id.gridView1);
View header = getLayoutInflater().inflate(R.layout.header, gridView, false);
gridView.addHeaderView(header);
// set adapter AFTER adding headerViews
gridView.setAdapter(MyAdapter(...))
Tried it, worked like a charm. Hope it helps!
The problem and fix I have found is that if the gridview has rows data bound the select statement must have that particular field in my case I am evaluating Grade and this grade was not included in my select statement and the gridview was returning single row no matter what but the moment I included the Grade in my select statement the problem was fixed
Protected Sub GVRos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVRos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim stat As String
'This row evaluates and puts the value in stat as per the Finalised columon result
stat = DataBinder.Eval(e.Row.DataItem, "Grade").ToString()
If stat = "A" Then
e.Row.BackColor = System.Drawing.Color.LightGreen
ElseIf stat = "B" Then
e.Row.BackColor = System.Drawing.Color.LightBlue
ElseIf stat = "C" Then
e.Row.BackColor = System.Drawing.Color.Yellow
ElseIf stat = "D" Then
e.Row.BackColor = System.Drawing.Color.Orange
ElseIf stat = "F" Then
e.Row.BackColor = System.Drawing.Color.Red
Else
e.Row.BackColor = System.Drawing.Color.White
End If
End If
End Sub

ListView Selction in Android?

I have 2 ListView in my Layout and one common row layout for it and the row is repeating multiple times .I am confused how i will identify on both of ListView which result is selected and how i will get the data of TextViews that are selected in both the listViews.
This is my ListView XML
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/footerLayout"
android:layout_below="#+id/sortFlightLayouts"
android:orientation="horizontal" >
<ListView
android:id="#+id/lvDepartures"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<View
android:layout_width="1dp"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray" />
<ListView
android:id="#+id/lvArrivals"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
And this is the Row Layout that i am putting in these two ListViews
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/flightLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5sp"
android:layout_marginRight="10sp"
android:layout_marginTop="5sp"
android:layout_marginLeft="5dp"
android:src="#drawable/spicejet" />
<TextView
android:id="#+id/flightCompanyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/flightLogo"
android:text="SpiceJet" />
<TextView
android:id="#+id/flightNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/flightCompanyName"
android:text="9W-123" />
<TextView
android:id="#+id/flightTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="12dp"
android:layout_toRightOf="#+id/flightLogo"
android:gravity="center_vertical"
android:text="6:00 - 7:00" />
<TextView
android:id="#+id/flightStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/flightTime"
android:layout_toRightOf="#+id/flightLogo"
android:layout_marginLeft="12dp"
android:text="1h 35m | Non Stop" />
<TextView
android:id="#+id/amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/flightStop"
android:layout_below="#+id/flightStop"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/flightCompanyName"
android:text="Rs 20,000" />
</RelativeLayout>
And in MY Activity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);
ArrayList<HashMap<String, String>> flightData = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 12; i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(FlightCompanyName, "SpiceJet");
map.put(FlightNumber, "SG-123");
map.put(FlightTime, "6:00 - 7:00");
map.put(FlightStop, "1h 30m | Non Stop");
map.put(FlightCost, "Rs 12,000");
// adding HashList to ArrayList
flightData.add(map);
}
onewayListView=(ListView)findViewById(R.id.lvDepartures);
ReturnListView=(ListView)findViewById(R.id.lvArrivals);
// Getting adapter by passing xml data ArrayList
onewaydata=new OneWayFlightResult(this, flightData);
onewayListView.setAdapter(onewaydata);
returndata=new ReturnFlightResult(this, flightData);
ReturnListView.setAdapter(returndata);
}
A bit more explanation this design is for flight result.So if the user is searching for roundtrip.I will show him 2 result one on left and other on right side .Now what i want that user can select one flight from left list and and one flight from the right side.Once he select the flight .I have to get the data of the flight selected.So how could i do this .Please help me
SparseBooleanArray checked;
lvDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
checked = lvDialog.getCheckedItemPositions();
if(checked.get(arg2))
{
chkText.setTextColor(Color.CYAN);
colorRow ++;
}
else
{
chkText.setTextColor(Color.BLACK);
colorRow--;
}
}
});
hey here is some code...try

Categories

Resources