Replace one fragment to another fragment in the swipable TabHost - android-fragments

I have an activity extending fragment activity and swipable tab view. In tab view i have used fragment and Tabs pager adapter to call fragments according to the tab position.
Now i want to replace these fragment using on click items with another fragment and on back press i want the original fragment back...
But when i am clicking on the items..it do nothing...
What should i do..pls help me ...
Thanks in advance
here is my code-
This is my Homeactivity which has tab
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
ressources = getResources();
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// Fragments and ViewPager Initialization
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(HomeScreen.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
// Method to add a TabHost
private static void AddTab(HomeScreen activity, TabHost tabHost,
TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
HomeScreen.AddTab(
this,
this.mTabHost,
this.mTabHost.newTabSpec(Button_tab).setIndicator("",
ressources.getDrawable(R.drawable.menu)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Image_tab).setIndicator("",ressources.getDrawable(R.drawable.jobs)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Text_tab).setIndicator("",ressources.getDrawable(R.drawable.people)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec("line_tab").setIndicator("",ressources.getDrawable(R.drawable.calenders)));
mTabHost.setOnTabChangedListener(this);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(Button_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Button_tab)).popFragment();
} else if (currentTabTag.equals(Image_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Image_tab)).popFragment();
} else if (currentTabTag.equals(Text_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Text_tab)).popFragment();
} else if (currentTabTag.equals(line_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(line_tab)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
My XMl for HomeActivity:
<RelativeLayout 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=".HomeScreen" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/krma" />
<Button
android:layout_width="30dp"
android:layout_marginTop="3dp"
android:layout_height="30dp"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:background="#drawable/listmenu" />
</RelativeLayout>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_weight="0"
android:background="#FF7519"
android:orientation="horizontal" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</LinearLayout>
</TabHost>
</RelativeLayout>
My TabsPagerAdapter is :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Menu();
case 1:
return new Jobs();
case 2:
return new Applicant();
case 3:
return new Admin();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
my Job fragment is :
public class Jobs extends BaseContainerFragment implements OnItemClickListener {
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_job, container,
false);
listView = (ListView) rootView.findViewById(R.id.list);
SharedPreferences sharedpreferences = getActivity()
.getSharedPreferences(LoginScreen.MyPREFERENCES,
Context.MODE_PRIVATE);
String loggedInEmail = sharedpreferences.getString("nameKey", "");
// String loggedInEmail="aditya.pratap#krmaa.com";
RestClient client = new RestClient(
"http://122.180.4.83:8080/krmaa/krmaa/joblist/" + loggedInEmail
+ "/1234");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Gson gson = new Gson();
String convertedStr = response.replace("\\\"", "\"");
String finalJson = convertedStr.substring(1, convertedStr.length() - 2);
JobDTO[] jobDTOList = gson.fromJson(finalJson, JobDTO[].class);
ItemAdapter adapter = new ItemAdapter(getActivity()
.getApplicationContext(), jobDTOList);
// Attach the adapter to a ListView
ListView listView = (ListView) rootView.findViewById(R.id.list);
listView.setAdapter(adapter);
// return list of jobDTO and iterate in view page.
return rootView;
}
public class JobDTOList {
List<JobDTO> jobDTOList;
public List<JobDTO> getJobDTOList() {
return jobDTOList;
}
public void setJobDTOList(List<JobDTO> jobDTOList) {
this.jobDTOList = jobDTOList;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
// How can I switch from 1st tab to 2nd tab here???
// Below code is not worked for me.
fragment2 fr = new fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.job,fr);
transaction.commit();
}
}
My xml for Job fragment is :
<?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:id="#+id/job"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="6"
android:background="#A3A385"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:text="Jobs"
android:textColor="#000000"
android:textSize="10pt" />
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#A3A385"
android:text="Filter"`enter code here`
android:onClick="frag"
android:textSize="10pt" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >`enter code here`
<ListView`enter code here`
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
</LinearLayout>

Related

Why is my floating action button not responding to clicks?

I have two floating action buttons in a fragment that is being created by a ViewPager. My intention is for the FABs to do the same thing that can be done in the ViewPager, so that the user can have a choice in terms of navigation. My problem is that the FABs do not respond to clicks initially, so if I click the left FAB, and then click the right FAB, the ViewPager will flip to the left instead of flipping to the right. What am I doing wrong?
Here is my code:
activity_view_pager:
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment_test:
<?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">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Title"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:text="Description"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="250dp"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/c"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/left_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="450dp"
android:src="#drawable/ic_left_arrow"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/right_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="450dp"
android:layout_marginEnd="50dp"
android:src="#drawable/ic_right_arrow"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ViewPagerActivity:
package com.fl4me.android.exampleapplication;
import static com.fl4me.android.exampleapplication.TestAdapter.EXTRA_ID;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
public class ViewPagerActivity extends AppCompatActivity {
public static int index;
public static ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager);
index = (int) getIntent().getSerializableExtra(EXTRA_ID);
viewPager = (ViewPager) findViewById(R.id.view_pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(position);
}
#Override
public int getCount() {
return 5;
}
});
for(int i = 0; i < Test.testData.length; i++) {
if(i == index) {
viewPager.setCurrentItem(i);
break;
}
}
}
}
TestFragment:
package com.fl4me.android.exampleapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class TestFragment extends Fragment {
private static final String ARG_ID = "Id";
private int Id;
private String a;
private TextView aTV;
private String b;
private TextView bTV;
private int c;
private TextView cTV;
private FloatingActionButton leftBtn;
private FloatingActionButton rightBtn;
public static TestFragment newInstance(int Id) {
Bundle args = new Bundle();
args.putSerializable(ARG_ID, Id);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
Id = getArguments().getInt(ARG_ID);
a = Test.testData[Id].getA();
b = Test.testData[Id].getB();
c = Test.testData[Id].getC();
aTV = (TextView) view.findViewById(R.id.a);
aTV.setText(a);
bTV = (TextView) view.findViewById(R.id.b);
bTV.setText(b);
cTV = (TextView) view.findViewById(R.id.c);
cTV.setText(String.valueOf(c));
leftBtn = view.findViewById(R.id.left_btn);
rightBtn = view.findViewById(R.id.right_btn);
leftBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewPagerActivity.viewPager.setCurrentItem(ViewPagerActivity.index--);
}
});
rightBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewPagerActivity.viewPager.setCurrentItem(ViewPagerActivity.index++);
}
});
return view;
}
}
This is probably happening because you are post-incrementing or post-decrementing the index instead of pre-incrementing or pre-decrementing it. I think that you should know how post and pre incrementation works, but here is something to read.
Basically the index that you are providing for the setCurrentItem is not evaluated on the spot as index + 1 or index - 1, but it gets its new value only after the execution of the line of code in which there is an expression index++ or index--. This is why you got that "lag" in switching pages that you have described.
So, in your listener for the rightBtn the code should probably be like this:
ViewPagerActivity.viewPager.setCurrentItem(++ViewPagerActivity.index);
The listener for the leftBtn will be analogous, but with --.

I want an implit loading spinner to be displayed in a fragment which has some views and the user clicks any one of them

I have a fragment which basically has a recyclerView. So when the user clicks on any item of the view, the background needs to change (the item clicked needs to be highlighted) and a loading spinner needs to appear and then fragment needs to replaced based on the item clicked. How to achieve this? In the below code, I have implemented the highlight facility, but once an item is clicked redirection should happen....
My Internal Layout, (layout_research)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="#dimen/loginCardRadius"
android:elevation="5dp"
android:layout_gravity="center"
android:layout_marginTop="#dimen/loginViewsMargin"
android:layout_marginBottom="#dimen/loginViewsMargin"
android:background="#ffffff">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:padding="#dimen/loginViewsMargin">
<ImageView
android:contentDescription="#string/abc"
android:src="#drawable/logo"
android:layout_gravity="center"
android:layout_height="100dp"
android:layout_width="wrap_content"
android:layout_marginTop="#dimen/loginViewsMargin"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/grid_view"
android:layout_marginTop="20dp"
tools:listitem="#layout/row_item"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
My External Layout,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ScrollView
android:fillViewport="true"
android:layout_height="match_parent"
android:layout_width="match_parent">
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:baselineAligned="true"
android:weightSum="12"
android:background="#drawable/login_shape_bk"
android:orientation="vertical"
android:layout_weight="3">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ic_login_bk" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:layout_marginTop="40dp"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textColor="#ffffff"
android:textSize="22sp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_gravity="center"
android:text="#string/abcd"/>
<include
layout="#layout/internal_research"/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
My Java File,
package com.example.a123;
import android.os.Bundle;
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.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class research extends Fragment {
int selectedPosition=-1;
private String[] names = {"Blogs & Books","Patents","Projects","Publications"};
private int[] image ={R.drawable.books,R.drawable.patents,R.drawable.project,R.drawable.publications};
private ArrayList<adapter_for_research> mProfiles;
private RecyclerView mProfileRecyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
mProfiles = new ArrayList<>();
for(int i =0;i<names.length;i++){
adapter_for_research s = new adapter_for_research();
s.setname(names[i]);
s.setImageId(image[i]);
mProfiles.add(s);
}
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_research, container, false);
mProfileRecyclerView = view.findViewById(R.id.grid_view);
updateUI();
return view;
}
private void updateUI(){
ProfileAdapter mAdapter = new ProfileAdapter(mProfiles);
mProfileRecyclerView.setAdapter(mAdapter);
}
private class ProfileHolder extends RecyclerView.ViewHolder {
private adapter_for_research mProfilecsg;
private ImageView mImageView;
private TextView mnameTextView;
private ProfileHolder(final View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image_view);
mnameTextView = itemView.findViewById(R.id.text_view);
}
private void bindData(adapter_for_research s){
mProfilecsg = s;
mImageView.setImageResource(s.getImageId());
mnameTextView.setText(s.getname());
}
}
private class ProfileAdapter extends RecyclerView.Adapter<ProfileHolder>{
private ArrayList<adapter_for_research> mProfiles;
private ProfileAdapter(ArrayList<adapter_for_research> profile){
mProfiles = profile;
}
#NonNull
public ProfileHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_item,parent,false);
return new ProfileHolder(view);
}
#Override
public void onBindViewHolder(ProfileHolder holder, final int position) {
adapter_for_research s = mProfiles.get(position);
holder.bindData(s);
if(selectedPosition==position)
holder.itemView.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.item_select));
else
holder.itemView.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.item_nselect));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition=position;
notifyItemChanged(selectedPosition);
}
});
}
#Override
public int getItemCount() {
return mProfiles.size();
}
}
}
Adapter Class,
package com.example.a123;
class adapter_for_research {
private String mName;
private int mImageId;
String getname() {
return mName;
}
void setname(String mName) {
this.mName = mName;
}
int getImageId() {
return mImageId;
}
void setImageId(int mImageId) {
this.mImageId = mImageId;
}
}

NullPointerException while populating views inside populateView using FirebaseListAdapter even when everything's right

The populateView method of FirebaseListAdapter is throwing null pointer exceptions while trying to set text of individual text views even though the layout id, view ids are correct. Here's the main activity
public class MainActivity extends AppCompatActivity {
private String dbUrlString = "MY_DB_URL_HERE";
private ListView listView;
private DatabaseReference databaseReference;
private FirebaseListAdapter<Video> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Fetching",Toast.LENGTH_SHORT).show();
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(dbUrlString);
listView = (ListView) findViewById(R.id.list_view);
FirebaseListOptions<Video> options = new FirebaseListOptions.Builder<Video>()
.setQuery(databaseReference,Video.class)
.setLayout(R.layout.custom_item_layout)
.build();
adapter = new FirebaseListAdapter<Video>(options) {
#Override
protected void populateView(#NonNull View v, #NonNull final Video video, int position) {
TextView vname = (TextView) findViewById(R.id.video_name);
TextView vId = (TextView) findViewById(R.id.video_list_id);
vname.setText(video.getName());
vId.setText(video.getVideoId());
}
};
listView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
This is the main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
These are the views in the custom_item_layout file with the respective ids:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:weightSum="10"
android:layout_margin="10dp">
<ImageView
android:id="#+id/play_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_play_video_24dp"
android:layout_marginRight="10dp"
android:layout_centerInParent="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/video_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/play_icon"
android:text="Video title"
android:textSize="20sp"
android:layout_centerInParent="true"
android:textColor="#android:color/black"/>
<TextView
android:id="#+id/video_list_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="."
android:layout_alignParentRight="true"
android:layout_centerInParent="true"/>
</RelativeLayout>
This is the Video class:
package com.example.util;
public class Video {
private String name, videoId;
public Video(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVideoId() {
return videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
public Video(String name, String videoId) {
this.name = name;
this.videoId = videoId;
}
}
And this is the error I'm getting:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.gifapplication.MainActivity$1.populateView(MainActivity.java:44)
at com.example.gifapplication.MainActivity$1.populateView(MainActivity.java:39)
at com.firebase.ui.database.FirebaseListAdapter.getView(FirebaseListAdapter.java:121)
at android.widget.AbsListView.obtainView(AbsListView.java:2365)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1408)
at android.widget.ListView.onMeasure(ListView.java:1315)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1167)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:687)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:754)
at android.view.View.measure(View.java:22759)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2538)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1565)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1833)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1453)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7039)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:924)
at android.view.Choreographer.doCallbacks(Choreographer.java:732)
at android.view.Choreographer.doFrame(Choreographer.java:664)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:910)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6524)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
Any help is appreciated. I've been going crazy trying to fix this. Tried a couple of fixes suggested online but nothing works. I don't even get why the views are null even when they're being instantiated with the right ids.

Recyler view is not displaying anything

I set a recycler view for displaying data from firestore. I almost did everything right.but when I run my app it is not showing any data. Someone please help me. I attached my code here. I added setLinearlayoutmanager and set visibility to visible for recyclerview. I tried to get a data from user and use that data to retrieve content from the database.
display_data.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/loginbg"
tools:context=".displayData">
<EditText
android:id="#+id/deptName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="41dp"
android:layout_marginTop="41dp"
android:ems="10"
android:hint="Enter dept eg:IT"
android:inputType="textPersonName"
android:textColorHint="#android:color/white"
android:textColorLink="#android:color/black"
tools:textColor="#android:color/background_light" />
<Button
android:id="#+id/getData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/deptName"
android:layout_toEndOf="#+id/deptName"
android:background="#drawable/buttonshape"
android:text="Get" />
<android.support.v7.widget.RecyclerView
android:id="#+id/mainlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="120dp"
android:visibility="visible" />
</RelativeLayout>
my java code display.java:
public class displayData extends AppCompatActivity implements View.OnClickListener {
RecyclerView mlist;
EditText deptName;
FirebaseFirestore db3;
public List<Users> usersList;
UsersListAdaptor usersListAdaptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_data);
findViewById(R.id.getData).setOnClickListener(this);
deptName=findViewById(R.id.deptName);
mlist=(RecyclerView) findViewById(R.id.mainlist);
mlist.setHasFixedSize(true);
mlist.setLayoutManager(new LinearLayoutManager(this));
mlist.setAdapter(usersListAdaptor);
db3=FirebaseFirestore.getInstance();
usersList=new ArrayList<>();
usersListAdaptor=new UsersListAdaptor(usersList);
}
public void onClick(View view) {
switch (view.getId()){
case R.id.getData:
getdata();
break;
}
}
private void getdata() {
String deptname=deptName.getText().toString().trim().toLowerCase();
CollectionReference cref=db3.collection("bookingdetails");
Query q2=cref.whereEqualTo("dept",deptname);
q2.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if(e!=null){
Toast.makeText(getApplicationContext(),"Something went wrong",Toast.LENGTH_SHORT).show();
}
for(DocumentChange doc:queryDocumentSnapshots.getDocumentChanges()){
Users users = doc.getDocument().toObject(Users.class);
usersList.add(users);
usersListAdaptor.notifyDataSetChanged();
}
}
});
}
}
users.class
package com.example.sarukesi.seminarbook;
public class Users {
String name;
String dept;
String time;
String date;
public Users() {
}
public Users(String name, String dept, String time, String date) {
this.name = name;
this.dept = dept;
this.time = time;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
UsersListAdapter:
public class UsersListAdaptor extends RecyclerView.Adapter<UsersListAdaptor.ViewHolder> {
List<Users> usersList;
public UsersListAdaptor(List<Users> usersList) {
this.usersList = usersList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.tname.setText(usersList.get(i).getName());
viewHolder.tdept.setText(usersList.get(i).getDept());
viewHolder.ttime.setText(usersList.get(i).getTime());
viewHolder.tdate.setText(usersList.get(i).getDate());
}
#Override
public int getItemCount() {
return usersList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
View mview;
public TextView tname,tdept,ttime,tdate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mview=itemView;
tname=itemView.findViewById(R.id.nametxt);
tdept=itemView.findViewById(R.id.depttxt);
ttime=itemView.findViewById(R.id.timetxt);
tdate=itemView.findViewById(R.id.datetxt);
}
}
}
list_item.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:orientation="vertical"
android:padding="20dp">
<TextView
android:id="#+id/nametxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:padding="15dp"
android:text="Name"
android:textSize="16sp" />
<TextView
android:id="#+id/depttxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="serif-monospace"
android:padding="15dp"
android:text="Dept"
android:textSize="16sp" />
<TextView
android:id="#+id/timetxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:padding="15dp"
android:text="Time"
android:textSize="16sp" />
<TextView
android:id="#+id/datetxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="serif-monospace"
android:padding="15dp"
android:text="Date"
android:textSize="16sp" />
</LinearLayout>
mlist.setAdapter(usersListAdaptor);
db3=FirebaseFirestore.getInstance();
usersList=new ArrayList<>();
usersListAdaptor=new UsersListAdaptor(usersList);
You create a new adapter after assigning the old one. Move the first line to the end of this block

Android: Custom listview button - returns wrong position

attached you can find my problem and I would be very happy if somebody could help me out. I did several days of research and just can find my mistake. I want a custom listview with a clickable button which starts an activity. The activity is always the same but I need to know which item's button was clicked. For beeing able to see which button was clicked, I implemented a Toast but the onlything the Toast returns is 0 and 1.
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner java_spinner;
Spinner java_spinner2;
String mytext;
String mytext2;
TextView choosen_text;
TextView choosen_text2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
java_spinner = (Spinner)findViewById(R.id. spinner);
java_spinner.setOnItemSelectedListener(this);
java_spinner2 = (Spinner)findViewById(R.id. spinner_number_of_rounds);
java_spinner2.setOnItemSelectedListener(this);
ListView lv = (ListView) findViewById(R.id.listView);
generateListContent();
lv.setAdapter(new MyListAdaper(this, R.layout.custom_layout, data));
}
private ArrayList<String> data = new ArrayList<String>();
private void generateListContent() {
for(int i = 0; i < 55; i++) {
data.add("This is row number " + i);
}
}
private class MyListAdaper extends ArrayAdapter<String> {
private int layout;
private List<String> mObjects;
private MyListAdaper(Context context, int resource, List<String> objects) {
super(context, resource, objects);
mObjects = objects;
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewholder = null;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.itemImage);
viewHolder.title = (TextView) convertView.findViewById(R.id.listView);
viewHolder.button = (Button) convertView.findViewById(R.id.playbutton);
viewHolder.button.setTag(position);
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button of the following item was clicked at: " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
mainViewholder = (ViewHolder) convertView.getTag();
mainViewholder.title.setText(getItem(position));
return convertView;
}
}
public class ViewHolder {
ImageView thumbnail;
TextView title;
Button button;
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
View test1 = java_spinner.getSelectedView();
choosen_text = (TextView)test1 ;
mytext = choosen_text.getText().toString();
//Toast.makeText(this, "you selected" + mytext, Toast.LENGTH_SHORT).show();
View test2 = java_spinner2.getSelectedView();
choosen_text2 = (TextView)test2 ;
mytext2 = choosen_text2.getText().toString();
//Toast.makeText(this, "you selected" + mytext2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Keinen Bock mehr...?");
alertDialogBuilder
.setMessage("Ja und tschüss...!")
.setCancelable(false)
.setPositiveButton("Ja",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}}
content_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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main"
tools:context="com.example.dominic.spinner.MainActivity"
android:background="#c0b7b7">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
android:background="#368260">
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_marginTop="12dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:entries="#array/days"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:spinnerMode="dropdown"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/linearLayout"
android:layout_alignEnd="#+id/linearLayout" />
<Spinner
android:entries="#array/pools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner2"
android:spinnerMode="dropdown"
android:layout_above="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_number_of_rounds"
android:entries="#array/Auswahl_der_Rundenanzahl"
android:layout_above="#+id/spinner2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:id="#+id/listView" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="125dp"
android:layout_height="90dp"
android:id="#+id/itemImage"
android:src="#mipmap/party"
android:layout_margin="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/listView"
android:layout_weight="2"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_weight="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PLAY"
android:id="#+id/playbutton" />
</LinearLayout>
</LinearLayout>
K Thx and Best,
Dominic

Resources