I want to retrieve information from my firebase database into a recyclerview which is in a fragment called fragment_schedule.xml, the layout of each entry is in blog_row.xml, The following is my code sample;
fragment_schedule.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".ScheduleFragment"
android:orientation="vertical"
android:background="#drawable/blackboard2">
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/myrecycleView">
</android.support.v7.widget.RecyclerView>
blog_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
app:cardCornerRadius="12dp"
android:elevation="90dp"
android:layout_margin="7dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_date"
android:text="Date"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_time"
android:text="Time"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_event"
android:text="Event"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_moderator"
android:text="Moderator"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_venue"
android:text="Venue"/>
</LinearLayout>
</android.support.v7.widget.CardView>
ScheduleFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ScheduleFragment extends Fragment {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
public ScheduleFragment() {
// Required empty public constructor
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Schedule,ScheduleViewHolder>firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<Schedule, ScheduleViewHolder>
(Schedule.class,R.layout.blog_row,ScheduleViewHolder.class, mDatabase) {
#Override
protected void populateViewHolder(ScheduleViewHolder viewHolder, Schedule
model, int position) {
viewHolder.setEvent_name( model.getEvent_name() );
viewHolder.setEvent_date( model.getEvent_date() );
viewHolder.setEvent_moderator( model.getEvent_moderator() );
viewHolder.setEvent_time( model.getEvent_time() );
viewHolder.setEvent_venue( model.getEvent_venue() );
}
};
mBlogList.setAdapter( firebaseRecyclerAdapter );
}
public static class ScheduleViewHolder extends RecyclerView.ViewHolder{
View mView;
public ScheduleViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setEvent_name(String event_name){
TextView post_event = (TextView)mView.findViewById( R.id.post_event );
post_event.setText( event_name );
}
public void setEvent_moderator(String event_moderator){
TextView post_moderator = (TextView)mView.findViewById( R.id.post_moderator );
post_moderator.setText( event_moderator );
}
public void setEvent_time(String event_time){
TextView post_time = (TextView)mView.findViewById( R.id.post_time );
post_time.setText( event_time );
}
public void setEvent_venue(String event_venue){
TextView post_venue = (TextView)mView.findViewById( R.id.post_venue );
post_venue.setText( event_venue );
}
public void setEvent_date(String event_date) {
TextView post_date = (TextView)mView.findViewById( R.id.post_date );
post_date.setText( event_date );
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_schedule, container, false);
mDatabase = FirebaseDatabase.getInstance().getReference().child("schedule");
mDatabase.keepSynced(true);
mBlogList = (RecyclerView) view.findViewById(R.id.myrecycleView);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
Schedule.java
public class Schedule {
private String event_name;
private String event_date;
private String event_moderator;
private String event_time;
private String event_venue;
public Schedule(String event_name, String event_date, String event_moderator, String
event_time, String event_venue) {
this.event_name = event_name;
this.event_date = event_date;
this.event_moderator = event_moderator;
this.event_time = event_time;
this.event_venue = event_venue;
}
public String getEvent_name() {
return event_name;
}
public void setEvent_name(String event_name) {
this.event_name = event_name;
}
public String getEvent_date() {
return event_date;
}
public void setEvent_date(String event_date) {
this.event_date = event_date;
}
public String getEvent_moderator() {
return event_moderator;
}
public void setEvent_moderator(String event_moderator) {
this.event_moderator = event_moderator;
}
public String getEvent_time() {
return event_time;
}
public void setEvent_time(String event_time) {
this.event_time = event_time;
}
public String getEvent_venue() {
return event_venue;
}
public void setEvent_venue(String event_venue) {
this.event_venue = event_venue;
}
public Schedule()
{
}
}
Everything seems fine and the application runs but the fragment is blank. I have gone over the code time and again and I can't find where I may have made a mistake. Please help
You are using an old version of FirebaseUI, you need to remove mBlogList.setHasFixedSize(true); so the data will appear in the page.
This was a bug in the older versions check here:
https://github.com/firebase/FirebaseUI-Android/issues/204
Related
I am unable to display the image (only) in RecyclerView stored in Firebase Storage, while I'm displaying the other text data in the recyclerView.
I browse through a lot of questions but i didn't find the answer for me .
hint: all roles for Realtime Database , Firebase Storage is set either to [true or test mode]
hint : below is the link for out put image :
https://i.stack.imgur.com/dagbA.jpg
data model
import com.google.firebase.database.Exclude;
public class House {
#Exclude
private String key;
//owner name
private String name ;
//location
private String Location;
//image
private String imageUrl;
/*all start with [RealState] (realTimeDatabase/storage)*/
/*
* [RealStateData] - database
* [RealStatePictures] - storage
* */
public House() {
//required
}
public House(String name, String location, String imageUrl) {
if (name.trim().equals("") || name.isEmpty()){
name = "realState company";
}
this.name = name;
Location = location;
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
#Exclude
public String getKey() {
return key;
}
#Exclude
public void setKey(String key) {
this.key = key;
}
}
Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import com.techmarinar.royalhomes.data.House;
import java.util.List;
public class HouseAdapter extends RecyclerView.Adapter<HouseAdapter.HouseHolder> {
private static final String TAG = "HouseAdapter";
private Context mContext;
private List<House> houseList;
public HouseAdapter(Context mContext, List<House> houseList) {
this.mContext = mContext;
this.houseList = houseList;
}
public void setUploads(List<House> uploads) {
this.houseList = uploads;
this.notifyDataSetChanged();
}
#NonNull
#Override
public HouseHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(mContext)
.inflate(R.layout.list_item,parent,false);
return new HouseHolder(v);
}
#Override
public void onBindViewHolder(#NonNull HouseHolder holder, int position) {
//house object
House house = houseList.get(position);
holder.name.setText(house.getName());
holder.location.setText(house.getLocation());
// holder.image.setImageURI(Uri .parse(house.getImageUrl());
String imageUrl = house.getImageUrl();
Glide.with(mContext)
.load(imageUrl)
.placeholder(R.drawable.ic_baseline_add_business_24)
.centerCrop()
.into(holder.image);
}
#Override
public int getItemCount() {
return houseList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class HouseHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView name;
private TextView location ;
public HouseHolder(#NonNull View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.xHouseImage);
name = (TextView) itemView.findViewById(R.id.xHouseName);
location = (TextView) itemView.findViewById(R.id.xHouseLocation);
}
}
}
MainActicity -- recyclerclass
package com.techmarinar.royalhomes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.techmarinar.royalhomes.data.House;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements MenuItem.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
//widget
private RecyclerView mRecycler;
private ProgressBar mProgress;
//firebase Element
private StorageReference storageReference;
private DatabaseReference databaseReference;
//Adapters var
private List<House> houseList;
private HouseAdapter mAdapter;
private ValueEventListener getFirebaseData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set Widget
setupUIWidget();
//init firebase
initiateFireBaseElement();
//set recyclerView
setupRecyclerView();
//get data from fire(storage/fireDataBase);
getHousesDataFromFireBase();
//setup Item Touch Helper
setupItemTouchHelper(mRecycler , mAdapter);
}
private void setupUIWidget() {
setTitle("home");
//widget
mProgress = (ProgressBar) findViewById(R.id.progress_circular);
mRecycler = (RecyclerView) findViewById(R.id.recycler);
FloatingActionButton mActionButton = (FloatingActionButton) findViewById(R.id.floatingBtn);
//ActionButton
mActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this, "wow", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this , EditHouse.class));
}
});
}
private void initiateFireBaseElement() {
//fireBase reference
databaseReference = FirebaseDatabase.getInstance().getReference("RealStateData");
storageReference= FirebaseStorage.getInstance().getReference("RealStatePictures") ;
}
private void setupRecyclerView() {
Log.d(TAG, "setupRecyclerView: ");
houseList = new ArrayList<>();
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mRecycler.setHasFixedSize(true);
//mRecycler.setHasStableIds(true);
//init adapter
mAdapter = new HouseAdapter(MainActivity.this,houseList);
//set adapter to the recyclerView
mRecycler.setAdapter(mAdapter);
}
private void getHousesDataFromFireBase() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
houseList.clear();
for (DataSnapshot data : snapshot.getChildren()) {
//init house object
House houseValues = data.getValue(House.class);
// houseValues.setKey(data.getKey());
//fill the list
houseList.add(houseValues);
}
//notify the adapter
mAdapter.setUploads(houseList);
//mAdapter.notifyDataSetChanged();
//hide the progressBar
mProgress.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: " + error.getMessage());
Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
//hide progressbar
mProgress.setVisibility(View.INVISIBLE);
}
});
}
private void setupItemTouchHelper(RecyclerView mRecycler, HouseAdapter mAdapter) {
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
}).attachToRecyclerView(mRecycler);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu
MenuItem addNewHouse , deleteHouse , updateHouse;
addNewHouse= menu.add(0,1,1,"add house");
addNewHouse.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
addNewHouse.setIcon(R.drawable.ic_baseline_supervised_user_circle_24);
updateHouse= menu.add(0,2,2,"update house");
deleteHouse= menu.add(0,3,3,"delete house");
addNewHouse.setOnMenuItemClickListener(this);
updateHouse.setOnMenuItemClickListener(this);
deleteHouse.setOnMenuItemClickListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case 1:
Toast.makeText(this, "new house", Toast.LENGTH_SHORT).show();
return true;
case 2:
Toast.makeText(this, "update house data", Toast.LENGTH_SHORT).show();
return true;
case 3:
Toast.makeText(this, "delete house data", Toast.LENGTH_SHORT).show();
return true;
default:return false;
}
}
}
here is xml files
List item:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="2dp"
app:cardBackgroundColor="#color/purple_200"
app:cardElevation="12dp"
app:cardCornerRadius="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp">
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#color/purple_200"/>
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"/>
<ImageView
android:id="#+id/xHouseImage"
android:layout_width="match_parent"
android:layout_height="220dp"
android:adjustViewBounds="true" />
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"/>
<TextView
android:id="#+id/xHouseLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="house Location"
android:layout_margin="4dp"
android:layout_marginStart="6dp"
android:fontFamily="sans-serif-light"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:textColor="#color/black"
android:textSize="33sp"/>
<TextView
android:id="#+id/xHouseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="house owner name"
android:layout_margin="4dp"
android:layout_marginStart="8dp"
android:fontFamily="sans-serif-light"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/black"
android:textSize="16sp"
android:gravity="top|center_vertical" />
</LinearLayout>
</androidx.cardview.widget.CardView>
recycler
<?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"
android:layout_margin="8dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_goneMarginBottom="8dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.029" />
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.446"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.406" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_baseline_home_work_24"
android:backgroundTint="#color/white"
android:foregroundGravity="bottom|right"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.945" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try this applyDefaultRequestOptions Method for Center crop of the image
Glide.with(mContext)
.applyDefaultRequestOptions(RequestOptions().centerCrop())
.load(imageUrl)
.placeholder(R.drawable.ic_baseline_add_business_24)
.into(target!!)
the problem was in Manifest.xml security issuess.
solution :
adding
android:usesCleartextTraffic="true"
to the application section
I am slightly new to Firebase implementation, and would appreciate any help in the display of my Firebase data in my Android application. There are no specifics in "what data" should be displayed, I am simply attempting to populate the entire database into the application. There are also NOT specific user auth's, the database is shared by all users for the sake of this application.
Here is my Cart.java (Where I would like the data to populate)
package edu.phoenix.mbl402.week2apptt2163;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class sunglass1 extends AppCompatActivity {
private FirebaseAuth mAuth;
private String TAG;
int minteger = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sunglass2);
mAuth = FirebaseAuth.getInstance();
Button button = (Button) findViewById(R.id.addcart);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Octagon Glasses");
myRef.setValue("$64");
Toast.makeText(getBaseContext(), "Added to Cart", Toast.LENGTH_SHORT).show();
}
});
Button button2 = (Button) findViewById(R.id.viewcart);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCart();
}
});
}
public void openCart() {
Intent intent = new Intent(this, cart.class);
startActivity(intent);
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}}
Here is the cart.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/activity_main"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</RelativeLayout>
Here is my cartadapter.java:
package edu.phoenix.mbl402.week2apptt2163;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class cartadapter extends RecyclerView.Adapter<cartadapter.MyViewHolder> {
private List<cartitems> cartList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, price;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
price = (TextView) view.findViewById(R.id.price);
}
}
public cartadapter(List<cartitems> moviesList) {
this.cartList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cart_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
cartitems items = cartList.get(position);
holder.title.setText(items.getTitle());
holder.price.setText(items.getPrice());
}
#Override
public int getItemCount() {
return cartList.size();
}
}
And of course, cartitems.java:
package edu.phoenix.mbl402.week2apptt2163;
public class cartitems {
private String title, price;
public cartitems() {
}
public cartitems(String title, String price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getPrice() {
return price;
}
public void setPrice(String year) {
this.price = price;
}
}
Here is the cart_list_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingBottom="#dimen/row_padding_vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/row_padding_vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textColor="#color/title"
android:textSize="40dp"
android:text="Your Cart"
android:gravity="center"
android:textStyle="bold" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="#+id/price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title" />
</RelativeLayout>
Thank you for absolutely any help,
if you don't use authentication and no error(or Exception) comes then i think you must set auth == null in firebase console database rule part.and if you also done it then check variable name of the class cartitems should same as firebase variable.
How to switch layout when RecyclerView is List to Grid or vice versa.
build.gradle app level
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'de.hdodenhof:circleimageview:2.0.0'
ItemModel.java
public class ItemModel {
private String name;
private String imagePath;
public ItemModel(){
}
public ItemModel(String name, String imagePath) {
this.name = name;
this.imagePath = imagePath;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
String imageUrl[] = Constant.image;
String names[] = Constant.name;
#BindView(R.id.my_recycler_view)
RecyclerView mRecyclerView;
private RecyclerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initView();
}
private void initView() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
List list = getList();
mAdapter = new RecyclerAdapter(this, list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
}
private List getList() {
List list = new ArrayList<>();
for (int i = 0; i < imageUrl.length; i++) {
ItemModel model = new ItemModel();
model.setName(names[i]);
model.setImagePath(imageUrl[i]);
list.add(model);
}
return list;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.switch_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
finish();
break;
case R.id.switch_view:
supportInvalidateOptionsMenu();
boolean isSwitched = mAdapter.toggleItemViewType();
mRecyclerView.setLayoutManager(isSwitched ? new LinearLayoutManager(this) : new GridLayoutManager(this, 2));
mAdapter.notifyDataSetChanged();
break;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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.sunil.switchlisttogridrecyclerview.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>
</RelativeLayout>
RecyclerAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by sunil on 12/10/16.
*/
public class RecyclerAdapter extends RecyclerView.Adapter {
private List itemModels;
private Context context;
private static final int LIST_ITEM = 0;
private static final int GRID_ITEM = 1;
boolean isSwitchView = true;
public RecyclerAdapter(Context context, List itemModels) {
this.itemModels = itemModels;
this.context = context;
}
#Override
public int getItemCount() {
return itemModels.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView;
if (i == LIST_ITEM){
itemView = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.item_layout, null);
}else{
itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view_grid, null);
}
return new ItemViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemModel model = itemModels.get(position);
initializeViews(model, holder, position);
}
#Override
public int getItemViewType (int position) {
if (isSwitchView){
return LIST_ITEM;
}else{
return GRID_ITEM;
}
}
public boolean toggleItemViewType () {
isSwitchView = !isSwitchView;
return isSwitchView;
}
private void initializeViews(ItemModel model, final RecyclerView.ViewHolder holder, int position) {
String imageUrl = model.getImagePath();
if (imageUrl != null && !imageUrl.isEmpty()){
Glide.with(context)
.load(imageUrl)
.into(((ItemViewHolder)holder).imageView);
}
((ItemViewHolder)holder).name.setText(model.getName());
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.name)
TextView name;
#BindView(R.id.imageView)
ImageView imageView;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<de.hdodenhof.circleimageview.CircleImageView
android:src="#mipmap/ic_launcher"
android:id="#+id/imageView"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:text="name"
android:textStyle="bold"
android:layout_alignBaseline="#id/imageView"
android:layout_margin="10dp"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_toRightOf="#+id/imageView"/>
</RelativeLayout>
item_layout_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="0dp">
<RelativeLayout
android:padding="10dp"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:src="#mipmap/ic_launcher"
android:id="#+id/imageView"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:text="name"
android:textStyle="bold"
android:layout_margin="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"/>
</RelativeLayout>
</RelativeLayout>
I have a database where my data looks like this.
I have used Firebase Recycler Adapter to the info for S1, S2 and so on, to represent that data in a recycler view. However the data is not showing only in my application. The application is for a teacher to see whether the student is present or not by retrieving data from Firebase.
AttendaceFrag.java
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class AttendanceFrag extends Fragment {
RecyclerView recyclerView;
DatabaseReference databaseReference;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_attendance_frag, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
databaseReference = FirebaseDatabase.getInstance().getReference().child("Student");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
Toast.makeText(getContext(), "Data to show", Toast.LENGTH_LONG).show();
startShowing();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return v;
}
private void startShowing() {
FirebaseRecyclerAdapter<Student, AttendanceFrag.RequestViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Student, AttendanceFrag.RequestViewHolder>(
Student.class,
R.layout.custom_row,
AttendanceFrag.RequestViewHolder.class,
databaseReference
) {
#Override
protected void populateViewHolder(AttendanceFrag.RequestViewHolder viewHolder, Student model, int position) {
viewHolder.setName(model.getName());
viewHolder.setAp(model.getAp());
viewHolder.setRegno(model.getRegno());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class RequestViewHolder extends RecyclerView.ViewHolder {
View mView;
public RequestViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView stname = (TextView) mView.findViewById(R.id.st_name);
stname.setText(name);
}
public void setRegno(String regno) {
TextView stregno = (TextView) mView.findViewById(R.id.st_regno);
stregno.setText(regno);
}
public void setAp(String ap) {
TextView stap = (TextView) mView.findViewById(R.id.st_ap);
stap.setText(ap);
}
}
}
Student.java
public class Student {
private String name, regno,ap;
public Student(String name, String regno, String ap) {
this.name = name;
this.regno = regno;
this.ap = ap;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegno() {
return regno;
}
public void setRegno(String regno) {
this.regno = regno;
}
public String getAp() {
return ap;
}
public void setAp(String ap) {
this.ap = ap;
}
}
activity_attendance_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:padding="3dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.xxx.AttendanceFrag">
<TableLayout
android:id="#+id/table_lay"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow
android:id="#+id/firstrow"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:background="#drawable/r1"
android:text="Sr. No."
android:id="#+id/srnohead"
android:textAlignment="center"
android:padding="5dp"
android:textColor="#color/colorPrimaryDark"
/>
<TextView
android:padding="5dp"
android:textAlignment="center"
android:background="#drawable/r1"
android:text="Reg. Number"
android:layout_width="135dp"
android:id="#+id/regNohead"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="Name"
android:textAlignment="center"
android:layout_height="wrap_content"
android:layout_width="120dp"
android:id="#+id/namehead"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="P/A"
android:layout_height="wrap_content"
android:id="#+id/attnhead"
android:textColor="#color/colorPrimaryDark"/>
</TableRow>
</TableLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/table_lay"
android:layout_alignParentStart="true"
android:layout_marginTop="33dp" />
</RelativeLayout>
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:padding="3dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#drawable/r1"
android:text="Sr. No."
android:id="#+id/st_sr"
android:textAlignment="center"
android:padding="5dp"
android:textColor="#color/colorPrimaryDark"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="135dp"
android:padding="5dp"
android:textAlignment="center"
android:background="#drawable/r1"
android:text="Reg. Number"
android:id="#+id/st_regno"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="Name"
android:textAlignment="center"
android:layout_height="wrap_content"
android:layout_width="120dp"
android:id="#+id/st_name"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:layout_width="wrap_content"
android:padding="5dp"
android:background="#drawable/r1"
android:text="P/A"
android:layout_height="wrap_content"
android:id="#+id/st_ap"
android:textColor="#color/colorPrimaryDark"/>
</LinearLayout>
put this in your App level gradle : implementation 'com.firebaseui:firebase-ui-database:3.2.1'
In your onStart method put this :
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Blog")
.limitToLast(50);
FirebaseRecyclerOptions<BlogModel> options =
new FirebaseRecyclerOptions.Builder<BlogModel>()
.setQuery(query, BlogModel.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<BlogModel, BlogViewHolder>(options) {
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_blog, parent, false);
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(BlogViewHolder holder, int position, BlogModel model) {
holder.setTitleBlog(model.getTitle());
holder.setTitleDesc(model.getDescription());
holder.setImage(getApplicationContext(), model.getImage_url());
}
};
adapter.startListening();
mRecycler.setAdapter(adapter);
}
in your BlogViewHolder put this :
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View view;
public BlogViewHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setTitleBlog(String title) {
TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
tvTitle.setText(title);
}
public void setTitleDesc(String desc) {
TextView tvDesc = (TextView) view.findViewById(R.id.tv_desc);
tvDesc.setText(desc);
}
public void setImage(Context context, String url) {
ImageButton ib = (ImageButton) view.findViewById(R.id.ib_blog);
Picasso.with(context).load(url).into(ib);
}
}
And your are all set to go :)
Your database reference pointing wrong node you can use it like this:
FirebaseDatabase.getInstance().getReferenceFromUrl("https://facapp-bee2.firebaseio.com/");
Then .child("Faculty/Student") and recylerview don't use addValueListener. Here you can find how to use recycler view in firebase
Two issue with List Fragment: 1. I have a class that extends ListFragments.In the onCreated, I am setting my custom Adapter. The issue is that when the user logs in, the adadpter is null and would not have a value until the user searches for an owner. As a result, it throws an exception when it tries to set up the listadapter and it finds the ArrayAdapter object to be null. I have a custome layout that has a listview and a textview, but I still gets the error. See sample code below. I bold the line of code where the issue happens. Also, I bold few other section where I think it may be important to notice.
I implemented Parcelable in the class "Owner" so that I can pass the object as a ParcelableArray. Even though the object is not null, retrieving it in the OwnerDetail class shows null as if I did not pass it it. I've seen several example, but I am not able to get it right. What am I doing wrong here?
Note: If I were to call the AsyncTask in the OwnerDetail class and set the ListAdapter, it will work fine. The issue with that is that it will display a list of owners as soon as the user is logged in which is not the expected behavior. The behavior that I want is to login first, search for an owner, display the owner, double click on an owner, and finally display a list of cars that the owner owns. I am doing this project, so I can learn how to use ListFraments.
// Here is the entire code
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Car implements Parcelable {
private String _make;
private String _model;
private String _year;
public Car()
{
this._make = "";
this._model = "";
this._year = "";
}
public Car(String make)
{
this._make = make;
}
public Car(String make, String year)
{
this._make = make;
this._year = year;
}
public Car(String make, String model, String year)
{
this._make = make;
this._model = model;
this._year = year;
}
//Getters
public String getMake()
{
return _make;
}
public String getModel()
{
return _model;
}
public String getYear()
{
return _year;
}
//Setters
public void setMake(String make)
{
_make = make;
}
public void setModel(String model)
{
_model = model;
}
public void setYear(String year)
{
_year = year;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
package com.mb.carlovers;
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.ArrayAdapter;
public class CarDetail extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
String[] myCars = {};
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> carAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, myCars);
setListAdapter(carAdapter);
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Login extends Activity implements OnClickListener{
private Button btnLogin;
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initializeVariables();
}
public void initializeVariables()
{
btnLogin = (Button) this.findViewById(R.id.bLogin);
etUsername = (EditText)this.findViewById(R.id.etUserName);
etPassword = (EditText)this.findViewById(R.id.etPassword);
btnLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
Log.i("Tag", "In Onclick Litener");
String uName = etUsername.getText().toString();
String pWord = etPassword.getText().toString();
if(uName.equals("owner") && pWord.equals("1234"))
{
Log.i("Tag", "username =" + uName + "Password =" + pWord);
Intent intent = new Intent(this, People.class);
startActivity(intent);
}
}
}
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Owner implements Parcelable {
private String _firstName;
private String _lastName;
private String _carId;
private Car _car;
public Owner()
{
this._firstName = "";
this._lastName = "";
this._carId = "";
}
public Owner(String lName)
{
this._lastName = lName;
}
public Owner(String lName, String cId)
{
this._lastName = lName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId, Car car)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
this._car = car;
}
//Getters
public String getFirstName()
{
return _firstName;
}
public String getLastName()
{
return _lastName;
}
public String getCarId()
{
return _carId;
}
public Car getCar()
{
return _car;
}
//Setters
public void setFirstName(String fName)
{
_firstName = fName;
}
public void setLastName(String lName)
{
_lastName = lName;
}
public void setCarId(String cId)
{
_carId = cId;
}
public void setCar(Car car)
{
_car = car;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(_firstName);
dest.writeString(_lastName);
dest.writeString(_carId);
dest.writeParcelable(_car, flags);
}
public Owner(Parcel source){
_firstName = source.readString();
_lastName = source.readString();
_carId = source.readString();
_car = source.readParcelable(Car.class.getClassLoader());
}
public class MyCreator implements Parcelable.Creator<Owner> {
public Owner createFromParcel(Parcel source) {
return new Owner(source);
}
public Owner[] newArray(int size) {
return new Owner[size];
}
}
}
package com.mb.carlovers;
import com.mb.carlovers.adapter.OwnerAdapter;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container, false);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Owner[] myOwners = null;
super.onCreate(savedInstanceState);
Bundle values = getActivity().getIntent().getExtras();
if(values != null)
{
myOwners = (Owner[]) values.getParcelableArray("test");
}
super.onActivityCreated(savedInstanceState);
ownerAdapter = new OwnerAdapter(getActivity(), R.layout.owner_detail , myOwners);
ownerAdapter.notifyDataSetChanged();
}
package com.mb.carlovers;
import java.util.List;
import com.mb.carlovers.asynctask.OnwerAsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class People extends FragmentActivity implements OnClickListener, OnItemSelectedListener {
private Button search;
private EditText etSearchBy, etSearchByID;
private Spinner spOption;
private String selectedOption = null;
private TextView tvErrorMessage;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.people);
InitializeVariables();
}
private void InitializeVariables()
{
etSearchBy = (EditText) this.findViewById(R.id.etByLastName);
etSearchByID = (EditText) this.findViewById(R.id.etCarID);
spOption = (Spinner) this.findViewById(R.id.spOption);
search = (Button) this.findViewById(R.id.bSearch);
search.setOnClickListener(this);
tvErrorMessage = (TextView) this.findViewById(R.id.tvErrorMessage);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.spOptions, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOption.setAdapter(adapter);
spOption.setOnItemSelectedListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
String searchByName = etSearchBy.getText().toString();
String searchById = etSearchByID.getText().toString();
if(selectedOption == null || selectedOption == "All")
{
if(searchByName.matches("") || searchById.matches(""))
{
tvErrorMessage.setText("You must select a last name and car id");
} else
{
}
} else if(selectedOption == "Name")
{
if(!searchByName.matches(""))
{
OnwerAsyncTask asynTask = new OnwerAsyncTask();
List<Owner> lt = null;
try {
lt = asynTask.execute("").get();
} catch (Exception e) {
e.printStackTrace();
}
Owner myOwners[] = lt.toArray(new Owner[lt.size()]);
Bundle data = new Bundle();
data.putParcelableArray("test", myOwners);
} else
{
tvErrorMessage.setText("You must enter the last name of the owner.");
}
} else if (selectedOption == "ID")
{
if(!searchById.matches(""))
{
String st = null;
String d = st;
} else
{
tvErrorMessage.setText("You must enter the car id that you'd like to search.");
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
switch(pos)
{
case 0:
selectedOption = "All";
break;
case 1:
selectedOption ="Name";
break;
case 2:
selectedOption ="ID";
break;
default:
selectedOption = null;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedOption ="ALL";
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Car;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CarAdapter extends ArrayAdapter<Car> {
private Context context;
private int layoutResourceId;
private Car data[] = null;
public CarAdapter(Context context, int resource, Car[] data) {
super(context, resource, data);
this.context = context;
this.layoutResourceId = resource;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CarHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CarHolder();
holder.tvMake = (TextView) row.findViewById(R.id.tvMake);
holder.tvModel = (TextView) row.findViewById(R.id.tvModel);
holder.tvYear = (TextView) row.findViewById(R.id.tvYear);
row.setTag(holder);
} else
{
holder = (CarHolder) row.getTag();
}
Car item = data[position];
holder.tvMake.setText(item.getMake().toString());
holder.tvModel.setText(item.getModel().toString());
holder.tvYear.setText(item.getYear().toString());
return row;
}
public static class CarHolder
{
TextView tvMake;
TextView tvModel;
TextView tvYear;
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Owner;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class OwnerAdapter extends ArrayAdapter<Owner> {
private Context context;
private int layoutResourceId;
private Owner data[] = null;
public OwnerAdapter(Context context, int textViewResourceId,Owner[] data) {
super(context, textViewResourceId, data);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OwnerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OwnerHolder();
holder.tvFName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCId = (TextView) row.findViewById(R.id.tvCarID);
row.setTag(holder);
} else
{
holder = (OwnerHolder) row.getTag();
}
Owner item = data[position];
holder.tvFName.setText(item.getFirstName());
holder.tvLName.setText("Example");
holder.tvCId.setText("1");
return row;
}
static class OwnerHolder
{
TextView tvFName;
TextView tvLName;
TextView tvCId;
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Car;
import android.os.AsyncTask;
public class CarAsyncTask extends AsyncTask<String, Void, List<Car>> {
private List<Car> item = null;
#Override
protected List<Car> doInBackground(String... params) {
item = new ArrayList<Car>();
item.add(new Car("Chevy","Caprice","2002"));
item.add(new Car("Chevy","Malibu","2014"));
item.add(new Car("Dodge","Stratus","2002"));
item.add(new Car("Saturn","L300","2004"));
return item;
}
#Override
protected void onPostExecute(List<Car> result) {
super.onPostExecute(result);
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Owner;
import android.os.AsyncTask;
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
#Override
protected List<Owner> doInBackground(String... params) {
try
{
items = new ArrayList<Owner>();
Owner own = new Owner();
own.setFirstName("John");
own.setLastName("Smith");
own.setCarId("1");
items.add(own);
Owner own1 = new Owner();
own1.setFirstName("Samantha");
own1.setLastName("Right");
own1.setCarId("2");
items.add(own1);
Owner own2 = new Owner();
own2.setFirstName("Regie");
own2.setLastName("Miller");
own2.setCarId("3");
items.add(own2);
Owner own3 = new Owner();
own3.setFirstName("Mark");
own3.setLastName("Adam");
own3.setCarId("4");
items.add(own3);
} catch(Exception ex)
{
ex.toString();
}
return items;
}
#Override
protected void onPostExecute(List<Owner> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
// car_detail.xml
<?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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Car Detail Page" />
</LinearLayout>
// car_row.xml
<?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="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvMake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvModel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
//customize_layout.xml
<?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="match_parent"
android:orientation="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No record to be displayed."
/>
</LinearLayout>
//Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".Login" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etUserName"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
>
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etPassword"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:inputType="textPassword" />
<Button
android:id="#+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:text="Login" />
</LinearLayout>
//owner_detail.xml
<?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="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvCarID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
// People.xml
<?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="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by last name"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
/>
<EditText
android:id="#+id/etByLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by car id"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<EditText
android:id="#+id/etCarID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<Spinner
android:id="#+id/spOption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/spOptions"
/>
<TextView
android:id="#+id/tvErrorMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:layout_marginTop="10dp"
android:text="" />
<Button
android:id="#+id/bSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="2"
>
<fragment
android:id="#+id/fOwnerDetail"
android:name="com.mb.carlovers.OwnerDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<fragment
android:id="#+id/fragment1"
android:name="com.mb.carlovers.CarDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
/>
</LinearLayout>
</LinearLayout>
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(ownerAdapter);
}
}
Your code has a lot of problems:
1 Never call lifecycle methods on your own like you do in the OwnerDetail class with super.onActivityCreated(savedInstanceState);
2 Bundle values = getActivity().getIntent().getExtras(); ... values.getParcelableArray("test"); will normally fail because this piece of code will get the activity reference, get the Intent that started the activity and then try to find data passed in under the test key in that Intent. You don't pass such data to the People activity so there will be nothing to be found. You'd normally want to pass a Bundle containing the data at the moment of the creation of the fragment.
3 If you use the fragment in the xml layout you'll not be able to use a Bundle to pass data, instead you either add the fragment manually with transactions and then use a Bundle or you create a setter method in the fragment class and use that. So instead of Bundle data = new Bundle(); data.putParcelableArray("test", myOwners);, which does nothing, get a reference to your fragment and pass the myOwners array through a method.
4 Your AsyncTask will be pretty useless if you use them with .get() because the get() method will wait the AsyncTask to finish, blocking the UI tread as well. Instead you should just start the AsyncTask and then in the onPostExecute() pass the data around.
Here is an example with a simple method which will not change most of your code(which will happen if you manually add the fragments):
// where you start the owner asynctask
if(!searchByName.matches("")) {
OnwerAsyncTask asynTask = new OnwerAsyncTask(People.this);
asynTask.execute("");
}
//...
Then change the OnwerAsyncTask like this:
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
private FragmentActivity mActivity;
public OnwerAsyncTask(FragmentActivity activity) {
mActivity = activity;
}
// doInBackground()...
#Override
protected void onPostExecute(List<Owner> result) {
//I'm assuming that items is the data you want to return, so
// find the OwnerDetail fragment and directly assign the data
OwnerDetail fragment = (OwnerDetail)mActivity.getSupportFragmentManager().findFragmentById(R.id.fOwnerDetail);
fragment.setData(); // to setData you'll pass the data you have in the AsyncTask
// the items list? or you transform that into an array?
}
and in the OwnerDetail fragment:
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
public void setData() {
// update the adapter, create a new one etc.
}