in https://github.com/Yalantis/Side-Menu.Android
please help me :(
How can when i click on each item in side menu, go to command "intent to other activity" instead of transport between images
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
import io.codetail.animation.SupportAnimator;
import io.codetail.animation.ViewAnimationUtils;
import yalantis.com.sidemenu.interfaces.Resourceble;
import yalantis.com.sidemenu.interfaces.ScreenShotable;
import yalantis.com.sidemenu.model.SlideMenuItem;
import yalantis.com.sidemenu.sample.fragment.ContentFragment;
import yalantis.com.sidemenu.util.ViewAnimator;
public class MainActivity extends ActionBarActivity implements ViewAnimator.ViewAnimatorListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private List<SlideMenuItem> list = new ArrayList<>();
private ContentFragment contentFragment;
private ViewAnimator viewAnimator;
private int res = R.drawable.content_music;
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentFragment = ContentFragment.newInstance(R.drawable.content_music);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, contentFragment)
.commit();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setScrimColor(Color.TRANSPARENT);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
}
});
setActionBar();
createMenuList();
viewAnimator = new ViewAnimator<>(this, list, contentFragment, drawerLayout, this);
}
private void createMenuList() {
SlideMenuItem menuItem0 = new SlideMenuItem(ContentFragment.CLOSE, R.drawable.icn_close);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(ContentFragment.BUILDING, R.drawable.icn_1);
list.add(menuItem);
SlideMenuItem menuItem2 = new SlideMenuItem(ContentFragment.BOOK, R.drawable.icn_2);
list.add(menuItem2);
SlideMenuItem menuItem3 = new SlideMenuItem(ContentFragment.PAINT, R.drawable.icn_3);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(ContentFragment.CASE, R.drawable.icn_4);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(ContentFragment.SHOP, R.drawable.icn_5);
list.add(menuItem5);
SlideMenuItem menuItem6 = new SlideMenuItem(ContentFragment.PARTY, R.drawable.icn_6);
list.add(menuItem6);
SlideMenuItem menuItem7 = new SlideMenuItem(ContentFragment.MOVIE, R.drawable.icn_7);
list.add(menuItem7);
}
private void setActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
toolbar, /* 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);
linearLayout.removeAllViews();
linearLayout.invalidate();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0.6 && linearLayout.getChildCount() == 0)
viewAnimator.showMenuContent();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int topPosition) {
this.res = this.res == R.drawable.content_music ? R.drawable.content_films : R.drawable.content_music;
View view = findViewById(R.id.content_frame);
int finalRadius = Math.max(view.getWidth(), view.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(view, 0, topPosition, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackgroundDrawable(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
ContentFragment contentFragment = ContentFragment.newInstance(this.res);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, contentFragment).commit();
return contentFragment;
}
#Override
public ScreenShotable onSwitch(Resourceble slideMenuItem, ScreenShotable screenShotable, int position) {
switch (slideMenuItem.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
default:
return replaceFragment(screenShotable, position);
}
}
#Override
public void disableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(false);
}
#Override
public void enableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.closeDrawers();
}
#Override
public void addViewToContainer(View view) {
linearLayout.addView(view);
}
}
Very Thanks for All
Hi currently I also using that library. I've attached my working code.
(In this case im using fragment)
Go and find how to use startActivity then you can use Intent & putExtra your resId.
#Override
public ScreenShotable onSwitch(Resourceble resourceble, ScreenShotable screenShotable, int position) {
int primaryColorCanvas = R.color.colorPrimary;
switch (resourceble.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
case ContentFragment.DASHBOARD:
DashboardFragment fragment = DashboardFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
return replaceFragment(fragment, position);
case ContentFragment.FRIDGE:
FridgeFragment fragment2 = FridgeFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment2).commit();
return replaceFragment(fragment2, position);
case ContentFragment.COOKBOOK:
DashboardFragment fragment3 = DashboardFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment3).commit();
return replaceFragment(fragment3, position);
case ContentFragment.SHOPPINGLIST:
case ContentFragment.FEEDBACK:
ContentFragment fragment4 = ContentFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,fragment4).commit();
return replaceFragment(fragment4, position);
default:
ContentFragment fragment0 = ContentFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,fragment0).commit();
return replaceFragment(fragment0, position);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int position) {
int finalRadius = Math.max(contentFrame.getWidth(), contentFrame.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(contentFrame, 0, position, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackground(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
return screenShotable;
}
private void initializedMenu() {
SlideMenuItem menuItem0 = new SlideMenuItem(contentFragment.CLOSE, R.drawable.back_btn);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(contentFragment.DASHBOARD, R.drawable.dashboard_icon_a);
list.add(menuItem);
SlideMenuItem menuIte2 = new SlideMenuItem(contentFragment.FRIDGE, R.drawable.fridge_icon_a);
list.add(menuIte2);
SlideMenuItem menuItem3 = new SlideMenuItem(contentFragment.COOKBOOK, R.drawable.cookbook_icon_a);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(contentFragment.SHOPPINGLIST, R.drawable.right_icon_a);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(contentFragment.FEEDBACK, R.drawable.feedback_icon_a);
list.add(menuItem5);
}
Remember that I've assigned static string variable in ContentFragment.
You can see at the initializedMenu().
Hope that help!
Related
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.
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.
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;
I am making some android apps with viewpager in fragment. It shows tabs correct, but I can't see any content in my code. I trying to find and search in stackoverflow and google but I don't know why this code is not working. The code looks strange and i am very sorry about that. I am a first quesiton on here. Thx to help me :-)
This is MainActivity.java
package com.yeungnam.food;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
/* mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START); */
dataList.add(new DrawerItem(true));
dataList.add(new DrawerItem("Message", R.drawable.ic_action_camera));
dataList.add(new DrawerItem("Likes", R.drawable.ic_action_cloud));
dataList.add(new DrawerItem("Games", R.drawable.ic_action_email));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(1);
}
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 1:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
case 2:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
case 3:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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 false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(dataList.get(position).isFirst == false)
SelectItem(position);
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} */
}
This is FragmentFood.java
package com.yeungnam.food;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.astuetz.PagerSlidingTabStrip;
public class FragmentFood extends Fragment {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private FoodAdapter adapter;
public FragmentFood() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container,
false);
tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
pager = (ViewPager) view.findViewById(R.id.pager);
adapter = new FoodAdapter(getActivity());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
return view;
}
public class FoodAdapter extends PagerAdapter {
private final String[] TITLES = { "breafkast", "lunch", "dinner" };
private LayoutInflater mInflater;
public FoodAdapter(Context c) {
super(); mInflater = LayoutInflater.from(c);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Object instantiateItem(ViewGroup pager, int position) {
// looks a little bit messy here
TextView v = new TextView(getActivity());
v.setBackgroundResource(R.color.background_window);
v.setText("PAGE " + (position + 1));
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources()
.getDisplayMetrics());
v.setPadding(padding, padding, padding, padding);
v.setGravity(Gravity.CENTER);
pager.addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
}
I also encountered a similar problem,but i use FragmentAdapter. you can refer to the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_first_main, container, false);
textViewMesuemInfo = (TextView) view.findViewById(R.id.textViewMesuemInfo);
textViewOpenInfo = (TextView) view.findViewById(R.id.textViewOpenInfo);
fragmentAdapter = new IntroPagerAdapter(**getChildFragmentManager()**);
sliViewPager = (ViewPager) view.findViewById(R.id.viewPagerMain);
sliViewPager.setOnPageChangeListener(pagerChangeListener);
sliViewPager.setAdapter(fragmentAdapter);
sliViewPager.setCurrentItem(0);
return view;
}
private class IntroPagerAdapter extends FragmentPagerAdapter {
public IntroPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
Log.i("position=",position+"");
switch (position) {
case 0:
return new IntroFragment().setLayout(R.layout.fragment_colckbuild);
case 1:
return new IntroFragment().setLayout(R.layout.fragment_playclock);
case 2:
return new IntroFragment().setLayout(R.layout.fragment_measureinfo);
case 3:
return new IntroFragment().setLayout(R.layout.fragment_playclock);
default:
return null;
}
}
I am using navigationdrawer in an activity.If I click any of the item in the navigation drawer
in default with some color it should allow us to paint some thing.But I tried for a long time i was unable to do it.Kindly hep as soon as possible.Below is my code which i am using.
Painting.java
package com.example.painturselfnew;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class Painting extends Activity {
private ListView mdrawerlist;
private DrawerLayout mdrawerlayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mdrawertitle;
private CharSequence mtitle;
private String[] mfragmenttitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_painting);
mtitle = mdrawertitle = getTitle();
mfragmenttitles = getResources().getStringArray(R.array.widgets);
mdrawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mdrawerlist = (ListView) findViewById(R.id.left_drawer);
mdrawerlist.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mfragmenttitles));
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
mdrawerlist.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mdrawerlayout,
R.drawable.ic_launcher, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mtitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mdrawertitle);
invalidateOptionsMenu();
}
};
mdrawerlayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.painting, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean draweropen = mdrawerlayout.isDrawerOpen(mdrawerlist);
menu.findItem(R.id.action_settings).setVisible(!draweropen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
if (mdrawerlayout.isDrawerOpen(mdrawerlist)) {
mdrawerlayout.closeDrawer(mdrawerlist);
} else {
mdrawerlayout.openDrawer(mdrawerlist);
}
mdrawerlayout.openDrawer(mdrawerlist);
/*
* Toast.makeText(getApplicationContext(), "Options Selected",
* Toast.LENGTH_LONG).show();
*/
return true;
case android.R.id.home:
startActivity(new Intent(Painting.this, MainActivity.class));
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = new Fragment();
Bundle args = new Bundle();
// args.putInt(Fragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
switch (position) {
case 0:
fragment = new Fragment1();
Toast.makeText(getApplicationContext(), "Camera Selected",
Toast.LENGTH_LONG).show();
break;
case 1:
fragment = new Fragment2();
Toast.makeText(getApplicationContext(), "Color Selected",
Toast.LENGTH_LONG).show();
break;
case 2:
/*
* PaintFragment fragment1; fragment1 = new PaintFragment();
*/
PaintFragment fragment1 = new PaintFragment();
Toast.makeText(getApplicationContext(), "Paint Selected",
Toast.LENGTH_LONG).show();
break;
case 3:
fragment = new Fragment4();
Toast.makeText(getApplicationContext(), "Save selected",
Toast.LENGTH_LONG).show();
break;
case 4:
fragment = new Fragment5();
Toast.makeText(getApplicationContext(), "Share Selected",
Toast.LENGTH_LONG).show();
break;
case 5:
fragment = new Fragment6();
Toast.makeText(getApplicationContext(), "ArtBy Selected",
Toast.LENGTH_LONG).show();
break;
case 6:
fragment = new Fragment7();
Toast.makeText(getApplicationContext(), "Refresh Selected",
Toast.LENGTH_LONG).show();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mdrawerlist.setItemChecked(position, true);
setTitle(mfragmenttitles[position]);
mdrawerlayout.closeDrawer(mdrawerlist);
}
#Override
public void setTitle(CharSequence title) {
mtitle = title;
getActionBar().setTitle(mtitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
PainitngFragment.java
package com.example.painturselfnew;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PaintFragment extends Activity {
/*private static int displayWidth = 0;
private static int displayHeight = 0;
*/
/*
* #Override public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* //setContentView(R.layout.activity_fragment3); //setContentView(new
* MyView(this));
*
*
* }
*/
/*public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BrushView view=new BrushView(this);
setContentView(view);
addContentView(view.btnEraseAll, view.params);
/*
* View view = inflater.inflate(R.layout.activity_fragment3, container,
* false);
*/
// getActivity();
/*
* Display display =
* ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE
* )).getDefaultDisplay(); displayWidth = display.getWidth();
* displayHeight = display.getHeight();
*/
//ImageView iv = (ImageView) view.findViewById(R.id.imageView1);
/*
* iv.setOnClickListener(new View.OnClickListener() {
*
* #Override public void onClick(View arg0) { // TO DO Auto-generated
* method stub
*
* BrushView view = new BrushView(getActivity()); //setContentView(new
* BrushView(this)); } });
*/
//return view;
}
#Override
protected void onPause() {
super.onPause();
finish();
}
public class BrushView extends View {
private Paint brush = new Paint();
private Path path = new Path();
public Button btnEraseAll;
public LayoutParams params;
public BrushView(Context paintFragment) {
super(paintFragment);
brush.setAntiAlias(true);
brush.setColor(Color.BLUE);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(15f);
btnEraseAll = new Button(paintFragment);
btnEraseAll.setText("Erase Everything!!");
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
btnEraseAll.setLayoutParams(params);
btnEraseAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// reset the path
path.reset();
// invalidate the view
postInvalidate();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX, pointY);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
// Force a view to draw.
postInvalidate();
return false;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, brush);
}
}
}
Thanks In Advance...