Unable to launch app - java.lang.NullPointerException [duplicate] - java

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I'm having problems launching my app (crashes), while there is no errors in code.
This happend after i converted code of List View activity to List Fragment...
My main activity:
package com.example.eronetmarket;
import com.preporuceno_app.AppAdapter;
import android.R.drawable;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.itemmenu, menu);
return true;
}
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
final ActionBar actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
//actionBar.setDisplayShowHomeEnabled(false);
addTabs(actionBar);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
Log.d("VIVZ","onPageScrolled "+i+" "+v+" "+i2);
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
Log.d("VIVZ","onPageSelected "+i);
}
#Override
public void onPageScrollStateChanged(int i) {
if(i==ViewPager.SCROLL_STATE_IDLE)
Log.d("VIVZ","onPageScrollStateChanged scroll state idle "+i);
if(i==ViewPager.SCROLL_STATE_DRAGGING)
Log.d("VIVZ","onPageScrollStateChanged scroll state dragging "+i);
if(i==ViewPager.SCROLL_STATE_SETTLING)
Log.d("VIVZ","onPageScrollStateChanged scroll state settling "+i);
}
});
}
private void addTabs(ActionBar actionBar)
{
ActionBar.Tab tab1=actionBar.newTab();
tab1.setText("PREPORUČENO");
tab1.setTabListener(this);
ActionBar.Tab tab2=actionBar.newTab();
tab2.setText("NAJPOPULARNIJE");
tab2.setTabListener(this);
ActionBar.Tab tab3=actionBar.newTab();
tab3.setText("KATEGORIJE");
tab3.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
// Log.d("VIVZ","onTabSelected "+tab.getText());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabUnselected "+tab.getText());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabReselected "+tab.getText());
}
}
class MyAdapter extends FragmentStatePagerAdapter
{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment=null;
if(i==0)
{
fragment=new FragmentA();
}
if(i==1)
{
fragment=new Preporuceno();
}
if(i==2)
{
fragment=new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
And my fragment list:
package com.example.eronetmarket;
import java.io.FileNotFoundException;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Preporuceno extends ListFragment {
private AppAdapter mAdapter;
private ListView siteList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("mobAppModel", "OnCreate()");
View rootView = inflater.inflate(R.layout.activity_preporuceno, container, false);
siteList = (ListView) getActivity().findViewById(R.id.listView1);
siteList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getstoreURL();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
if(isNetworkAvailable()){
Log.i("mobAppModel", "starting download Task");
AppDownloadTask download = new AppDownloadTask();
download.execute();
}else{
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
}
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private class AppDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("http://minores.info/joomla30/stacksites.xml", getActivity().openFileOutput("XMLsource.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
Log.i("mobAppModel", "adapter size = "+ mAdapter.getCount());
}
}
}
Here is my LogCat messages:
In line 38 where LogCat shows error, I have this line public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
I don't understand where I went wrong?

Change this
siteList = (ListView) getActivity().findViewById(R.id.listView1);
to
siteList = (ListView) rootView.findViewById(R.id.listView1);
The view belongs to the inflated layout and you need to use the view object to initialize views.
java.lang.RuntimeException: Your content must have a ListView whose
id attribute is 'android.R.id.list'
ListActivity or ListFragment will have listview which occuppies the entire screen. If you want to have other views in the layout then your layout must have listview with id andorid.R.id.list
http://developer.android.com/reference/android/app/ListFragment.html
QUoting docs
ListFragment has a default layout that consists of a single list view.
However, if you desire, you can customize the fragment layout by
returning your own view hierarchy from onCreateView(LayoutInflater,
ViewGroup, Bundle). To do this, your view hierarchy must contain a
ListView object with the id "#android:id/list" (or list if it's in
code)

Related

Android java - making 1 ImageAdapter for 2 or more viewpagers (currently 2 adapters for 2 viewpagers)

I made an ImageAdapter class that contains images and an activity that contains 2 buttons, on click each one opens a new activity with a viewpager. The 2 viewpagers have different images and this is where my inexperience comes in.
I took the easy way and duplicated the ImageAdapter (named it ImageAdapter2) and linked it to the 2nd viewpager. visual representation
It works fine, but what I'm trying to do is clean it up and do it all through 1 adapter and 1 viewpager. I tried to do it through Intent getStringExtra but it didn't recognize Intent method. Here are my classes:
ImageAdapter (ImageAdapter2 is the same, just has different images in sliderImageId):
package hr.cnzd.prepoznajmoenasilje;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
public class ImageAdapter extends PagerAdapter {
Context mContext;
ImageAdapter(Context context){
this.mContext = context;
}
#Override
public boolean isViewFromObject(View view, Object o){
return view == ((ImageView) o);
}
private int[] sliderImageId = new int[]{
R.drawable.djeca01, R.drawable.djeca02, R.drawable.djeca03, R.drawable.djeca04, R.drawable.djeca05, R.drawable.djeca06, R.drawable.djeca07, R.drawable.djeca08
};
#Override
public Object instantiateItem(ViewGroup viewGroup, int position){
ImageView imageView = new ImageView(mContext);
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(sliderImageId[position]);
((ViewPager) viewGroup).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup viewGroup, int position, Object o){
((ViewPager) viewGroup).removeView((ImageView) o);
}
#Override
public int getCount(){
return sliderImageId.length;
}
}
Activity with buttons:
package hr.cnzd.prepoznajmoenasilje;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
public class MA_Savjeti extends AppCompatActivity {
private ImageButton imageButtonDjeca;
private ImageButton imageButtonOdrasli;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ma__savjeti);
imageButtonDjeca = findViewById(R.id.imgBtnDjeca);
imageButtonDjeca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivitySavjetiDjeca();
}
});
imageButtonOdrasli = findViewById(R.id.imgBtnOdrasli);
imageButtonOdrasli.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivitySavjetiOdrasli();
}
});
}
public void openActivitySavjetiDjeca() {
Intent intent = new Intent(this, Savjeti_Djeca.class);
intent.putExtra("savjeti", "djeca");
startActivity(intent);
}
public void openActivitySavjetiOdrasli() {
Intent intent = new Intent(this, Savjeti_Odrasli.class);
intent.putExtra("savjeti", "odrasli");
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
Activity with viewpager (other activity with viewpager has the same code, just calls ImageAdapter2)
package hr.cnzd.prepoznajmoenasilje;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class Savjeti_Djeca extends AppCompatActivity {
ViewPager viewPager;
ImageAdapter imageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.savjeti_djeca);
viewPager = findViewById(R.id.viewpager);
imageAdapter = new ImageAdapter(this);
viewPager.setAdapter(imageAdapter);
}
}
TLDR: I have 2 ImageAdapters and 2 Viewpagers, but I wanna do it through 1 ImageAdapter and 1 Viewpager (2 buttons on a previous activity decide which set of images is shown on the viewpager)
Solved it using ViewPager2 instead of this way.

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

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;
}

Recyclerview with cards in a fragment shows nothing

I am trying to make an activity which has a fragment inside with a recyclerView and cards on it. Right now, it only shows the activity, the fragment is empty, and I don't know what is going on here.
This is the code of the activity, the fragment, and the adapter
Activity:
package com.laorden.goodreasons.habits;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.NavigationView;
import android.support.test.espresso.IdlingResource;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.Injection;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.statistics.StatisticsActivity;
import com.laorden.goodreasons.util.ActivityUtils;
import com.laorden.goodreasons.util.EspressoIdlingResource;
public class HabitsActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private HabitsPresenter mHabitsPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.habits_act);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// Set up the toolbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
// Set up the navigation drawer.
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
HabitsFragment habitsFragment =
(HabitsFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
if (habitsFragment == null) {
// Create the fragment
habitsFragment = HabitsFragment.newInstance();
ActivityUtils.addFragmentToActivity(
getSupportFragmentManager(), habitsFragment, R.id.contentFrame);
}
// Create the presenter
mHabitsPresenter = new HabitsPresenter(habitsFragment,
Injection.provideUseCaseHandler());
}
/* // Load previously saved state, if available.
if (savedInstanceState != null) {
TasksFilterType currentFiltering =
(TasksFilterType) savedInstanceState.getSerializable(CURRENT_FILTERING_KEY);
mTasksPresenter.setFiltering(currentFiltering);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(CURRENT_FILTERING_KEY, mTasksPresenter.getFiltering());
super.onSaveInstanceState(outState);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Open the navigation drawer when the home icon is selected from the toolbar.
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.list_navigation_menu_item:
// Do nothing, we're already on that screen
break;
case R.id.statistics_navigation_menu_item:
Intent intent =
new Intent(HabitsActivity.this, StatisticsActivity.class);
startActivity(intent);
break;
default:
break;
}
// Close the navigation drawer when an item is selected.
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#VisibleForTesting
public IdlingResource getCountingIdlingResource() {
return EspressoIdlingResource.getIdlingResource();
}
}
Fragment:
package com.laorden.goodreasons.habits;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.ArrayList;
import java.util.List;
public class HabitsFragment extends android.support.v4.app.Fragment implements HabitsContract.View {
private HabitsContract.Presenter mPresenter;
private HabitsAdapter mListAdapter;
private RecyclerView recyclerView;
public HabitsFragment() {
// Requires empty public constructor
}
public static HabitsFragment newInstance() {
return new HabitsFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Habit> habitsList = new ArrayList<>();
habitsList.add(new Habit(R.drawable.smoke,"Quit smoking",300));
habitsList.add(new Habit(R.drawable.books,"Read more",600));
habitsList.add(new Habit(R.drawable.sleep,"Get more sleep",600));
mListAdapter = new HabitsAdapter(getContext(),habitsList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setAdapter(mListAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return root;
}
#Override
public void onResume() {
super.onResume();
mPresenter.start();
}
#Override
public void setLoadingIndicator(boolean active) {
}
#Override
public void showHabits(List<Habit> habits) {
}
#Override
public void showHabitDetailsUi(String habitId) {
}
#Override
public boolean isActive() {
return false;
}
#Override
public void setPresenter(HabitsContract.Presenter presenter) {
mPresenter = presenter;
}
}
Adapter:
package com.laorden.goodreasons.habits;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.List;
public class HabitsAdapter extends RecyclerView.Adapter<HabitsAdapter.myViewHolder> {
Context mContext;
List<Habit> mData;
public HabitsAdapter(Context mContext, List<Habit> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.card_item,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
holder.background_image.setImageResource(mData.get(position).getBackground());
holder.tv_title.setText(mData.get(position).getHabitName());
holder.tv_nbSubscribers.setText(mData.get(position).getNumSubscribers() + " Joined");
}
#Override
public int getItemCount() {
return 0;
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView background_image;
TextView tv_title,tv_nbSubscribers;
public myViewHolder(View itemView) {
super(itemView);
background_image = itemView.findViewById(R.id.card_background);
tv_title = itemView.findViewById(R.id.card_title);
tv_nbSubscribers = itemView.findViewById(R.id.card_numberUsers);
}
}
}
If you need any other code snippets, please tell me (maybe the xml
layouts)
Thanks
That is because you are returning 0 in the getItemCount method
Change this :
#Override
public int getItemCount() {
return 0;
}
To this:
#Override
public int getItemCount() {
return (mData != null ? mData.size():0);
}
you should set layout manager first
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mListAdapter);
return root;
}
also you need to change the getItemCount into
#Override
public int getItemCount() {
if(mData!=null){return mData.size();}else return 0;
}
The reason you are getting empty list because your method getItemCount returns 0.
Here is the modified method.
#Override
public int getItemCount() {
return mData!=null ? mData.size():0;
}

When I move from fragment b to fragment A after adding my new listitem, my new listitem is not showing in recyclerview

I am making note taking app.i have two fragments in my app first fragment A (ListFragment) contains the recycler adapter .
while when I press adding floating button first fragment A (ListFragment) is replaced with next fragment B(AddingFragment) in which I type new data and then again press adding floating button on fragment B(AddingFragment) to add that new data in data set and then press backfloating button on my fragment B to move back to Fragment A(with recycler adapter) .
This new data item is added to data list every time but never becomes visible in recycler adapter in Fragment A.
package com.example.anonymous.note_taking_app;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class AddingFragment extends Fragment {
public AddingFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_adding, container, false);
return view;
}
#Override
public void onResume()
{
super.onResume();
FloatingActionButton floating = (FloatingActionButton) getActivity().findViewById(R.id.addingfloatingbutton);
floating.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("floating_button", "floating button 2 clicked");
EditText title = (EditText) getActivity().findViewById(R.id.firsttextview);
EditText detial = (EditText) getActivity().findViewById(R.id.secondtextview);
DatabaseHelper db = new DatabaseHelper(getActivity().getApplication());
boolean insert = db.insert(title.getText()+"",detial.getText()+"");
if(insert==true)
{
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter();
ListFragment.it.add(new ListItem(title.getText()+"",detial.getText()+""));
l.notifyItemInserted(ListFragment.it.size()-1);//DataSetChanged();
l.notifyDataSetChanged();
for(int i=0;i<ListFragment.it.size();i++)
{
Log.i("List item"+i+"", ListFragment.it.get(i).getNoteTitle());
}
Log.i("insertion", "is added");
}
else
{
Log.i("insertion", "is not added");
}
}
});
FloatingActionButton floatings = (FloatingActionButton) getActivity().findViewById(R.id.addcancelfloatingbutton);
floatings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStackImmediate();
}
});
}
}
//
package com.example.anonymous.note_taking_app;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
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.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Fragment;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.holderclas> implements EditDilogue.EditDilougeinterface
{
static ArrayList<ListItem> i;
Context context;
View view;
ImageButton share;
ImageButton edit;
static int lastposition;
android.app.FragmentManager fm;
public ListAdapter(ArrayList<ListItem> i,android.app.FragmentManager fm)
{
this.i=i;
this.fm=fm;
}
public ListAdapter()
{
}
#Override
public ListAdapter.holderclas onCreateViewHolder(ViewGroup parent, int viewType)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
holderclas h = new holderclas(view);
share = (ImageButton) view.findViewById(R.id.share);
edit = (ImageButton) view.findViewById(R.id.edit);
return h;
}
#Override
public void onBindViewHolder(ListAdapter.holderclas holder, final int position)
{
final int y= position;
lastposition = position;
final ListItem it = i.get(position);
holder.title.setText(it.getNoteTitle());
holder.details.setText(it.getNoteDetail());
ImageButton b =(ImageButton) view.findViewById(R.id.delete);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("size", i.size()+"");
i.remove(y);
notifyDataSetChanged();
}
});
share.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("share", "share");
}
});
edit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("edit", i.size()+"edit");
EditDilogue ed = new EditDilogue();
Bundle args = new Bundle();
args.putString("title", it.getNoteTitle());
args.putString("detail", it.getNoteDetail());
ed.setArguments(args);
ed.setTargetFragment(new ListFragment(),1);
ed.show(fm,"fragment");
}
});
}
#Override
public int getItemCount()
{
return i.size();
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = i.get(lastposition).getNoteTitle();
String olddetail = i.get(lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
public class holderclas extends RecyclerView.ViewHolder
{
TextView title;
TextView details;
public holderclas(View itemView)
{
super(itemView);
title=(TextView) itemView.findViewById(R.id.title);
details=(TextView) itemView.findViewById(R.id.detail);
}
}
}
//
package com.example.anonymous.note_taking_app;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
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.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListFragment extends Fragment implements EditDilogue.EditDilougeinterface
{
RecyclerView recyClerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
public static ArrayList<ListItem> it;
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
it = new ArrayList<>();
View view = inflater.inflate(R.layout.fragment_list, parent, false);
FloatingActionButton floating = (FloatingActionButton) view.findViewById(R.id.listfloatingbutton);
floating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Fragment frg = new AddingFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.replace(R.id.placeholder,frg);
trans.addToBackStack("addingfragment");
trans.commit();
AddingFragment()).addToBackStack("addingfragment").commit();
}
});
for(int i=0;i<5;i++)
{
ListItem t = new ListItem("Time Bank",
"Bank should contain atleast $2000 rupees then i will leave this matter") ;
it.add(t);
}
recyClerView=(RecyclerView) view.findViewById(R.id.recycle);
FragmentManager fm = getFragmentManager();
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter(it,fm);
recyClerView.setAdapter(l);
layoutManager = new LinearLayoutManager(getActivity());
recyClerView.setLayoutManager(layoutManager);
return view;
}
#Override
public void onResume()
{
super.onResume();
if(adapter!=null)
{
adapter.notifyDataSetChanged();
adapter.notifyItemInserted(ListFragment.it.size()-1);
}
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteTitle();
String olddetail = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
}

Why won't Fragment Transaction work?

I'm writing a simple program in which a two fragments and one activity is used. Both Fragments are displayed (one at a time) within the activity's Frame Layout. The first fragment is a listview that lists items from which the user can select, then the main activity should swap the first fragment with a detail fragment according to the item position determined by a listener within the first fragment. Trouble is, my program won't actually commence the swap. Here's the code for the activity:
package com.example.user.monkeys;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class ListActivity extends FragmentActivity implements
monkeyListFragment.OnMonkeySelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("Activity", "onCreate Pre-Fragment 1");
super.onCreate(savedInstanceState);
setContentView(R.layout.monkey_list_frame);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
monkeyListFragment monkeyList = new monkeyListFragment();
monkeyList.setArguments(getIntent().getExtras());
// Add the fragment to the container
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, monkeyList);
Log.i("Activity", "made it end onCreate");
}
}
#Override
public void onMonkeyItemSelected(int position) {
Log.i("From Activity", "onMonkeyItemSelected");
monkeyDetailsFragment newDetailFrag = new monkeyDetailsFragment();
Bundle args = new Bundle();
args.putInt("itemPosition", position);
newDetailFrag.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newDetailFrag);
transaction.addToBackStack(null);
transaction.commit();
}
}
And the code for the listview fragment:
package com.example.user.monkeys;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class monkeyListFragment extends Fragment{
OnMonkeySelectedListener monkeyCallBack;
private ListView monkeyLV;
private String[] monkeyStrings;
public interface OnMonkeySelectedListener {
public void onMonkeyItemSelected(int position);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("Fragment 1", "Made it to onCreateView");
View view = inflater.inflate(R.layout.list_fragment, container, false);
monkeyLV = (ListView) view.findViewById(R.id.monkeyListView);
monkeyStrings = getResources().getStringArray(R.array.monkey_data_list);
ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, monkeyStrings);
monkeyLV.setAdapter(objAdapter);
AdapterView.OnItemClickListener monkeyListen = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("ListFragment-ClckLstnr", "Made it");
monkeyCallBack.onMonkeyItemSelected(position);
}
};
Log.i("Fragment 1", "Made it past OnItemClick Listener");
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
monkeyCallBack = (OnMonkeySelectedListener) activity;
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
}
and finally the code for the detail fragment (this isn't fully fleshed out but it should still swap I believe).
package com.example.user.monkeys;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class monkeyDetailsFragment extends Fragment {
ImageView monkeyPicture;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
Log.i("From Detail Fragment", "Got here");
View view = inflater.inflate(R.layout.monkey_detail_fragment, container,
false);
return view;
}
}
I found your missing line of code for the listview fragment:
monkeyLV.setOnItemClickListener(monkeyListen)

Categories