Android: E/RecyclerView: No adapter attached; skipping layout - java

so i have a tabbed activity that contains 3 tabs as fragments, each tab has a RecyclerView.
I checked all the answered questions on here and on other sites, everything seems fine, yet it doesn't work!
here's my Code:
MainActivity.java:
package esprit.tn.mywaterproject;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.time.Duration;
import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("test","test log");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Chat avec un
résponsable", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e("frag number", "frag test number
:"+getArguments().getInt(ARG_SECTION_NUMBER));
if (getArguments().getInt(ARG_SECTION_NUMBER)==1){
Log.e("frag test1", "frag test TEST1");
new Eaux_Fragment();
return inflater.inflate(R.layout.fragment_eaux,
container,false);
}
if (getArguments().getInt(ARG_SECTION_NUMBER)==2){
Log.e("frag test2", "frag test TEST2");
return inflater.inflate(R.layout.fragment_piscine,
container,false);
}
if (getArguments().getInt(ARG_SECTION_NUMBER)==3){
Log.e("frag test3", "frag test TEST3");
return inflater.inflate(R.layout.fragment_electricite, container,false);
}
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
Here's my Adapter
ProduitAdapter.java :
package esprit.tn.mywaterproject;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import esprit.tn.mywaterproject.Entities.Produit_Eau;
public class ProduitAdapter extends
RecyclerView.Adapter<ProduitAdapter.ViewHolder> {
private Context context;
private List<Produit_Eau> list;
public ProduitAdapter( Context context, ArrayList<Produit_Eau> list) {
this.context=context;
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("LOG IN ADAPTER","TEST ADAPTER");
View v =
LayoutInflater.from(context).inflate(R.layout.single_produit_eau, parent,
false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Produit_Eau prod_eau = list.get(position);
holder.text_single_prod_nom.setText(prod_eau.getNom());
holder.text_single_prod_description.setText(prod_eau.getDescription());
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView text_single_prod_nom, text_single_prod_description;
public ViewHolder(View itemView) {
super(itemView);
text_single_prod_nom = itemView.findViewById(R.id.single_prod_nom);
text_single_prod_description =
itemView.findViewById(R.id.single_prod_description);
}
}
}
And Here's one of the fragments
Eau_Fragment.java
package esprit.tn.mywaterproject.Fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import esprit.tn.mywaterproject.Entities.Produit_Eau;
import esprit.tn.mywaterproject.ProduitAdapter;
import esprit.tn.mywaterproject.R;
/**
* A simple {#link Fragment} subclass.
*/
public class Eaux_Fragment extends Fragment {
private RecyclerView recyclerList;
private LinearLayoutManager linearLayoutManager;
private ArrayList<Produit_Eau> produit_eauList;
private ProduitAdapter adapter;
private String UrlShowProducts = "http://192.168.1.7:3003/prodeau";
private LinearLayout linearLayout;
public Eaux_Fragment() {
Log.e("Test Eau Fragment","EAU FRAG TEST");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragmentd
View view = inflater.inflate(R.layout.fragment_eaux, container, false);
linearLayoutManager = new
LinearLayoutManager(getActivity().getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
DividerItemDecoration(recyclerList.getContext(),
linearLayoutManager.getOrientation());
adapter = new ProduitAdapter(getActivity().getApplicationContext(),
produit_eauList);
recyclerList = getActivity().findViewById(R.id.eau_prod_list);
recyclerList.setHasFixedSize(true);
recyclerList.setLayoutManager(linearLayoutManager);
produit_eauList = new ArrayList<>();
getData();
recyclerList.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
private void getData() {
JsonArrayRequest jsonArrayRequest = new
JsonArrayRequest(UrlShowProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Produit_Eau produit_eau = new Produit_Eau();
produit_eau.setNom(jsonObject.getString("name"));
produit_eau.setDescription(jsonObject.getString("description"));
produit_eauList.add(produit_eau);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue =
Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(jsonArrayRequest);
}
}
Edit:
The problem i'm facing here is that Eau_Fragment is not showing in the application. i've deleted every other fragment and kept only this one to test it, the fragment is displayed empty, and the only error i got is the one mentionned above.

It's only a warning but if you're concerned about it, then set the adapter before the layout manager:
recyclerList = getActivity().findViewById(R.id.eau_prod_list);
recyclerList.setAdapter(adapter);
recyclerList.setHasFixedSize(true);
recyclerList.setLayoutManager(linearLayoutManager);
Because it triggers layout update immediately when you set layout manager, which looks for the adapter eventually.

I am not sure what is the problem you are facing, but one thing I noticed, is that you are not using Eaux_Fragment in your SectionsPagerAdapter so you need change :
return PlaceholderFragment.newInstance(position + 1);
to
return Eaux_Fragment(position + 1);
and do not forget to add the newInstance method to Eaux_Fragment
public static Eaux_Fragment newInstance(int position) {
Eaux_Fragment fragment = new Eaux_Fragment();
Bundle args = new Bundle();
args.putString(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}

Related

How to setOnclickListener FAB in a fragment that will add a card in a RecyclerView

Im trying to add a FAB that will add a card to the recycler view if clicked
FAB is located in the fragment where it contains the recyclerview
Here is my Adapter
package com.example.tmcpm;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
Context mContext ;
List<MediCard> mData;
public RecyclerViewAdapter(Context mContext, List<MediCard> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v ;
v = LayoutInflater.from(mContext).inflate(R.layout.fragment_medicard_recycler,parent,false);
MyViewHolder vHolder = new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
int currentPosition = position;
final MediCard infoData = mData.get(position);
holder.tv_num.setText(mData.get(position).getMediCardNumber());
holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"Deleted Medication" , Toast.LENGTH_SHORT).show();
removeItem(infoData);
}
private void removeItem(MediCard infoData) {
int currPosition = mData.indexOf(infoData);
mData.remove(currPosition);
notifyItemRemoved(currPosition);
notifyItemRangeChanged(currPosition,mData.size());
notifyDataSetChanged();
}
});
/* holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"ADDING", Toast.LENGTH_SHORT).show();
}
});*/
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tv_num;
private Button buttonDelete;
public FloatingActionButton buttonAdd;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_num = (TextView) itemView.findViewById(R.id.word);
buttonDelete = (Button) itemView.findViewById(R.id.buttonDelete);
buttonAdd = (FloatingActionButton) itemView.findViewById(R.id.floatButtonAdd);
}
}
}
THIS is my Tabbed Activity Java
package com.example.tmcpm;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
public class Prescribe extends AppCompatActivity {
// private final LinkedList<String> mWordList = new LinkedList<>();
private RecyclerView myrecyclerview;
private List<MediCard> lstnum;
/**
* The {#link androidx.viewpager.widget.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* androidx.fragment.app.FragmentStatePagerAdapter.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prescribe);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
/* for (int i = 1; i < 6; i++) {
mWordList.addLast("Medicine # " + i);
}*/
;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_prescribe, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView myrecyclerview;
List<MediCard> mData = new ArrayList<>();
mData.add(new MediCard("Medication 1"));
mData.add(new MediCard("Medication 2"));
mData.add(new MediCard("Medication 3"));
mData.add(new MediCard("Medication 4 "));
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
//do something
rootView = inflater.inflate(R.layout.fragment_prescribe, container, false);
break;
case 2:
//do something
rootView = inflater.inflate(R.layout.medicard_fragment,container,false);
myrecyclerview = rootView.findViewById(R.id.medicard_recyclerview);
RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(),mData);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerAdapter);
new FragmentMedicard();
break;
case 3:
rootView = inflater.inflate(R.layout.medicard_fragment, container, false);
break;
}
//TextView textView = (TextView) rootView.findViewById(R.id.section_label);
// textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
and the Fragment that holds the recyclerView Java
package com.example.tmcpm;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
public class FragmentMedicard extends Fragment implements View.OnClickListener {
View v;
private RecyclerView myrecyclerview;
private List<MediCard> mData;
FloatingActionButton fabAdd;
Context mContext;
public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
View myView = inflater.inflate(R.layout.medicard_fragment, container, false);
fabAdd = (FloatingActionButton) myView.findViewById(R.id.floatButtonAdd);
fabAdd.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View v) {
Toast.makeText(mContext,"ADDING", Toast.LENGTH_SHORT).show();
}
}
I really dont know what to do anymore
I tried putting my code for the fab in the adapter which only cause a nullpointer exception which is i think is right since its in a different fragment
Create an instance variable to hold your recyclerAdapter in your fragment. Then you can have the FAB click listener add a MediaCard to mData.
Then call
recyclerAdapter.notifyDataSetChanged();

Add existing activity to a TabActivity Android

Hi guys I'm adding a tab activity to an existing android app! In particular, I should add HomeActivity to TabActivity, how can I do? I read on the net that you should implement in HomeActivity fragment and then add it to the TabActivity! But if I implement Fragment in HomeActivity I have a series of errors!
Tab Activity
package xx.myapp;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TabActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
Home Activity:
package xx.myapp;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import xx.*;
public class HomeActivity extends AppCompatActivity {
int[] images = {R.drawable.accettato, R.drawable.fatturato, R.drawable.incorso, R.drawable.rifiutato};
ArrayList CantieriRicerca = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Home");
/* Deserializzo l'oggetto */
Intent i = getIntent();
User u = (User) i.getSerializableExtra("User");
Cantiere c = new Cantiere();
CantieriRicerca = c.RicercaCantiere("a", u);
//Listview che visulizza in cantieri con il customadapter
ListView cantieriListView = (ListView) findViewById(R.id.ListViewCantieri);
CustomAdapter cm = new CustomAdapter();
cantieriListView.setAdapter(cm);
try {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
} catch (Exception ex) {
System.out.println("\n Errore HomeActivity.java : " + ex);
}
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return CantieriRicerca.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.row, null);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageview_stato);
TextView textview_nomecantiere = (TextView) convertView.findViewById(R.id.textView_NomeCantiere);
TextView textview_cliente = (TextView) convertView.findViewById(R.id.textView_Cliente);
Cantiere c = (Cantiere) CantieriRicerca.get(position);
String statoCantiere = c.GetStatoCantiere();
if (statoCantiere.equals("Chiuso")==true) {
imageView.setImageResource(images[0]);
} else if (statoCantiere.equals("InCorso")==true) {
imageView.setImageResource(images[2]);
} else if (c.GetStatoFatturazione() > 0) {
imageView.setImageResource(images[1]);
}
else{
imageView.setImageResource(images[3]);
}
textview_cliente.setText(c.c.GetRagioneSociale());
textview_nomecantiere.setText(c.GetNomeCantiere());
return convertView;
}
}
}
You should consider converting you HomeActivity to Fragment and put it inside of your TabActivity. Fragments are extremely powerful as much as their API, so there should be no problems for you.

Unable to retrieve context in Fragment [duplicate]

This question already has answers here:
Why is my context in my Fragment null?
(4 answers)
Closed 5 years ago.
I tried to find the solution with several resources:
Retrieve Context from a fragment
Using context in a fragment
But I still got the following error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
Any help will be appreciated. Thanks!
My current codes:
AnalysisActivity.java:
package com.app.component.fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.material.components.R;
import com.material.components.fragment.FragmentTabsEvents;
import com.material.components.fragment.FragmentTabsPerformance;
import com.material.components.fragment.FragmentTabsRecommendation;
import com.material.components.utils.Tools;
import java.util.ArrayList;
import java.util.List;
public class AnalysisActivity extends AppCompatActivity {
private ViewPager view_pager;
private TabLayout tab_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_analysis);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Tools.setSystemBarColor(this,R.color.black);
view_pager = findViewById(R.id.view_pager);
setupViewPager(view_pager);
tab_layout = findViewById(R.id.tab_layout);
tab_layout.setupWithViewPager(view_pager);
}
private void setupViewPager(ViewPager viewPager) {
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(FragmentTabsPerformance.newInstance(), "PERFORMANCE");
adapter.addFragment(FragmentTabsRecommendation.newInstance(), "RECOMMENDATION");
adapter.addFragment(FragmentTabsEvents.newInstance(), "EVENTS RELATED TO YOU");
viewPager.setAdapter(adapter);
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
FragmentTabsPerformance.java:
package com.app.component.fragment;
import android.content.Context;
import android.graphics.Color;
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.ImageView;
import com.material.components.R;
import com.material.components.utils.Tools;
import java.util.ArrayList;
import java.util.List;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;
public class FragmentTabsPerformance extends Fragment {
private Context context;
public FragmentTabsPerformance() {
this.context = getActivity().getApplicationContext();
List<PointValue> values = new ArrayList<>();
values.add(new PointValue(0, 2));
values.add(new PointValue(1, 4));
values.add(new PointValue(2, 3));
values.add(new PointValue(3, 4));
//In most cased you can call data model methods in builder-pattern-like manner.
Line line = new Line(values).setColor(Color.BLUE).setCubic(true);
List<Line> lines = new ArrayList<>();
lines.add(line);
LineChartData data = new LineChartData();
data.setLines(lines);
LineChartView chart = new LineChartView(this.getContext());
chart.setLineChartData(data);
}
public static FragmentTabsPerformance newInstance() {
FragmentTabsPerformance fragment = new FragmentTabsPerformance();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_tabs_performance, container, false);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_1), R.drawable.image_8);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_2), R.drawable.image_9);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_3), R.drawable.image_15);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_4), R.drawable.image_14);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_5), R.drawable.image_12);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_6), R.drawable.image_2);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_7), R.drawable.image_5);
return root;
}
}
This exception occurred since you called the getActivity() in the construction method when the fragment is not attached to an activity. You may refer to the API guides about the lifecycle methods about fragment with activity. In your case, you may use getContext() instead of getActivity() method to get the context of fragment.
getActivity() only available after Fragment is attached to activity. So, getActivity() in Fragment constructor will return null. Check fragment life cycle for more detail

Android: FragmentManager returns blank fragment layout when new Fragment is inflated - onCreateView() method is not called at all

Hi my fragment does not get inflated inside a frame layout. please help here is my code:
My MainActivity extends AppCompatActivity and not FragmentActivity because i need to use actionbar.
public void showFragmentWomen(String title) {
showFragment(FragmentWomen.newInstance(title), false);
}
private void showFragment(Fragment fragment, boolean allowStateLoss) {
FragmentManager fm = mFragmentManager;
FragmentTransaction ft = fm.beginTransaction().replace(R.id.container, fragment);
ft.addToBackStack(null);
if (allowStateLoss || !BuildConfig.DEBUG) {
ft.commitAllowingStateLoss();
} else {
ft.commit();
}
fm.executePendingTransactions();
}
Fragment code:
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.msahakyan.angesbags.R;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentWomen#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentWomen extends Fragment {
private static final String KEY_MOVIE_TITLE = "key_title";
private Spinner spinner1;
public FragmentWomen() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment.
*
* #return A new instance of fragment FragmentWomen.
*/
public static FragmentWomen newInstance(String movieTitle) {
FragmentWomen fragmentWomen = new FragmentWomen();
return fragmentWomen;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_women, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
spinner1 = (Spinner) view.findViewById(R.id.frag_women_spinner);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
String firstItem = String.valueOf(spinner1.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
// ToDo when first item is selected
} else {
Toast.makeText(parent.getContext(),
"You have selected : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}

ListFragment in a Tabbed Layout not populating from a SQLite DB

I'm trying to populate 3 ListFragments that are in a Tabbed ViewPager Layout. (Using one of the templates in Android Studio.)
I have been able to successfully put items into the SQLite DB, but I'm having a hard time populating the ListView(s). It would be easy if things weren't static, but the static-ness simply adds to the complexity.
package com.example.listapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ListFragment;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import static com.example.listapp.ItemData.Items.ORDERB;
import static com.example.listapp.ItemData.Items.TABLE_NAME;
import static com.example.listapp.ItemData.Items.TYPE;
import static com.example.listapp.ItemData.Items.LIST_TEXT;
public class MainActivity extends AppCompatActivity {
private ItemData ItemsDb;
String listText = null;
public static String[] FROM = { LIST_TEXT };
public static int[] TO = { R.id.list_text };
public static final Uri CONTENT_URI = Uri.parse("content://"
+ "com.example.listapp" + "/" + TABLE_NAME);
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemsDb = new ListData(getApplicationContext());
Intent saveIntent = getIntent();
listText = saveIntent.getStringExtra(ItemCreate.EXTRA_MESSAGE);
if (rlistText != null) {
SQLiteDatabase db = ItemsDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ORDERB, System.currentTimeMillis());
values.put(ITEM_TEXT, listText);
db.insertOrThrow(TABLE_NAME, null, values);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public void createItem(View view) {
Intent intent = new Intent(this, ItemCreate.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "List1";
case 1:
return "List2";
case 2:
return "List3";
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends ListFragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Cursor cursor = getActivity().getContentResolver().query(CONTENT_URI, FROM, null, null, "_ID DESC");
ListView listItems = getListView();
ListAdapter adapter = new SimpleCursorAdapter(getContext(), R.layout.list_item, cursor, FROM, TO, 0);
listItems.setAdapter(adapter);
}
}
}
The adapter does get properly set, but I get the following error when I run the code:
E/ActivityThread: Failed to find provider info for com.example.listapp
What am I doing wrong?

Categories