it doesn't show the items in the recyclerviewer - java

This is what I got when I make it.
The first thing this is the database and I don't know what exactly happen, but it is not work with me it doesn't show any data in the app.
And this is the code with every thing with it
package com.ta3am.ta3ami.ta3ami;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import com.ta3am.ta3ami.ta3ami.Common.Common;
import com.ta3am.ta3ami.ta3ami.Interface.ItemClickListener;
import com.ta3am.ta3ami.ta3ami.Model.Category;
import com.ta3am.ta3ami.ta3ami.ViewHolder.MenuViewHolder;
public class Home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DatabaseReference ref;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
//Init Firebase
ref = FirebaseDatabase.getInstance().getReference("Category");
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Set Name for user
View headerView = navigationView.getHeaderView(0);
txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
txtFullName.setText(Common.currentUser.getName());
//Load menu
recycler_menu =(RecyclerView)findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
FirebaseRecyclerAdapter<Category,MenuViewHolder> adapter=new FirebaseRecyclerAdapter <Category, MenuViewHolder>(Category.class, R.layout.menu_item, MenuViewHolder.class, ref) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.imageView);
final Category clickItem =model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(Home.this, ""+clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_menu) {
// Handle the camera action
} else if (id == R.id.nav_cart) {
} else if (id == R.id.nav_orders) {
} else if (id == R.id.nav_log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
And the other thing about the other code is ViewHolder and so on
package com.ta3am.ta3ami.ta3ami.ViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ta3am.ta3ami.ta3ami.Interface.ItemClickListener;
import com.ta3am.ta3ami.ta3ami.R;
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtMenuName;
public ImageView imageView;
private ItemClickListener itemClickListener;
public MenuViewHolder(View itemView) {
super(itemView);
txtMenuName =(TextView)itemView.findViewById(R.id.menu_name);
imageView =(ImageView)itemView.findViewById(R.id.menu_image);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view){
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
And as I say there is noting here every thing seem to me good and work harmfully, but I don't know what is the wrong with the data
package com.ta3am.ta3ami.ta3ami.Model;
import android.net.Uri;
import android.widget.ImageView;
public class Category {
private String Name;
private String Image;
public Category() {
}
public Category(String name, String image) {
Name = name;
Image = image;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}

You have not set the layout manager to the adapter. Kindly set a Layout Manager as per your requirement.
Like, adapter.setLayoutManager(new LinearLayoutManager(context)); and it shall work fine then.

You have to update the syntax of the FirebaseRecyclerAdapter
Update loadMenu() method.
private void loadMenu() {
Query query = ref.limitToLast(10); // you can set data limit for how much data you want in list
FirebaseRecyclerOptions dataoptions = new FirebaseRecyclerOptions.Builder<Category>().setQuery(query, Category.class).build();
adapter=new FirebaseRecyclerAdapter <Category, MenuViewHolder>(dataoptions) {
#Override
protected void onBindViewHolder(MenuViewHolder viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.imageView);
final Category clickItem =model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(Home.this, ""+clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_item, parent, false);
return new MenuViewHolder(view);
}
};
recycler_menu.setAdapter(adapter);
}
After that you need to register adapter listener in OnStart() method of the your activity.
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}

Related

RecyclerView search filter getting wrong position after filtering result

Hello friend please help me i am using Recylerview and implemented searchfilter but problem is that after searching the item in recylerview when i click on item it always return 0 position of the item i want actual position of list item please me help here is my code how get actual position recylerview after searching item in recylerview
here is my code
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
private ListView listView;
private ArrayList<String> books;
private ArrayList<String> bookid;
private ListViewAdapter adapter;
private DatabaseHelper mDBHelper = null;
private SQLiteDatabase mDb = null;
BookRecyclerAdopter bookRecyclerAdopter;
//life is awesome
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
RecyclerView bookanme = findViewById(R.id.list);
bookanme.setLayoutManager(new LinearLayoutManager(this));
bookRecyclerAdopter = new BookRecyclerAdopter(this, books);
bookanme.setAdapter(bookRecyclerAdopter);
/* adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
listView.setAdapter(adapter);*/
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booknumber=position;
String bookname=bookid.get(position);
Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();
*//* Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booknumber);
intent.putExtra("bookname",bookname);
startActivity(intent);*//*
}
});
}
*/
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_voice_btn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
searchView.setOnQueryTextListener(this);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite) {
Intent intent = new Intent(this, Favourite.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setData() {
books = new ArrayList<>();
bookid = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
books.add(cursor.getString(1));
bookid.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
String userinput = newtext.toLowerCase();
List<String> newlist = new ArrayList<>();
for (String name : books) {
if (name.toLowerCase().contains(userinput)) {
newlist.add(name);
}
}
bookRecyclerAdopter.updatelist(newlist);
return true;
}
}
package bible.swordof.God;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.context=context;
}
public class Booksholder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView bookname;
public Booksholder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
bookname = (TextView) itemView.findViewById(R.id.text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public Booksholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_listview, viewGroup, false);
return new Booksholder(view);
}
#Override
public void onBindViewHolder(#NonNull Booksholder booksholder, final int i) {
booksholder.bookname.setText(bookname.get(i));
//get first letter of each String item
String firstLetter = String.valueOf(bookname.get(i).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(bookname.get(i));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
booksholder.imageView.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return bookname.size();
}
public void updatelist(List<String>newlist){
bookname=new ArrayList<>();
bookname.addAll(newlist);
notifyDataSetChanged();
}
}
You will need to maintain a separate list of bookname. Let's call it filteredBookname. Initially set it as bookname.
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
private List<String> filteredBookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.filteredBookname = bookname
this.context=context;
}
...
// other pieces of code.
and instead of using bookname to populate RecyclerView items, use filteredBookname
and your update list method will be,
public void updatelist(List<String>newlist){
filteredBookname=new ArrayList<>();
filteredBookname.addAll(newlist);
notifyDataSetChanged();
}
Using the above approach, you can always find the proper position of your item in the original list bookname
The reason is that you are picking the wrong list, pick your data from filtered adapter list/model.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Books booksdata= (Books)adapterName.bookname.get(position);
Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booksdata.booknumber);
intent.putExtra("bookname",booksdata.bookname);
startActivity(intent);
}
});
}
holder.cardView_title.setOnClickListener {
when (holder.tv_number.text) {
"1" -> {
(context as Activity).startActivity(Intent(context, Ma1::class.java))
}
"2" -> {
(context as Activity).startActivity(Intent(context, Ma2::class.java))
}
"3" -> {
(context as Activity).startActivity(Intent(context, Ma3::class.java))
}
}
}

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

RecyclerView error: No adapter attached; skipping layout

When I try to add RecyclerView in the sample application, I get an error E/RecyclerView: No adapter attached; skipping layout.
Because of this, the data which is successfully retrieved from my server does not appear on the screen (empty)
This in my code
MainActivity
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import page.DefaultFragment;
import page.HomeFragment;
import page.ProfileFragment;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private final static String API_KEY = "7e8f60e325cd06e164799af1e317d7a7";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Fragment fragment = null;
fragment = new DefaultFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
String title = getString(R.string.app_name);
if (id == R.id.nav_camera) {
fragment = new HomeFragment();
title = "Home";
} else if (id == R.id.nav_gallery) {
fragment = new ProfileFragment();
title = "Profile";
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void showToast(String output){
Toast.makeText(this.getBaseContext(), output, Toast.LENGTH_SHORT).show();
}
}
My Fragment code
package page;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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.Toast;
import com.transvision.bertho.transvisiondashboardapp.R;
import java.util.List;
import adapter.ChannelAdapter;
import model.Channel;
import model.ChannelResponse;
import rest.ApiClient;
import rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private static final String TAG = HomeFragment.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
getChannelData();
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
public void getChannelData() {
ApiInterface apiService = ApiClient.getChannel().create(ApiInterface.class);
Call<ChannelResponse> call = apiService.getItems();
call.enqueue(new Callback<ChannelResponse>() {
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
int statusCode = response.code();
List<Channel> channel = response.body().getItems();
recyclerView.setAdapter(new ChannelAdapter(channel, R.layout.list_channel, getActivity()));
}
#Override
public void onFailure(Call<ChannelResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
showToast("CONNECTION ERROR");
}
});
}
public void showToast(String output){
Toast.makeText(getActivity(), output, Toast.LENGTH_SHORT).show();
}
}
My adapter
package adapter;
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.LinearLayout;
import android.widget.TextView;
import com.transvision.bertho.transvisiondashboardapp.R;
import java.util.List;
import model.Channel;
public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.ChannelViewHolder> {
private List<Channel> channels;
private int rowLayout;
private Context context;
public static class ChannelViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
TextView name;
TextView code;
TextView description;
TextView number;
TextView definition;
TextView paket;
ImageView logo;
public ChannelViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
name = (TextView) v.findViewById(R.id.title);
definition = (TextView) v.findViewById(R.id.subtitle);
description = (TextView) v.findViewById(R.id.description);
// rating = (TextView) v.findViewById(R.id.rating);
}
}
public ChannelAdapter(List<Channel> channels, int rowLayout, Context context) {
this.channels = channels;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public ChannelAdapter.ChannelViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ChannelViewHolder(view);
}
#Override
public void onBindViewHolder(ChannelViewHolder holder, final int position) {
holder.name.setText(channels.get(position).getName());
holder.definition.setText(channels.get(position).getDefinition());
holder.description.setText(channels.get(position).getDescription());
// holder.rating.setText(channels.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return channels.size();
}
}
Is there anything wrong in my code? Or wrong in code placement?
Thanks
Getting data from internet is an async task and may takes too long, here you don't bind any adapter to the recyclerView until you get a response and this is not the usual right way, If you don't get any response for some reasons (e.g no internet connection), then recyclerView.setAdapter won't run, So I suggest you to create an empty adapter first, Then whenever you get response just update the adapter :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Pass empty list to (predefined) adapter
adapter = new ChannelAdapter (new ArrayList<>(), rowLayout, getActivity());
//Bind it to recyclerView
recyclerView.setAdapter(adapter);
getChannelData();
// Inflate the layout for this fragment
return rootView;
}
Add some method to your adapter in case you want add Channel :
public void addChannel(Channel channel) {
channels.add(channel);
notifyDatasetChanged();//even better notifyItemInserted();
}
Now in your response listener add the response body that you got to the adapter:
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
//Use a loop to add channels you got
adapter.addChannel(responsebodyItems);
}

Interstitial banner application

I have a application but i want use now interstitial banner.
Now it uses only the small banner.
I need to use an interstitial banner when the user opens my application.
But I cannot use with it in my app.
My question is; how to put an interstitial banner when the user opens my application?
I don't know how to push it.
This is my main activity
import android.content.Context;
import android.content.Intent;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.mycompany.krakowiewdk.CityGuideApplication;
import com.mycompany.krakowiewdk.R;
import com.mycompany.krakowiewdk.adapter.DrawerAdapter;
import com.mycompany.krakowiewdk.database.dao.CategoryDAO;
import com.mycompany.krakowiewdk.database.model.CategoryModel;
import com.mycompany.krakowiewdk.fragment.PoiListFragment;
import com.mycompany.krakowiewdk.listener.OnSearchListener;
import com.mycompany.krakowiewdk.utility.ResourcesHelper;
import com.mycompany.krakowiewdk.view.DrawerDividerItemDecoration;
import com.mycompany.krakowiewdk.view.ScrimInsetsFrameLayout;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity implements DrawerAdapter.CategoryViewHolder.OnItemClickListener, OnSearchListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ScrimInsetsFrameLayout mDrawerScrimInsetsFrameLayout;
private DrawerAdapter mDrawerAdapter;
private static final String ADMOB_INTERSTITIAL_UNIT_ID = "ca-app-pub-9431671174707107/7681038866";
private InterstitialAd mInterstitialAd;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private List<CategoryModel> mCategoryList;
public static Intent newIntent(Context context) {
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupActionBar();
setupRecyclerView();
setupDrawer(savedInstanceState);
// init analytics tracker
((CityGuideApplication) getApplication()).getTracker();
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// open or close the drawer if home button is pressed
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// action bar menu behaviour
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfiguration) {
super.onConfigurationChanged(newConfiguration);
mDrawerToggle.onConfigurationChanged(newConfiguration);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public void onItemClick(View view, int position, long id, int viewType) {
// position
int categoryPosition = mDrawerAdapter.getCategoryPosition(position);
selectDrawerItem(categoryPosition);
}
#Override
public void onSearch(String query) {
Fragment fragment = PoiListFragment.newInstance(query);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment).commitAllowingStateLoss();
mDrawerAdapter.setSelected(mDrawerAdapter.getRecyclerPositionByCategory(0));
setTitle(getString(R.string.title_search) + ": " + query);
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setDisplayUseLogoEnabled(false);
bar.setDisplayShowTitleEnabled(true);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
private void setupRecyclerView() {
// reference
RecyclerView recyclerView = getRecyclerView();
// set layout manager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// load categories from database
loadCategoryList();
// set adapter
if (recyclerView.getAdapter() == null) {
// create adapter
mDrawerAdapter = new DrawerAdapter(mCategoryList, this);
} else {
// refill adapter
mDrawerAdapter.refill(mCategoryList, this);
}
recyclerView.setAdapter(mDrawerAdapter);
// add decoration
List<Integer> dividerPositions = new ArrayList<>();
dividerPositions.add(3);
RecyclerView.ItemDecoration itemDecoration = new DrawerDividerItemDecoration(
this,
null,
dividerPositions,
getResources().getDimensionPixelSize(R.dimen.global_spacing_xxs));
recyclerView.addItemDecoration(itemDecoration);
}
private void setupDrawer(Bundle savedInstanceState) {
mTitle = getTitle();
mDrawerTitle = getTitle();
// reference
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_main_layout);
mDrawerScrimInsetsFrameLayout = (ScrimInsetsFrameLayout) findViewById(R.id.activity_main_drawer);
// set drawer
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerLayout.setStatusBarBackgroundColor(ResourcesHelper.getValueOfAttribute(this, R.attr.colorPrimaryDark));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// show initial fragment
if (savedInstanceState == null) {
selectDrawerItem(0);
}
}
private void selectDrawerItem(int position) {
Fragment fragment = PoiListFragment.newInstance(mCategoryList.get(position).getId());
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment).commitAllowingStateLoss();
mDrawerAdapter.setSelected(mDrawerAdapter.getRecyclerPositionByCategory(position));
setTitle(mCategoryList.get(position).getName());
mDrawerLayout.closeDrawer(mDrawerScrimInsetsFrameLayout);
}
private void loadCategoryList() {
try {
mCategoryList = CategoryDAO.readAll(-1l, -1l);
} catch (SQLException e) {
e.printStackTrace();
}
CategoryModel all = new CategoryModel();
all.setId(PoiListFragment.CATEGORY_ID_ALL);
all.setName(getResources().getString(R.string.drawer_category_all));
all.setImage("drawable://" + R.drawable.ic_category_all);
CategoryModel favorites = new CategoryModel();
favorites.setId(PoiListFragment.CATEGORY_ID_FAVORITES);
favorites.setName(getResources().getString(R.string.drawer_category_favorites));
favorites.setImage("drawable://" + R.drawable.ic_category_favorites);
mCategoryList.add(0, all);
mCategoryList.add(1, favorites);
}
private RecyclerView getRecyclerView() {
return (RecyclerView) findViewById(R.id.activity_main_drawer_recycler);
}
}
Issue is resolved, i put code in mainactivity and show fine.

EditText field gets an incorrect output

So, I have this testing app where I am trying to have two fragments communicate via MainActivity. After some research, I have managed to pass data from MainFragment to FragmentTwo. However, whenever I pass in string value from the MainFragment, I get a message saying
"android.support.v7.widget.AppCompatEditText{cce883f VFED .....
app:id/editText}"
I couldn't find what the problem was for this case. Please help.
BTW I know how to use intents and that they are much more flexible(sometimes) than fragments are but this is just so that I know how far I can go with Fragments.
Here's my MainActivity
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MainFragment.OnHeadlineSelectedListener {
private String dataReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void sendInformations(String message) {
FragmentTwo fragmentTwo = new FragmentTwo();
Bundle args = new Bundle();
args.putString(fragmentTwo.DATA_RECEIVE, message);
fragmentTwo.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.container, fragmentTwo)
.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fragmentManager = getFragmentManager();
int id = item.getItemId();
if (id == R.id.frag_one) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentOne()).commit();
} else if (id == R.id.frag_two) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentTwo()).commit();
} else if (id == R.id.frag_three) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentThree()).commit();
} else if (id == R.id.frag_four) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentFour()).commit();
} else if (id == R.id.main_frag) {
fragmentManager.beginTransaction().replace(R.id.container, new MainFragment()).commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
MainFragment class
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MainFragment extends Fragment {
OnHeadlineSelectedListener mCallback;
Button sendData;
public interface OnHeadlineSelectedListener {
public void sendInformations(String message);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
final EditText userInput = (EditText) rootView.findViewById(R.id.editText);
sendData = (Button) rootView.findViewById(R.id.button);
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button) {
mCallback.sendInformations(userInput.toString());
}
}
});
return rootView;
}
}
FragmentTwo class
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTwo extends Fragment {
final static String DATA_RECEIVE = "data_receive";
TextView textView;
String input;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
textView = (TextView) rootView.findViewById(R.id.data_receiver2);
savedInstanceState = getArguments();
if(savedInstanceState != null) {
input = savedInstanceState.getString(DATA_RECEIVE);
}
textView.setText(input);
return rootView;
}
}
Oh, and the message I get is when I run the app, type into the textfield, and press the button, I get the weird message. I would appreciate if anyone can tell me what is causing the weird output..
If this is a bug, which I had noticed in some cases that were relevant, is it because I deprecated the v7.Fragment & v7.FragmentManager?
You are basically passing the EditText as a string in place of the EditText value.
In your MainFragment change mCallback.sendInformations(userInput.toString()); to mCallback.sendInformations(userInput.getText().toString());
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button) {
mCallback.sendInformations(userInput.getText().toString());
}
}
});

Categories