So I was trying to make a listview inside the fragment, although the code works, this list itself looks wierd. Here's a picture of it.
I'd appreciate your help in figuring out why the list looks strange.
ussd.java (Fragment)
package layout;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.buckydroid.app.droidcpu.R;
import com.buckydroid.app.droidcpu.ussdadaper;
import com.buckydroid.app.droidcpu.ussdz;
import com.google.android.gms.tagmanager.Container;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link ussd.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link ussd#newInstance} factory method to
* create an instance of this fragment.
*/
public class ussd extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ListView listView;
private ussdadaper ussd;
private List<ussdz> ussdlist;
private OnFragmentInteractionListener mListener;
public ussd() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ussd.
*/
// TODO: Rename and change types and number of parameters
public static ussd newInstance(String param1, String param2) {
ussd fragment = new ussd();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
View rootView = inflater.inflate(R.layout.fragment_ussd, container, false);
listView = (ListView)rootView.findViewById(R.id.listView);
ussdlist = new ArrayList<>();
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussd = new ussdadaper(getActivity(),ussdlist);
listView .setAdapter(ussd); //you should setthe adapter to the listview
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteractionHome(Uri uri);
public void openHome(View view);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
Adapter
package com.buckydroid.app.droidcpu;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by BuckyDroid on 14-06-2016.
*/
public class ussdadaper extends BaseAdapter {
private Context ussds;
private List<ussdz> ussdlist;
public ussdadaper(Context ussds, List<ussdz> ussdlist) {
this.ussds = ussds;
this.ussdlist = ussdlist;
}
#Override
public int getCount() {
return ussdlist.size();
}
#Override
public Object getItem(int position) {
return ussdlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v= View.inflate(ussds,R.layout.item_listview,null);
TextView ussdcode = (TextView)v.findViewById(R.id.textView1);
TextView ussddesc = (TextView)v.findViewById(R.id.textView2);
ussdcode.setText(ussdlist.get(position).getUSSD());
ussddesc.setText(ussdlist.get(position).getDescription());
return v;
}
}
ussdz.java
package com.buckydroid.app.droidcpu;
/**
* Created by BuckyDroid on 14-06-2016.
*/
public class ussdz
{
private int id;
private String USSD;
private String Description;
public ussdz(String description, String s) {
Description = description;
this.USSD = USSD;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUSSD() {
return USSD;
}
public void setUSSD(String USSD) {
this.USSD = USSD;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
item_listview.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="wrap_content"
android:background="#android:color/transparent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/lyt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="1px"
android:gravity="left|top"
android:padding="2dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:layout_weight="5"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:gravity="left|top"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Name"
android:textStyle="bold"/>
<TextView
android:gravity="left|top"
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:paddingLeft="5dp"
android:paddingRight="10dp"
android:text=":" />
<TextView
android:textStyle="bold"
android:gravity="left|top"
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_weight="6"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"/>
</LinearLayout>
</LinearLayout>
Update:
fragment's xml file
<FrameLayout 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="layout.ussd">
<!-- TODO: Update blank fragment layout -->
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center" />
</FrameLayout>
In your ussdz object your are not settign the USSD:
public ussdz(String description, String s) {
Description = description;
this.USSD = USSD; //No need to do that, it will be still null
this.id = id; //No need to do that, it will be still null
}
so you can add the SDD value in constructor:
private int id;
private String USSD;
private String description;
public ussdz(int mId, String mDescription, String mUSSD) {
description = mDescription;
this.USSD = mUSSD;
this.id = mId;
}
And construct an object like:
ussdz myObject = new ussdz(1, "description", "4529697");
Related
Wanna make to search with using EditText when I click it from ListView. I made it with some youtube videos or blogs. Mixed up those and of course, There's error. What should fix? I put my every codes to understand it. Need you guys help a lot.
<?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=".Playbook">
<ListView
android:id="#+id/listView2"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_baseline_search_24"
android:id="#+id/searchImage" />
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_toRightOf="#id/searchImage"
android:id="#+id/editTextFilter"/>
<TextView
android:id="#+id/termName"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editTextFilter"
style="#style/TextAppearance.AppCompat.Title"
android:text="Term"/>
</RelativeLayout>
This is layout part.
package com.example.gridiron;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Playbook#newInstance} factory method to
* create an instance of this fragment.
*/
public class Playbook extends Fragment {
ArrayList<PlaybookList> arrayList2;
ListView listView2;
private static PlaybookListAdapter playbookListAdapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Playbook() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Playbook.
*/
// TODO: Rename and change types and number of parameters
public static Playbook newInstance(String param1, String param2) {
Playbook fragment = new Playbook();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_playbook, container, false);
ListView listView2 = (ListView) view.findViewById(R.id.listView2);
EditText editTextFilter = (EditText) view.findViewById(R.id.editTextFilter);
ArrayList<PlaybookList> arrayList2 = new ArrayList<>();
arrayList2.add(new PlaybookList("Quarterback", "https://namu.wiki/w/%EC%BF%BC%ED%84%B0%EB%B0%B1"));
arrayList2.add(new PlaybookList("Runningback", "https://namu.wiki/w/%EB%9F%AC%EB%8B%9D%EB%B0%B1"));
PlaybookListAdapter playbookListAdapter = new PlaybookListAdapter(getActivity(), R.layout.list_row2, arrayList2);
listView2.setAdapter(playbookListAdapter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable edit) {
String filterText = edit.toString();
if (filterText.length() > 0) {
listView2.setFilterText(filterText);
} else {
listView2.clearTextFilter();
}
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayList2.get(position).getTermURL())));
getActivity().startActivity(intent);
}
});
return view;
}
}
package com.example.gridiron;
public class PlaybookList {
String TermName;
String TermURL;
public PlaybookList(String termName, String termURL) {
TermName = termName;
TermURL = termURL;
}
public String getTermName() {
return TermName;
}
public void setTermName(String termName) {
TermName = termName;
}
public String getTermURL() {
return TermURL;
}
public void setTermURL(String termURL) {
TermURL = termURL;
}
}
package com.example.gridiron;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class PlaybookListAdapter extends ArrayAdapter<PlaybookList> {
private Context mContext;
private int mResource;
public PlaybookListAdapter(#NonNull Context context, int resource, #NonNull ArrayList<PlaybookList> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
TextView termName = convertView.findViewById(R.id.termName);
termName.setText(getItem(position).getTermName());
return convertView;
}
}
And last 3 codes are for class. It's really hard to make it. Please, Help me!
There is no ListView in your layout code. You didn't include the error but I'm pretty sure it's NullPointerException on this line:
listView2.setAdapter(playbookListAdapter);
Everything works as in other projects but for some reason I'm unable to set the projectListItems ( a recycler view ) adapter because it won't resolve setAdapter()...
binding.projectListItems.setAdapter(adapter); in the ProjectsActivity.java
Cleaned and Rebuilt project... also Invalidated cache and restarted.
ProjectsActivity.java
package com.example.poleprofilingapp.ui;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import com.example.poleprofilingapp.R;
import com.example.poleprofilingapp.databinding.ActivityProjectsBinding;
import com.example.poleprofilingapp.project.Project;
import com.example.poleprofilingapp.project.ProjectAdapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ProjectsAcitivty extends AppCompatActivity {
private ProjectAdapter adapter;
private ActivityProjectsBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_projects);
Intent intent = getIntent();
List <Project> projectsList = new ArrayList<>();
Project project = new Project();
project.setName("Project 1");
project.setAddress("Address 1");
project.setDescription("Test Project 1");
project.setType("NOVEC");
project.setCompanyKey("333555");
projectsList.add(project);
binding = DataBindingUtil.setContentView(this,
R.layout.activity_projects);
adapter = new ProjectAdapter(projectsList, this);
binding.projectListItems.setAdapter(adapter); // setAdapter not resoleved
}
}
ProjectAdaptor.java
package com.example.poleprofilingapp.project;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.example.poleprofilingapp.R;
import com.example.poleprofilingapp.databinding.ProjectListItemBinding;
import java.util.List;
public class ProjectAdapter extends RecyclerView.Adapter<ProjectAdapter.ViewHolder> {
private List<Project> projects;
private Context context;
public ProjectAdapter(List<Project> projects, Context context) {
this.projects = projects;
this.context = context;
}
#NonNull
#Override
public ProjectAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
ProjectListItemBinding binding = DataBindingUtil
.inflate(LayoutInflater.from(parent.getContext()),
R.layout.project_list_item,
parent,
false);
return new ViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull ProjectAdapter.ViewHolder holder, int position) {
Project project = projects.get(position);
holder.projectListItemBinding.setProject(project);
}
#Override
public int getItemCount() {
return projects.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
// Binding Vars
public ProjectListItemBinding projectListItemBinding;
// Constructor to do view lookups for each subview
public ViewHolder(ProjectListItemBinding projectLayoutBinding){
super(projectLayoutBinding.getRoot());
projectListItemBinding = projectLayoutBinding;
}
}
}
Project.java ( data model )
package com.example.poleprofilingapp.project;
public class Project {
private String id;
private String name;
private String address;
private String description;
private String type;
private String companyKey;
public Project() {
}
public Project(String name, String address, String description, String type, String companyKey) {
this.name = name;
this.address = address;
this.description = description;
this.type = type;
this.companyKey = companyKey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCompanyKey() {
return companyKey;
}
public void setCompanyKey(String companyKey) {
this.companyKey = companyKey;
}
}
XML - activity_projects.xml
<?xml version="1.0" encoding="utf-8"?>
<layout
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">
<data>
<variable
name="project"
type="com.example.poleprofilingapp.project.Project"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.ProjectsAcitivty">
<android.support.v7.widget.RecyclerView
android:id="#+id/projectListItems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</android.support.v7.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
projects_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<layout
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">
<data>
<variable
name="project"
type="com.example.poleprofilingapp.project.Project"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/projectListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:paddingBottom="8dp"
tools:background="#color/colorPrimaryDark">
<TextView
android:id="#+id/name"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="#{project.name}"
android:textColor="#android:color/white"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Test Project"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Inside the onCreate intialize your bindiing variable
ActivityMainBinding mBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
mBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
}
In onStart method set you layoutManager and adapter
#Override
protected void onStart() {
super.onStart();
mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
UserAdapter adapter = new UserAdapter(getApplicationContext(),usersList());
mBinding.recyclerView.setAdapter(adapter);
}
and this is list
private List<Animals> usersList(){
List<Animals> animalsList = new ArrayList<>();
String[] animals = {"Tiger","Monkey","Dog","Lion","Zebra","Horse","Cat"};
String[] types = {"Carnivore","Herbivore","Omnivore","Carnivore","Herbivore","Herbivore","Omnivore"};
int[] image = {R.drawable.all_call,R.drawable.done,R.drawable.hide,R.drawable.all_call};
for (int i=0;i<animals.length;i++){
Animals users = new Animals(
animals[i],
types[i],
image[i]
);
animalsList.add(users);
}
return animalsList;
}
So the issue was that I migrated the project over to androix but never changed the RecyclerView to support androix method. So in the build folder my generated binding class was trying to us android.support.v7..... in place of androidx.recyclerview.....
So what fixed this was updating the XML then running Invalidating the Chache / Restart...
Whala all fixed up.
I am populating a ListView of songs using Firebase database and Firebase-UI, all the dependencies are initialized correctly and the app is connected with the database but when it displays the list it doesn't display the text, just empty boxes like that:
When an item is added to the database then a box is added but it doesn't show the text. Here is the code:
Song class:
package com.example.gloriadesideri.animas;
public class Song
{
private String myName;
private String myURL;
private String myAuthor;
public Song(){
/*myName="";
myURL="";
myAuthor="";*/
}
public Song(String Author, String Song, String URL) {
this.myName=Song;
this.myURL=URL;
this.myAuthor=Author;
}
public String getName()
{
return myName;
}
public String getURL()
{
return myURL;
}
public String getAuthor()
{
return myAuthor;
}
public void setName(String name)
{
this.myName=name;
}
public void setURL ( String URL)
{
this.myURL=URL;
}
public void setAuthor(String author)
{
this.myAuthor=author;
}
}
Song Layout:
<?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"
android:orientation="vertical"
android:layout_margin="20dp"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/songName"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/author"/>
</LinearLayout>
Activity that should have the list view:
package com.example.gloriadesideri.animas;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseListAdapter;
import com.firebase.ui.database.FirebaseListOptions;
import com.google.firebase.database.ChildEventListener;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class Canzoni extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
//nav view parameters
private DrawerLayout cDrawerLayout;
private ActionBarDrawerToggle cToggle;
//list view parameters
private ListView mListView;
//firebase parameters
private FirebaseListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_canzoni);
//nav view code
cDrawerLayout= (DrawerLayout) findViewById(R.id.draw_viewC);
cToggle= new ActionBarDrawerToggle(this, cDrawerLayout,R.string.Open, R.string.Close);
cDrawerLayout.addDrawerListener(cToggle);
cToggle.syncState();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
NavigationView cNavigationView = (NavigationView) findViewById(R.id.nav_viewC);
if (cNavigationView != null)
{
cNavigationView.setNavigationItemSelectedListener(this);
}
Query mQuery= FirebaseDatabase.getInstance().getReference().child("songs");
mListView= (ListView) findViewById(R.id.canzoni_list);
FirebaseListOptions<Song> mOptions= new FirebaseListOptions.Builder<Song>()
.setLayout(R.layout.song_layout)
.setQuery(mQuery, Song.class)
.setLifecycleOwner(this)
.build();
mAdapter= new FirebaseListAdapter <Song>(mOptions){
#Override
protected void populateView(View v, Song model, int position) {
TextView songName= v.findViewById(R.id.songName);
TextView songAuthor=v.findViewById(R.id.author);
songName.setText(model.getName());
songAuthor.setText(model.getAuthor());
}
};
mListView.setAdapter(mAdapter);
}
#Override
protected void onStart() {
super.onStart();
mAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mAdapter.stopListening();
}
#Override
public boolean onOptionsItemSelected(MenuItem Item)
{
if(cToggle.onOptionsItemSelected(Item))
{
return true;
}
return super.onOptionsItemSelected(Item);
}
#Override
public boolean onNavigationItemSelected(MenuItem Item)
{
int id = Item.getItemId();
Intent intent;
if (id == R.id.preghiere)
{
intent= new Intent(this, Preghiere.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if ( id== R.id.bans)
{
intent= new Intent(this, Bans.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id== R.id.canzoni)
{
intent= new Intent(this, this.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id==R.id.calendario)
{
intent= new Intent(this, Calendario.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id== R.id.per_riflettere)
{
intent= new Intent(this, perRiflettere.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if( id== R.id.home)
{
intent= new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.draw_viewC);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
layout of the above activity
<android.support.v4.widget.DrawerLayout 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=".Canzoni"
android:id="#+id/draw_viewC">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/canzoni_list">
</ListView>
<android.support.design.widget.NavigationView
android:layout_width="239dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/white"
android:fitsSystemWindows="true"
app:headerLayout="#layout/header"
app:itemIconTint="#color/black"
app:itemTextColor="#color/black"
app:menu="#menu/drawem_menu"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp"
tools:ignore="MissingConstraints"
android:id="#+id/nav_viewC"/>
</android.support.v4.widget.DrawerLayout>
Any suggestion on how to fix this?
Edit:
the database looks like this:
both writing and reading rules are true
Edit
I have changed the private names in the Song class so they are the same as the database.
private String Author;
private String Song;
private String Url;
it starts working the problem is that now it displays just the author
Update 2
I this code fetch the user data from firebase and show data into recycled view.
In layout i used constaraint layout you can change it..
display_data.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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvData"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/dlTvEmpty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Found"
android:textSize="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
then after row_layout bind into recycler view..
row_layout.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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="#+id/rlTvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="20dp" />
<TextView
android:id="#+id/rlTvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="#+id/rlTvName" />
<TextView
android:id="#+id/rlTvPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="20dp"
app:layout_constraintTop_toBottomOf="#+id/rlTvEmail" />
</android.support.constraint.ConstraintLayout>
then after make pojo class for user that insert into firebase..
User.java
public class User {
public String name;
public String email;
public String pwd;
// Default constructor required for calls to
// DataSnapshot.getValue(User.class)
public User() {
}
public User(String name, String email,String pwd) {
this.name = name;
this.email = email;
this.pwd=pwd;
}
}
then after make adapter class.
DisplayAllData.java
public class DisplayAllData extends RecyclerView.Adapter<DisplayAllData.ItemViewHolder> {
private List<User> mUserLsit = new ArrayList<>();
private Context mContext;
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext, List<User> mUserLsit) {
this.mContext = mContext;
this.mUserLsit = mUserLsit;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user = mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
#Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName, mTvEmail, mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail = itemView.findViewById(R.id.rlTvEmail);
mTvName = itemView.findViewById(R.id.rlTvName);
mTvPwd = itemView.findViewById(R.id.rlTvPwd);
}
}
}
then after finally make display class to fetch user record from firebase and bind into recyclerview.
DisplayActivity.java
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List<User> mUserList = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
After few experiments with code like change this
songName.setText(model.getName());
songAuthor.setText(model.getAuthor());
to this
songName.setText(model.getURL());
songAuthor.setText(model.getAuthor());
I have learned that the problem was really the names I gave to the privates and the names I gave to the get-methods in the Song class. The names of the privates should be the same as the database fields and the names of the methods should be getYourPrivateName().
In your database, you have a property under the name of the song called myAuthor but in the model class, you have the field named Author, both should be the same.
To solve this, you have two solutions. First one would be to delete all the record from your database and add fresh data according to your model class. Make sure that the properties in your database are added using the name od your field that exist in your model class: myName, myURL, myAuthor and NOT Author, Song, Url.
If you are not in testing mode, then just use annotation in your model class like this:
#PropertyName("Song")
private String myName;
#PropertyName("Url")
private String myURL;
#PropertyName("Author")
private String myAuthor;
According to your edited question, you fileds are incorrect. Please how you Song class should look like:
public class Song {
private String author, song, url;
public Song() {}
public Song(String author, String song, String url) {
this.author = author;
this.song = song;
this.url = url;
}
public String getAuthor() { return author; }
public String getSong() { return song; }
public String getUrl() { return url; }
}
See the fields? Are named with the first letter lower case.
I am not familiar with how to add items to listview of a fragment , But i tried. It's not showing any error . But It's not showing anything on the application too.
well i learnt the steps for doing it from youtube . It also worked perfectly in main activity class but in fragment class it's not working.
So HELP.
Item list view:
<?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"
android:background="#android:color/transparent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/lyt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="1px"
android:gravity="left|top"
android:padding="2dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:layout_weight="5"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:gravity="left|top"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Name"
android:textStyle="bold"/>
<TextView
android:gravity="left|top"
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:paddingLeft="5dp"
android:paddingRight="10dp"
android:text=":" />
<TextView
android:textStyle="bold"
android:gravity="left|top"
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_weight="6"
android:layout_height="wrap_content"
android:textColor="#color/darker_grey"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"/>
</LinearLayout>
</LinearLayout>
ussdz.java:
package com.buckydroid.app.droidcpu;
/**
* Created by BuckyDroid on 14-06-2016.
*/
public class ussdz
{
private int id;
private String USSD;
private String Description;
public ussdz(String description, String s) {
Description = description;
this.USSD = USSD;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUSSD() {
return USSD;
}
public void setUSSD(String USSD) {
this.USSD = USSD;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
ussdadaper.java:
package com.buckydroid.app.droidcpu;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by BuckyDroid on 14-06-2016.
*/
public class ussdadaper extends BaseAdapter {
private Context ussds;
private List<ussdz> ussdlist;
public ussdadaper(Context ussds, List<ussdz> ussdlist) {
this.ussds = ussds;
this.ussdlist = ussdlist;
}
#Override
public int getCount() {
return ussdlist.size();
}
#Override
public Object getItem(int position) {
return ussdlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v= View.inflate(ussds,R.layout.item_listview,null);
TextView ussdcode = (TextView)v.findViewById(R.id.textView1);
TextView ussddesc = (TextView)v.findViewById(R.id.textView2);
ussdcode.setText(ussdlist.get(position).getUSSD());
ussddesc.setText(ussdlist.get(position).getDescription());
return v;
}
}
ussd.java (the Fragment):
package layout;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.buckydroid.app.droidcpu.R;
import com.buckydroid.app.droidcpu.ussdadaper;
import com.buckydroid.app.droidcpu.ussdz;
import com.google.android.gms.tagmanager.Container;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link ussd.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link ussd#newInstance} factory method to
* create an instance of this fragment.
*/
public class ussd extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ListView listView;
private ussdadaper ussd;
private List<ussdz> ussdlist;
private OnFragmentInteractionListener mListener;
public ussd() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ussd.
*/
// TODO: Rename and change types and number of parameters
public static ussd newInstance(String param1, String param2) {
ussd fragment = new ussd();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
listView = (ListView)container.findViewById(R.id.listView);
ussdlist = new ArrayList<>();
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussd = new ussdadaper(getActivity().getApplicationContext(),ussdlist);
return inflater.inflate(R.layout.fragment_ussd, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteractionHome(Uri uri);
public void openHome(View view);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
Replace this line :
List = (ListView)
Container.findViewById(R.id.TaskListView);
Replace the above line with the code below :
list = (ListView) getView().findViewById(R.id.TaskListView);
You are not setting the adapter to the listview
Change you onCreateView like this
View rootView = inflater.inflate(R.layout.fragment_offer_detail_item, container, false);
listView = (ListView)view.findViewById(R.id.listView);
ussdlist = new ArrayList<>();
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussd = new ussdadaper(getActivity(),ussdlist);
listView .setAdapter(ussd); //you should setthe adapter to the listview
return rootView;
Also your adapter class is not following a viewholder pattern which is error prone it would be better you change it to viewHolder pattern
//Edit:
You can easily create Adapter class by pasting the list_item xml in Layout Finder. You could make a try its simple and saves you lot of time
set adapter for listview as
listview.setAdapter(mAapter);
Try to change your OnCreateView method as;
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
View view = inflater.inflate( R.layout.fragment_ussd, container, false );
listView = (ListView)view.findViewById(R.id.listView);
ussdlist = new ArrayList<>();
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussdlist.add(new ussdz("*#44336#","Software Version Info"));
ussd = new ussdadaper(getActivity(),ussdlist);
listView.setAdapter(ussd); //Set Adapter
return view;
}
I need a listview with vertical scroll, allowing a Pull-To-Refresh effect, and each cell must allow a Swipe (to show the button below). Furthermore, the whole ListView is contained in a three tabs activity. It's very similar to Gmail app for Android, which in inbox allows vertical scrolling, swipe to Archive conversation, and click to read the email.
The general activity contains tabs (SlidingTabLayout built with an HorizontalScrollView, SlidingTabStrip, and a ViewPager), extracted from developer.android.com.
Each tab contains a fragment with a FrameLayout, and a 47degree SwipeListView, inside. They're attached here.
We have disabled the horizontal movement of tabs (they work just clicking the header
I attach the layout of the cell and the java class which handles everything, too.
I implemented 47deg SwipeList library (https://github.com/47deg/android-swipelistview).
The errors I'm facing are: On one hand, the cell with swipe is not receiving the main click, and when I do swipe, the button bellow is shown but the click is not received correctly. And if we enable pull-to-refresh, the swipe stops working well.
layout_list_item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:id="#+id/back"
android:tag="back"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#color/gold">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btFavorite"
android:background="#drawable/abc_btn_rating_star_off_mtrl_alpha"
android:layout_alignParentLeft="false"
android:adjustViewBounds="true"
android:contentDescription="Favorite"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp" />
</RelativeLayout>
<LinearLayout
android:id="#+id/front"
android:tag="front"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffffff"
android:layout_marginLeft="5dp">
<include android:id="#+id/layout_list_item_image" layout="#layout/layout_list_item_image"
android:layout_width="70dp"
android:layout_height = "70dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<include android:id="#+id/layout_list_item_content" layout="#layout/layout_list_item_content"
android:layout_width="184dp"
android:layout_toRightOf="#id/layout_list_item_image"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
/>
<include android:id="#+id/layout_list_item_status"
layout="#layout/layout_list_item_status"
android:layout_width="match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"/>
</LinearLayout>
</FrameLayout >
layout_fragment_pager_contact_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"
android:clickable="false"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:clickable="false">
<com.fortysevendeg.swipelistview.SwipeListView
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#android:id/list"
android:listSelector="#00000000"
android:layout_width="match_parent"
android:layout_height="match_parent"
swipe:swipeFrontView="#+id/front"
swipe:swipeBackView="#+id/back"
swipe:swipeActionRight="reveal"
swipe:swipeMode="right"
swipe:swipeCloseAllItemsWhenMoveList="true"
swipe:swipeOpenOnLongPress="false"
swipe:swipeAnimationTime="350"
swipe:swipeOffsetLeft="280dp"
swipe:swipeOffsetRight="280dp"
/>
<!-- View to show if the list is emtpy -->
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="No items."
android:clickable="false"/>
</FrameLayout>
</LinearLayout>
ContactListFragment.java
package com.davduran.myapp.contacts.view;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.fortysevendeg.swipelistview.SwipeListView;
import com.davduran.myapp.R;
import com.davduran.myapp.contacts.connection.ContactController;
import com.davduran.myapp.contacts.detail.ContactDetailMainActivity;
import com.davduran.myapp.util.Constants;
import com.davduran.myapp.util.Utils;
import com.davduran.myapp.view.tab.SlidingTabLayout;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import io.realm.Realm;
import model.Contact;
import model.FavouriteContact;
import model.RecentContact;
/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {#link OnFragmentInteractionListener}
* interface.
*/
public class ContactListFragment extends ListFragment {
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
private Realm realm;
private ContactController mContactController;
private ArrayList<Contact> contactList;
private ArrayList<FavouriteContact> favouriteContactList;
private ArrayList<RecentContact> recentContactList;
protected Handler handler = new Handler();
private ContactListViewArrayAdapter adapter;
private SwipeListView swipeListView;
private ListView listView;
private Parcelable state;
private TextView emptyText;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private int mIndex;
private String mParam2;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
public static ContactListFragment newInstance(int index, String param2) {
ContactListFragment fragment = new ContactListFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, index);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout_fragment_pager_contact_list, container, false);
listView = (ListView) v.findViewById(android.R.id.list);
emptyText = (TextView) v.findViewById(android.R.id.empty);
return v;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ContactListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getInstance(getActivity());
mContactController = new ContactController(getActivity(),realm);
if (getArguments() != null) {
mIndex = getArguments().getInt(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
setListAdapterTabs();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i(Constants.TAG, "ContactListFragment.onListItemClick: Listclicking");
if (mListener != null) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
//mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).getId());
Intent in = new Intent(getActivity(), ContactDetailMainActivity.class);
if(mIndex == Constants.CONTACTS_ALL) {
in.putExtra(Constants.CONTACT_ID,contactList.get(position).getId() );
startActivity(in);
} else if (mIndex == Constants.CONTACTS_RECENT) {
try {
String action = recentContactList.get(position).getAction();
if (action.compareTo("call") == 0) {
String strPhones = recentContactList.get(position).getPhones();
if (strPhones != null) {
JSONArray jPhones = new JSONArray(strPhones);
String phone = (String)((JSONObject) jPhones.get(0)).get("phone");
Utils.launchCall(phone, getActivity());
}
}
else if (action.compareTo("sms") == 0) {
String strPhones = recentContactList.get(position).getPhones();
if (strPhones != null) {
JSONArray jPhones = new JSONArray(strPhones);
String phone = (String)((JSONObject) jPhones.get(0)).get("phone");
Utils.launchSms(phone, getActivity());
}
}
else if (action.compareTo("email") == 0) {
String strEmails = recentContactList.get(position).getEmails();
if (strEmails != null) {
JSONArray jPhones = new JSONArray(strEmails);
String email = (String)((JSONObject) jPhones.get(0)).get("email");
Utils.launchEmail(email, getActivity());
}
}
} catch (Exception ex) {
Log.e(Constants.TAG, "ContactListFragment.onListItemClick: ", ex);
}
} else if (mIndex == Constants.CONTACTS_FAVOURITE) { {
in.putExtra(Constants.CONTACT_ID,favouriteContactList.get(position).getId() );
startActivity(in);
}}
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
#Override
public void onDestroyView() {
super.onDestroyView();
realm.close();
}
public void setListAdapterTabs(){
Log.i(Constants.TAG, "ContactListFragment.setListAdapterTabs: index " + mIndex);
if(mIndex == Constants.CONTACTS_FAVOURITE) {
favouriteContactList = mContactController.getAllFavouriteContacts();
if (favouriteContactList!=null) {
setListAdapter(new ContactFavouriteListViewArrayAdapter(getActivity().getApplicationContext(),
favouriteContactList));
}
}else if(mIndex == Constants.CONTACTS_RECENT){
if (emptyText!=null)
emptyText.setText("");
recentContactList = mContactController.getAllRecentContacts();
if (recentContactList!=null) {
setListAdapter(new RecentListViewArrayAdapter(getActivity().getApplicationContext(), recentContactList));
}
}else if(mIndex == Constants.CONTACTS_ALL){
if (emptyText!=null)
emptyText.setText("");
contactList = mContactController.getAllContacts();
adapter = new ContactListViewArrayAdapter(getActivity().getApplicationContext(), contactList);
if (contactList!=null) {
if (listView!=null)
state = listView.onSaveInstanceState();
if (adapter != null){
setListAdapter(adapter);
if (state!=null)
listView.onRestoreInstanceState(state);
} else {
adapter = new ContactListViewArrayAdapter(getActivity().getApplicationContext(), contactList);
setListAdapter(adapter);
if (state!=null)
listView.onRestoreInstanceState(state);
}
}
}
}
}