Interstitial banner application - java

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.

Related

it doesn't show the items in the recyclerviewer

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

Glide: How to stop glide from loading images from cache instead load from server each time

I tried everything possible but couldn't try to figure out how to update images to glide whenever my json is updated
MY android app initally loads images from json using glide for firsttime after that it only load images from cache.It doesnot load images that are updated on server till i delete the app and reinstall it
I tried using diskCacheStrategy(DiskCacheStrategy.NONE) and .skipMemoryCache(true) but nothing happened
Glide.with(mContext).load(image.getMedium())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(holder.thumbnail);
This is my code GalleryAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import com.bumptech.glide.signature.StringSignature;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.model.Image;
/**
* Created by Sagunesh on 31/03/16.
*/
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {
private List<Image> images;
private Context mContext;
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
}
}
public GalleryAdapter(Context context, List<Image> images) {
mContext = context;
this.images = images;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gallery_thumbnail, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Image image = images.get(position);
Glide.with(mContext).load(image.getMedium())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(holder.thumbnail);
}
#Override
public int getItemCount() {
return images.size();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private GalleryAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GalleryAdapter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Here is the code of MainActivity.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.adapter.GalleryAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdView;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.android.gms.ads.AdRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.dailysolutions.sn.app.AppController;
import com.dailysolutions.sn.model.Image;
import com.google.android.gms.ads.InterstitialAd;
import java.util.ArrayList;
public class MainActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint = "https://www.freesabkuch.com/api_mehndi/glide.json";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;
private AdView mAdView;
InterstitialAd interstitial;
// Our created menu to use
private Menu mymenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
checkConnectivity();
//advertisement
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
// Prepare the Interstitial Ad
interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
interstitial.loadAd(adRequest);
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
// Call displayInterstitial() function
displayInterstitial();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(this);
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getApplicationContext(), images);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
fetchImages();
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
public void onResume() {
// Start or resume the game.
super.onResume();
displayInterstitial();
}
#Override
public void onStart() {
super.onStart();
displayInterstitial();
}
private void fetchImages() {
pDialog.setMessage("Downloading....");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
images.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Image image = new Image();
image.setName(object.getString("name"));
JSONObject url = object.getJSONObject("url");
image.setSmall(url.getString("small"));
image.setMedium(url.getString("medium"));
image.setLarge(url.getString("large"));
image.setTimestamp(object.getString("timestamp"));
images.add(image);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
#Override
public void onBackPressed() {
exit();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.home:
Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.share:
Toast.makeText(getApplicationContext(),"Share",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
} catch(Exception e) {
//e.toString();
}
case R.id.trash:
Toast.makeText(getApplicationContext(),"Drawer Closed",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.logout:
exit();
}
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
tv_email.setText("Daily Solutions");
drawerLayout = (DrawerLayout)findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
private void checkConnectivity(){
if(ConnectionHelper.isConnectedOrConnecting(getApplicationContext())) {
hideErrorsBar(true);
}else {
//hideErrorsBar(false);
Intent Intent = new Intent(MainActivity.this,NoInternet.class);
startActivity(Intent);
finish();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Add our menu
getMenuInflater().inflate(R.menu.menu_main, menu);
// We should save our menu so we can use it to reset our updater.
mymenu = menu;
//
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
// Do animation start
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
item.setActionView(iv);
new UpdateTask(this).execute();
return true;
}
return super.onOptionsItemSelected(item);
}
public void resetUpdating()
{
// Get our refresh item from the menu
MenuItem m = mymenu.findItem(R.id.action_refresh);
if(m.getActionView()!=null)
{
// Remove the animation.
m.getActionView().clearAnimation();
m.setActionView(null);
}
}
}
You can use Signature for invalidating cache and load image from network. Try
Glide.with(Fragment/context)
.load(imagePath)
.signature(new StringSignature(yourVersion))
.into(ImageView);
Just pass new StringSignature(System.currentTimeMillis()+"") to the signature so that it will load the image from network every time
You could also try setting Signatures
As per the glide documentation on caching
Try this
Glide.with(context)
.load(url) .
signature(new StringSignature(System.currentTimeMillis()))
.into(imageView);
Check here for more details
Well everyone thanks a lot for help :)
I resolved this problem by disabling cache of volley library that was causing the issue but anyway thanks for help :)
//disabling caching for url
AppController.getInstance().getRequestQueue().getCache().remove(url);

Using infinite scroll for load massive content without bug on Android App

Hello I have an application android, and I contact you having a problem. My application is a streaming application with a large number of works, the problem is that to load all works the load is really long, that's why I contact you I would like to use an infinite scroll but despite all Github projects i dont understand having low java base if you could tell me or place and how the necessary code thanks
This is my activity code :
package com.solodroid.androidnewsappdemo.activities;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
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.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.solodroid.androidnewsappdemo.Config;
import com.solodroid.androidnewsappdemo.R;
import com.solodroid.androidnewsappdemo.firebase.Analytics;
import com.solodroid.androidnewsappdemo.fragments.FragmentAbout;
import com.solodroid.androidnewsappdemo.fragments.FragmentFavorite;
import com.solodroid.androidnewsappdemo.fragments.TabFragment;
import com.startapp.android.publish.Ad;
import com.startapp.android.publish.AdEventListener;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
private AdView adView;
private StartAppAd startAppAd = new StartAppAd(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StartAppSDK.init(this, getResources().getString(R.string.startapp_app_id), false);
setContentView(R.layout.activity_main);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
} else {
Log.d("MainActivity", "Working in Normal Mode, RTL Mode is Disabled");
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
firebaseAnalytics();
loadAdMobBannerAd();
loadStartAppWhenAppLaunch();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
//setTitle(menuItem.getTitle());
if (menuItem.getItemId() == R.id.drawer_home) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
}
if (menuItem.getItemId() == R.id.drawer_favorite) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentFavorite()).commit();
}
if (menuItem.getItemId() == R.id.drawer_rate) {
final String appName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
}
}
if (menuItem.getItemId() == R.id.drawer_more) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));
}
if (menuItem.getItemId() == R.id.drawer_about) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentAbout()).commit();
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
loadStartAppOnBackPressed();
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
protected void onPause() {
adViewOnPause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
adViewOnResume();
}
#Override
protected void onDestroy() {
adViewOnDestroy();
super.onDestroy();
}
private void firebaseAnalytics() {
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, getResources().getString(R.string.analytics_item_id_1));
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, getResources().getString(R.string.analytics_item_name_1));
Analytics.getFirebaseAnalytics().logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
Analytics.getFirebaseAnalytics().setAnalyticsCollectionEnabled(true);
Analytics.getFirebaseAnalytics().setMinimumSessionDuration(5000);
Analytics.getFirebaseAnalytics().setSessionTimeoutDuration(1000000);
}
private void loadStartAppWhenAppLaunch() {
if (Config.ENABLE_STARTAPP_ADS) {
startAppAd.loadAd(new AdEventListener() {
#Override
public void onReceiveAd(Ad arg0) {
startAppAd.showAd();
startAppAd.loadAd();
}
#Override
public void onFailedToReceiveAd(Ad arg0) {
}
});
} else {
Log.d("MainActivity", "StartApp When App Launch is Disabled");
}
}
private void loadStartAppOnBackPressed() {
if (Config.ENABLE_STARTAPP_ADS) {
StartAppAd.onBackPressed(this);
} else {
Log.d("MainActivity", "StartApp onBackPressed is Disabled");
}
}
private void loadAdMobBannerAd() {
if (Config.ENABLE_ADMOB_ADS) {
adView = (AdView) findViewById(R.id.adView);
adView.loadAd(new AdRequest.Builder().build());
adView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
adView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
adView.setVisibility(View.VISIBLE);
}
});
Log.d("MainActivity", "AdMob Banner is Enabled");
} else {
Log.d("MainActivity", "AdMob Banner is Disabled");
}
}
private void adViewOnPause() {
if (Config.ENABLE_ADMOB_ADS) {
adView.pause();
} else {
Log.d("MainActivity", "adView onPause is Disabled");
}
}
private void adViewOnResume() {
if (Config.ENABLE_ADMOB_ADS) {
adView.resume();
} else {
Log.d("MainActivity", "adView onResume is Disabled");
}
}
private void adViewOnDestroy() {
if (Config.ENABLE_ADMOB_ADS) {
adView.destroy();
} else {
Log.d("MainActivity", "adView onDestroy is Disabled");
}
}
}
and this is my adapter code :
package com.solodroid.androidnewsappdemo.adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
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.solodroid.androidnewsappdemo.Config;
import com.solodroid.androidnewsappdemo.R;
import com.solodroid.androidnewsappdemo.activities.ActivityNewsDetail;
import com.solodroid.androidnewsappdemo.json.JsonConfig;
import com.solodroid.androidnewsappdemo.models.ItemNewsList;
import com.squareup.picasso.Picasso;
import java.util.List;
public class AdapterNewsRecent extends RecyclerView.Adapter<AdapterNewsRecent.ViewHolder> {
private Context context;
private List<ItemNewsList> arrayItemNewsList;
ItemNewsList itemNewsList;
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView title;
public TextView date;
public LinearLayout linearLayout;
public ViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.news_title);
date = (TextView) view.findViewById(R.id.news_date);
image = (ImageView) view.findViewById(R.id.news_image);
linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
if (Config.ENABLE_DATE_DISPLAY) {
date.setVisibility(View.VISIBLE);
} else {
date.setVisibility(View.GONE);
}
}
}
public AdapterNewsRecent(Context context, List<ItemNewsList> arrayItemNewsList) {
this.context = context;
this.arrayItemNewsList = arrayItemNewsList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.lsv_item_news_list, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
itemNewsList = arrayItemNewsList.get(position);
Typeface font1 = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
Typeface font2 = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf");
holder.title.setTypeface(font1);
holder.date.setTypeface(font2);
holder.title.setText(itemNewsList.getNewsHeading());
holder.date.setText(itemNewsList.getNewsDate());
Picasso.with(context).load(Config.SERVER_URL + "/upload/" +
itemNewsList.getNewsImage()).placeholder(R.drawable.ic_thumbnail).into(holder.image);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemNewsList = arrayItemNewsList.get(position);
int pos = Integer.parseInt(itemNewsList.getCatId());
Intent intent = new Intent(context, ActivityNewsDetail.class);
intent.putExtra("POSITION", pos);
JsonConfig.NEWS_ITEMID = itemNewsList.getCatId();
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return arrayItemNewsList.size();
}
}
I also have an API in php :
<?php
include_once ('includes/variables.php');
$connect->set_charset('utf8');
if(isset($_GET['cat_id']))
{
$query = "SELECT * FROM tbl_news_category c,tbl_news n WHERE c.cid=n.cat_id and c.cid='".$_GET['cat_id']."' ORDER BY n.news_heading ASC";
$resouter = mysqli_query($connect, $query);
}
else if(isset($_GET['nid']))
{
$id = $_GET['nid'];
$query = "SELECT * FROM tbl_news_category c,tbl_news n WHERE c.cid = n.cat_id && n.nid = '$id'";
$resouter = mysqli_query($connect, $query);
}
else if(isset($_GET['latest_news']))
{
$limit = $_GET['latest_news'];
$query = "SELECT * FROM tbl_news_category c,tbl_news n WHERE c.cid=n.cat_id ORDER BY n.news_heading ASC";
$resouter = mysqli_query($connect, $query);
}
else
{
$query = "SELECT * FROM tbl_news_category ORDER BY cid DESC";
$resouter = mysqli_query($connect, $query);
}
$set = array();
$total_records = mysqli_num_rows($resouter);
if($total_records >= 1){
while ($link = mysqli_fetch_array($resouter, MYSQLI_ASSOC)){
$set['NewsApp'][] = $link;
}
}
echo $val= str_replace('\\/', '/', json_encode($set));
?>
My problem is on the "else if(isset($_GET['latest_news']))"
Thanks for help
did you try the EndlessRecyclerOnScrollListener ?
You can found it here : https://gist.github.com/ssinss/e06f12ef66c51252563e
This way you could implement paging and you will not load all your stuff the first time you launch your activity.
You have to define a Step. It will be the number of items you will load per page. You will define it, backend (php API) and frontend (Android App).
Backend
You have to add a new parameter on your php API like this :
isset($_GET['page'])
Then your SQL query will look like this :
$page = $_GET['page'];
$step = 5;
$query = "SELECT * FROM tbl_news_category c,tbl_news n WHERE c.cid=n.cat_id and c.cid='".$_GET['cat_id']."' ORDER BY n.news_heading ASC LIMIT ".(($page - 1) * $step) . "," . $step;
Android App
Get the EndlessRecyclerOnScollListener.
Add a private int current_page to your class.
Add a Scroll Listener on your RecyclerView like this :
mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(
new LinearLayoutManager(getActivity())) {
#Override
public void onLoadMore() {
CallPhpApi(cat_id, current_page);
}
});
In the CallPhpApi, just call your php API with your new parameter page.
Get your objects from your request and add them to you arrayItemNewsList. Then notify your adapter that dataset changed by calling :
mAdapter.notifyDataSetChanged();
Hope it will help.

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

Android Fragment Not Updating Image From Interface

I am trying to update a image from another thread to a fragment via interface. The code does manage to get into the interface but every time it gets to Left_Image.setImageDrawable(Image_Rotated); I keep getting a null pointer exception. If on the on create for the fragment i set a image it works but as soon as it tries to do it for the interface it comes up with the null pointer exception. I used the command isAdded()) to check if the fragment is attached and that keeps coming back as nothing but i cant seem to fix it and have it attached. Here is the code
Fragment:
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.logging.Handler;
public class Augmented_Reality extends PreferenceFragment implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationVectorSensor;
private Sensor mMagneticSensor;
private final float[] mRotationMatrix = new float[16];
private Boolean MagnetButtonPressed = false;
private Boolean Left;
private Boolean Right;
Boolean Admin_Mode;
boolean Lock = false;
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs";
ToggleButton HeadTracker;
TextView Position;
TextView Position_Left;
TextView Position_Right;
ImageView Left_Image;
ImageView Right_Image;
private Image_Packet_Flag Image_Flag;
public final byte Image_Sync_Flag = 0x09;
private Context context;
Activity activity;
public Augmented_Reality() {
Image_Flag = new Image_Packet_Flag();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mRotationVectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mRotationVectorSensor, 10000);
mSensorManager.registerListener(this, mMagneticSensor, 10000);
} catch (Exception ex) {
Toast.makeText(getActivity().getApplicationContext(), "failed sensor", Toast.LENGTH_SHORT).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = getActivity();
View rootView = inflater.inflate(R.layout.augmented_reality_view, container, false);
ActionBar actionBar = ((ActionBarActivity) activity).getSupportActionBar();
actionBar.hide();
HeadTracker = (ToggleButton) rootView.findViewById(R.id.HeadTracker);
Left_Image = (ImageView) rootView.findViewById(R.id.lefty);
Right_Image = (ImageView) rootView.findViewById(R.id.righty);
Bitmap icon = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.ytyty);
BitmapDrawable Image = Rotate_Image(icon);
Left_Image.setImageDrawable(Image);
return rootView;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (HeadTracker.isChecked() == true) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(
mRotationMatrix, event.values);
if (mRotationMatrix[2] >= 0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2) {
Left = true;
Right = false;
} else if (mRotationMatrix[2] <= -0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2) {
Left = false;
Right = true;
} else {
Left = false;
Right = false;
}
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
if (event.values[2] >= 390) {
MagnetButtonPressed = true;
} else {
MagnetButtonPressed = false;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public BitmapDrawable Rotate_Image(Bitmap Image) {
Bitmap bitmapOrg = Image;
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
return bmd;
}
public void UpdateImages(Bitmap Image) {
System.out.println("Image Updated");
final BitmapDrawable Image_Rotated = Rotate_Image(Image);
System.out.println("Is Added Result: " + isAdded());
if(isAdded()) {
System.out.println("Fragment Added");
Left_Image.setImageDrawable(Image_Rotated);
Right_Image.setImageDrawable(Image_Rotated);
}
}
}
MainActivity:
package com.example.jaynesh.mobile_robot_interface.Main_Files;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
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 com.example.jaynesh.mobile_robot_interface.Fragments.Augmented_Reality;
import com.example.jaynesh.mobile_robot_interface.Fragments.Main_Screen;
import com.example.jaynesh.mobile_robot_interface.Fragments.Settings;
import com.example.jaynesh.mobile_robot_interface.Fragments.Mission_Data;
import com.example.jaynesh.mobile_robot_interface.Navigation_Drawer.DrawerItemCustomAdapter;
import com.example.jaynesh.mobile_robot_interface.Navigation_Drawer.ObjectDrawerItem;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Augmented_Reality_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Main_Screen_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Mission_Data_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Settings_Identifier;
import com.example.jaynesh.mobile_robot_interface.R;
import com.example.jaynesh.mobile_robot_interface.Socket.ClientThread;
public class MainActivity extends ActionBarActivity implements ClientThread.Image_Listener{
// declare properties
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
ClientThread clientThread;
private Augmented_Reality Augmented_Reality_Fragment;
private Main_Screen Main_Screen_Fragment;
private Mission_Data Mission_Data_Fragment;
private Settings Settings_Fragment;
private boolean Socket_Connected = false;
private int Current_Page = 0;
Main_Screen_Identifier MS;
Augmented_Reality_Identifier AR;
Mission_Data_Identifier MD;
Settings_Identifier SF;
Thread serverThread = null;
boolean NewPage = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
MS = new Main_Screen_Identifier();
AR = new Augmented_Reality_Identifier();
MD = new Mission_Data_Identifier();
SF = new Settings_Identifier();
NewPage = true;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for proper titles
mTitle = mDrawerTitle = getTitle();
// initialize properties
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// list the drawer items
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[4];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_share, "Main Screen");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_share, "Augment Reality View");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Mission Data");
drawerItem[3] = new ObjectDrawerItem(R.drawable.ic_action_share, "Settings");
// Pass the folderData to our ListView adapter
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
// Set the adapter for the list view
mDrawerList.setAdapter(adapter);
// set the item click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// for app icon control for nav drawer
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
public void OnNewImageListenerBitmap(final Bitmap Image) {
if (Thread.currentThread().getName() == "main") {
Augmented_Reality_Fragment.UpdateImages(Image);
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (Augmented_Reality_Fragment != null) {
Augmented_Reality_Fragment.UpdateImages(Image);
}
}
});
}
#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) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
SharedPreferences.Editor editor = sharedpreferences.edit();
switch (position) {
case 0:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Main_Screen_Fragment == null) {
Main_Screen_Fragment = new Main_Screen();
}
fragment = Main_Screen_Fragment;
Current_Page = 1;
NewPage = true;
break;
case 1:
editor.putBoolean("Image_Listener", true);
editor.commit();
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = new Augmented_Reality();
Current_Page = 2;
NewPage = true;
break;
case 2:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Mission_Data_Fragment == null) {
Mission_Data_Fragment = new Mission_Data();
}
fragment = Mission_Data_Fragment;
Current_Page = 3;
NewPage = true;
break;
case 3:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Settings_Fragment == null) {
Settings_Fragment = new Settings();
}
fragment = Settings_Fragment;
Current_Page = 4;
NewPage = true;
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public void onBackPressed() {
}
}
Thread on which Updated Interface:
if (Listener != null) {
System.out.println("Listener Found");
Image_data = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);
System.out.println("Image Created");
Listener.OnNewImageListenerBitmap(Image_data);
//sendMessage(Image_Flag.to_byte_array(Image_Sync_Flag));
System.out.println("Updated");
}
Ive been stuck on this problem for a while now and im not sure whats going wrong, Any help would be awesome :)
Steve
///////////................\\\\\\
Added Crash log
08-02 01:16:29.997 26346-26346/com.interface E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.jaynesh.mobile_robot_interface.Fragments.Augmented_Reality.UpdateImages(Augmented_Reality.java:215)
at com.example.jaynesh.mobile_robot_interface.Main_Files.MainActivity$2.run(MainActivity.java:180)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
EDIT: In your case 1, be sure to use the fragment that you had set earlier
You have:
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = new Augmented_Reality();
You should have:
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = Augmented_Reality_Fragment;

Categories