java.lang.NullPointerException when resume activity in viewpager - java

I would like to resume activity which i have stored in share preferences in viewpager. I have stored the activity details in onSaveState and retrieve the activity getpreferences in onResume. But somehow, it returns error that the key is in null value in onSaveState. How to save the preferences in viewpager ?
Here is the code
public class FullScreenImageActivity extends AppCompatActivity {
ViewPager viewPager;
ImageView favBtn;
private SharedPreference sharedPreference;
Activity context = this;
private Fragment contentFragment;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_image); //TBS
FragmentManager fragmentManager = getSupportFragmentManager();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavouriteListFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavouriteListFragment.ARG_ITEM_ID) != null) {
contentFragment = fragmentManager
.findFragmentByTag(FavouriteListFragment.ARG_ITEM_ID);
}
}
}
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
String[] arr=i.getStringArrayExtra("array");
String url = i.getStringExtra("url");
sharedPreference = new SharedPreference();
viewPager = (ViewPager) findViewById(R.id.slider);
viewPager.setAdapter(new GalleryViewPagerAdapter(this, arr, position, url));
viewPager.setCurrentItem(position);
}
class GalleryViewPagerAdapter extends PagerAdapter {
private Context context;
LayoutInflater inflater;
private String[] imageArrayList;
private String mUrl;
private int mPosition;
private ProgressDialog mProgress;
public GalleryViewPagerAdapter(Context _context, String[] imageArrayList, int position, String url) {
context = _context;
this.imageArrayList = imageArrayList; //null;
this.mPosition=position;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mUrl=url;
}
#Override
public int getCount() {
return imageArrayList.length;
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
showProgress();
favBtn = (ImageView) findViewById(R.id.btn_favourite);
String favoriteUrl=sharedPreference.getPrefsFavUrl(context);
//Boolean stateBtnNow=sharedPreference.getBtnState(context,mUrl);//why mUrl change to same url with favourite
Boolean stateBtnNow=false;
if(stateBtnNow) {
favBtn.setColorFilter(Color.argb(255, 249, 0, 0));//red
}
else
{
favBtn.setColorFilter(Color.argb(255, 192, 192, 192));
}
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Boolean stateBtn = sharedPreference.getBtnState(context, mUrl);
Boolean stateBtn=false;
if (!stateBtn) {
sharedPreference.save(context, mUrl);
//edit to save url in array
//sharepreference.add(context, product);
sharedPreference.saveBtnState(context, stateBtn);
Toast.makeText(context,
"Added to Favourite!",
Toast.LENGTH_SHORT).show();
favBtn.setColorFilter(Color.argb(255, 249, 0, 0));//red
Toast.makeText(context,
"Button state is " + stateBtn,
Toast.LENGTH_SHORT).show();
} else {
sharedPreference.saveBtnState(context, stateBtn);
favBtn.setColorFilter(Color.argb(255, 192, 192, 192));//grey
}
}
});
View photoRow = inflater.inflate(R.layout.item_fullscreen_image, container,
false);
TouchImageView fullScreenImg;
fullScreenImg =(TouchImageView)photoRow.findViewById(R.id.img_flickr);
// added imageloader for better performance
StaggeredDemoApplication.getImageLoader().get(imageArrayList[position],
ImageLoader.getImageListener(fullScreenImg, R.drawable.bg_no_image, android.R.drawable.ic_dialog_alert), container.getWidth(), 0);
((ViewPager) container).addView(photoRow);
stopProgress();
return photoRow;
}
private void stopProgress() {
mProgress.cancel();
}
private void showProgress() {
mProgress = ProgressDialog.show(FullScreenImageActivity.this, "", "Loading...");
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("content", FavouriteListFragment.ARG_ITEM_ID);
super.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
}
}
Here is the code in sharepreferences
public class SharedPreference {
public static final String PREFS_NAME = "AOP_PREFS";
public static final String PREFS_STATE="AOP_BTN";
public static final String PREFS_FAV_URL="AOP_FAV_URL";
public static final String PREFS_KEY = "AOP_PREFS_String";
public static final String PREF_BTN_KEY = "AOP_PREF_BTN";
public static final String PREF_URL_KEY = "AOP_PREF_URL";
public SharedPreference() {
super();
}
public void save(Context context, String text) {
SharedPreferences settings;
Editor editor;
//edit here to add image array list
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putString(PREFS_KEY, text); //3
editor.commit(); //4
}
public String getValue(Context context) {
SharedPreferences settings;
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
text = settings.getString(PREFS_KEY, null);
return text;
}
public String getPrefsFavUrl(Context context){
SharedPreferences settings;
String favUrl;
settings = context.getSharedPreferences(PREFS_FAV_URL, Context.MODE_PRIVATE);
favUrl = settings.getString(PREF_URL_KEY, null);
return favUrl;
}
public void clearSharedPreference(Context context) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.clear();
editor.commit();
}
public void removeValue(Context context) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.remove(PREFS_KEY);
editor.commit();
}
public void saveBtnState(Context context, Boolean stateBtn) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putBoolean(PREF_BTN_KEY, stateBtn);//added state for button
editor.commit(); //4
}
public boolean getBtnState(Context context,String text)//edit to store url here and check the boolean here
{
SharedPreferences prefs;
prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String favUrl = getPrefsFavUrl(context);
boolean switchState = false;
if(favUrl.equals(text)) {
switchState=true;
}
return switchState;
}
public void saveFavourite(FragmentActivity activity, String favouriteUrl) {
SharedPreferences settings;
Editor editor;
settings = activity.getSharedPreferences(PREFS_FAV_URL, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putString(PREF_URL_KEY, favouriteUrl); //3
editor.commit(); //4
}
}
Here is the error log file
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.Class.newInstance()' on a null object reference
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at com.example.myapp.MainActivity.displayView(MainActivity.java:141)
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at com.example.myapp.MainActivity.onCreate(MainActivity.java:41)
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
Here is my MainActivity program
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentFlickrGridImage.OnFragmentInteractionListener, ShareActionProvider.OnShareTargetSelectedListener {
private int backstack_count;
private boolean viewIsAtHome;
private Fragment contentFragment;
private ShareActionProvider share;
private Intent shareIntent=new Intent(Intent.ACTION_SEND);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
displayView(R.id.recent_picture);
}
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.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener(this);
shareIntent.setType("text/plain");
}
private void replaceFragment(Fragment fragment, boolean isAddToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.flContent, fragment);
if (isAddToBackStack) {
transaction.addToBackStack(fragment.getClass().toString());
backstack_count ++;
}
transaction.commit();
}
#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);
MenuItem item = menu.findItem(R.id.share);
share = new ShareActionProvider(this);
MenuItemCompat.setActionProvider(item, share);
return(super.onCreateOptionsMenu(menu));
}
#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.share) {
onShareAction();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onShareAction() {
String yourShareText = "test";
Intent shareIntent = ShareCompat.IntentBuilder.from(this).setType("text/plain").setText(yourShareText).getIntent();
// Set the share Intent
if (share != null) {
share.setShareIntent(shareIntent);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
displayView(item.getItemId());
return true;
}
private void displayView(int itemId) {
Fragment fragment = null;
Class fragmentClass = null;
String title="";
switch (itemId){
case R.id.one:
fragment = new FragmentFlickrGridImage("one");
title="one";
viewIsAtHome=true;
break;
case R.id.two:
fragment = new FragmentFlickrGridImage(" two");
title ="two";
viewIsAtHome=false;
break;
case R.id.three:
fragment = new FragmentFlickrGridImage("three");
title="three";
viewIsAtHome=false;
break;
case R.id.four:
fragment=new FavouriteListFragment();
title="Favourite";
viewIsAtHome=false;
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
getSupportActionBar().setTitle(title);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
if (!viewIsAtHome) { //if the current view is not the Recent Hot Girl fragment
displayView(R.id.recent_picture);
} else {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("Are you sure?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.setCancelable(false)
.setTitle("Exit");
builder.show();
}
}
#Override
public boolean onShareTargetSelected(ShareActionProvider source,
Intent intent) {
Toast.makeText(this, intent.getComponent().toString(),
Toast.LENGTH_LONG).show();
return(false);
}
}

The error line is:
fragment = (Fragment) fragmentClass.newInstance();
fragmentClass is always assigned with null object when you use it in fragmentClass.newInstance(), and it always have null value because you never assign it with other value. Try to remove these lines:
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Anyway, using non-empty constructor for the fragments is not a good practice. You should use this pattern instead.
EDIT
Check whether fragment is empty or not:
if (fragment != null){
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}

Related

Navigation Drawer Back Pressed Fragment Doesn't Load

I have a navigation drawer with fragments. At start, I display Home fragment as default.
There are options on navigation menu. In 2 fragments I have SwipeRefreshLayout. Until all recyclerview data are fetched then I display data and invisible SwipeRefreshLayout.
One of these fragments (included SwipeRefReshLayout) works fine but, in Home fragment something is wrong.
For example(use case)
You started app and you saw Home fragment
You clicked Profile fragment on navigation menu
You run onBackPressed(back button).
In this case data never loads and SwipeRefReshLayout is always spinning. (I also tried without refreshlayout, still same)
Any idea how to fix this? My thought is, its about displaying default fragment.
Navigation Drawer Activity
public class Page_Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
NavigationView navigationView;
SharedPreferences mSharedPref;
DrawerLayout drawer;
private Tracker mTracker;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page__navigation);
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbar_head = findViewById(R.id.toolbar_head);
ImageView toolbar_image = findViewById(R.id.toolbar_image);
ImageView toolbar_profile = findViewById(R.id.toolbar_profile);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName("page_navigation");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
//FIRST SETTINGS
setSupportActionBar(toolbar);
Typeface customFont = Typeface.createFromAsset(getAssets(), "Montserrat-Medium.ttf");
toolbar_head.setTypeface(customFont);
//Get Sessions
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String session_user_name = mSharedPref.getString("session_user_name", "");
String session_user_photo = mSharedPref.getString("session_user_photo", "");
//Navigation Drawer
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
//
View headerView = navigationView.getHeaderView(0);
TextView nav_userName = (TextView) headerView.findViewById(R.id.textView_nav_userName);
CircleImageView imageView_navigation = (CircleImageView) headerView.findViewById(R.id.imageView_navigation);
Glide.with(getApplicationContext()).load(session_user_photo).into(imageView_navigation);
nav_userName.setText(session_user_name);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.START)) {
drawer.closeDrawer(Gravity.START);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showProfileFragment();
}
}, 300);
}
});
toolbar_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
toolbar_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
FragmentManager manager = getSupportFragmentManager();
fragment = new Nav_Profile();
fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
});
displayDefaultFragment();
}
#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.page__navigation, 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.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (id) {
case R.id.nav_home:
fragment = new Nav_Home();
break;
case R.id.nav_contact:
fragment = new Nav_Contact();
break;
case R.id.nav_articles:
fragment = new Nav_Article();
break;
case R.id.nav_about:
fragment = new Nav_AboutUs();
break;
case R.id.nav_suggest:
fragment = new Nav_Suggest();
break;
case R.id.nav_share:
fragment = new Nav_Share();
break;
case R.id.nav_rateApp:
fragment = new Nav_RateApp();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.navContent, fragment)
.addToBackStack(null)
.commit();
}
}, 350);
return true;
}
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
}
Home Fragment
public class Nav_Home extends Fragment implements View.OnClickListener{
SharedPreferences mSharedPref;
private SwipeRefreshLayout swipeRefresh_home;
private CardView item_homeTop_coupons, item_homeTop_draws, item_homeTop_event;
private LinearLayout layout_all_article, layout_all_999;
private ScrollView shimmer_home;
private List<Model_ListItem> listNewItems;
private RecyclerView recyclerView_item_home;
private List<Model_Article> articleList;
private RecyclerView recyclerView_article_home;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetchItemsNew();
fetchArticlesNew();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav__home, container, false);
item_homeTop_coupons = view.findViewById(R.id.item_homeTop_coupons);
item_homeTop_draws = view.findViewById(R.id.item_homeTop_draws);
item_homeTop_event = view.findViewById(R.id.item_homeTop_event);
recyclerView_item_home = view.findViewById(R.id.recyclerView_item_home);
recyclerView_article_home = view.findViewById(R.id.recyclerView_article_home);
layout_all_article = view.findViewById(R.id.layout_all_article);
layout_all_999 = view.findViewById(R.id.layout_all_999);
swipeRefresh_home = view.findViewById(R.id.swipeRefresh_home);
shimmer_home = view.findViewById(R.id.shimmer_home);
item_homeTop_coupons.setOnClickListener(this);
item_homeTop_draws.setOnClickListener(this);
item_homeTop_event.setOnClickListener(this);
layout_all_999.setOnClickListener(this);
layout_all_article.setOnClickListener(this);
//first settngs
mSharedPref = PreferenceManager.getDefaultSharedPreferences(view.getContext());
String session_user_email = mSharedPref.getString("session_user_email","");
swipeRefresh_home.setRefreshing(true);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.item_homeTop_coupons:
startActivity(new Intent(getContext(), Page_Coupon.class));
break;
case R.id.item_homeTop_draws:
startActivity(new Intent(getContext(), Page_Draw.class));
break;
case R.id.item_homeTop_event:
startActivity(new Intent(getContext(), Page_Event.class));
break;
case R.id.layout_all_999:
//999 city search activity
startActivity(new Intent(getContext(), Page_SearchCity.class));
break;
case R.id.layout_all_article:
//article fragment
Fragment fragment;
FragmentManager fragmentManager = getFragmentManager();
fragment = new Nav_Article();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
break;
}
}
public void fetchItemsNew(){
listNewItems = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchItemsNew();
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
if(response.code() == 200){
listNewItems = response.body();
Adapter_HomeItem adapter_homeItem = new Adapter_HomeItem(getContext(), listNewItems);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_item_home.setHasFixedSize(true);
recyclerView_item_home.setLayoutManager(layoutManager);
recyclerView_item_home.setAdapter(adapter_homeItem);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView_item_home);
}
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}
public void fetchArticlesNew(){
articleList = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_Article>> callArticle = api_service.fetchArticlesNew();
callArticle.enqueue(new Callback<List<Model_Article>>() {
#Override
public void onResponse(Call<List<Model_Article>> call, Response<List<Model_Article>> response) {
if(response.code() == 200){
articleList = response.body();
Adapter_HomeArticles adapter_homeArticles = new Adapter_HomeArticles(getContext(), articleList);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_article_home.setLayoutManager(layoutManager);
recyclerView_article_home.setHasFixedSize(true);
recyclerView_article_home.setAdapter(adapter_homeArticles);
}
}
#Override
public void onFailure(Call<List<Model_Article>> call, Throwable t) {
}
});
}
}
Firstly you must disable SwipeRefreshLayout spinning when successfully or not fetched data:
swipeRefresh_home.setRefreshing(false);
If you do not do this spinner will be spinning all the time.
Another problem is that you have one fragment and you try to assign to it Nav_Home fragment and Nav_Profile fragment.
Fragment fragment;
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
Try to separate them and show like this:
Fragment homeFragment;
Fragment profileFragment;
public void displayDefaultFragment() {
homeFragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, homeFragment).commit();
}
public void showProfileFragment() {
profileFragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, profileFragment).addToBackStack(null).commit();
}

Android app stuck on sharing username from 1 activity to another but not getting it through SharedPreferences

Basically i want to use the email id from which user log in to store and use in any activity for fetching the data from server. Please help me.
First Activity Sign_In
public class Sign_In extends AppCompatActivity {
public static final String LOGIN_URL="url";
public static final String KEY_EMAIL="email";
public static final String KEY_PASSWORD="password";
public static final String LOGIN_SUCCESS="success";
public static final String SHARED_PREF_NAME="tech";
public static final String EMAIL_SHARED_PREF="email";
public static final String LOGGEDIN_SHARED_PREF="loggedin";
private EditText editTextEmail;
private EditText editTextPassword;
private Button BtnLogin;
private boolean loggedIn=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign__in);
editTextEmail=(EditText)findViewById(R.id.editText3);
editTextPassword=(EditText)findViewById(R.id.editText2);
BtnLogin=(Button)findViewById(R.id.button);
BtnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
}
private void login() {
final String email = editTextEmail.getText().toString().trim().toLowerCase();
final String password = editTextPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equalsIgnoreCase(LOGIN_SUCCESS)){
SharedPreferences sharedPreferences = Sign_In.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(EMAIL_SHARED_PREF, email);
editor.apply();
Intent intent = new Intent(Sign_In.this, HomePage.class);
startActivity(intent);
}
else {
Toast.makeText(Sign_In.this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> prams = new HashMap<>();
prams.put(KEY_EMAIL, email);
prams.put(KEY_PASSWORD, password);
return prams;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(LOGGEDIN_SHARED_PREF, false);
if (loggedIn){
Intent intent = new Intent(Sign_In.this, HomePage.class);
startActivity(intent);
}
}
}
Second Activity HomePage
import static in.borrowfunds.build30.Sign_In.EMAIL_SHARED_PREF;
import static in.borrowfunds.build30.Sign_In.SHARED_PREF_NAME;
public class HomePage extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode==KeyEvent.KEYCODE_BACK){
AlertDialog.Builder alertbox=new AlertDialog.Builder(HomePage.this);
alertbox.setTitle("You want to Exit?");
alertbox.setCancelable(false);
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), Sign_In.class);
startActivity(intent);
finish();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertbox.show();
}
return super.onKeyDown(keyCode,event);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_b) {
Intent intent = new Intent(getApplicationContext(), B.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_l) {
Intent intent = new Intent(getApplicationContext(), L.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_p) {
Intent intent = new Intent(getApplicationContext(), P.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_e) {
Intent intent = new Intent(getApplicationContext(), E.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_pr) {
Intent intent = new Intent(getApplicationContext(), Pr.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_logout) {
SharedPreferences sharedpreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
HomePage.this.finish();
Intent intent = new Intent(getApplicationContext(), Sign_In.class);
startActivity(intent);
return true;
}
else if (id == R.id.nav_email) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto","contact#hgdcsa.net",null));
try {
startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Mail account not configured", Toast.LENGTH_SHORT).show();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
After you retreive the data, whatever it may be, you can use SharedPreferences to store and access it locally on the device:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String pref = preferences.getString("preference_key", "default-username");
// if the pref isn't set, you can designate a default value
Any activity you want to access this data, you can call preferences.getString (or any type) to access what the user stored.
You can store data in the SharedPreferences by edit and commiting changes:
preferences.edit().putString("preference_key", "username").commit();
Preferences come in all kinds of types, notably:
String
int
boolean
I got the answer by myself, what a relief, was stuck on this for about 10 days.
Btw thanks for the anwers and i'm providing the solution for future purpose.
First Activity
SharedPreferences sharedPreferences = Sign_In.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(EMAIL_SHARED_PREF, email);
editor.apply();
Intent intent = new Intent(Sign_In.this, HomePage.class);
intent.putExtra(EMAIL_SHARED_PREF,email);
startActivity(intent);
Second Activity
TextView email1;
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
String email = sharedPreferences.getString(EMAIL_SHARED_PREF, "");
email1=(TextView)findViewById(R.id.textView18);
email1.setText(email);

Navigation Drawer not opening when using android support library v23.4.0

Hello everyone I'm developing an app that uses old navigation drawer approach. When I update 'com.android.support:appcompat-v7:23.1.1' to 'com.android.support:appcompat-v7:23.4.0' my navigation drawer not opening.
I debugged code and look for deprecated items but could not find any error code or message. Everything works perfectly but navigation drawer is not opening. Here is my code. Thanks in advance.
MainActivity.class
public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, TapuInterface.IAuthorization {
TapuUtils tapuUtils = new TapuUtils();
String userMail, userPassword;
SharedPreferences.Editor editor;
SharedPreferences preferences;
Tracker mTracker;
Bundle bundle;
String tapuAuth = "false";
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleAnalytics.getInstance(this).setLocalDispatchPeriod(15);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
Countly.sharedInstance().init(this, getString(R.string.countly_server), getString(R.string.countly_key));
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,(DrawerLayout) findViewById(R.id.drawer_layout));
ActionBar mActionBar = getSupportActionBar();
assert mActionBar != null;
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF297AA6));
if (savedInstanceState == null) {
bundle = getIntent().getExtras();
userMail = bundle.getString("personname");
userPassword = bundle.getString("personpassword");
tapuAuth = bundle.getString("tapu");
}
TapuCredentials.setUserMail(userMail);
TapuCredentials.setUserPassword(userPassword);
TapuCredentials.setTapuAuth(tapuAuth);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, MainMapFragment.newInstance(position + 1), "MapFragment")
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit_alert))
.setCancelable(true)
.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
LoginActivity.fa.finish();
}
})
.setNegativeButton(getString(R.string.no), null)
.show();
}
#Override
public void onStart() {
super.onStart();
Countly.sharedInstance().onStart();
}
#Override
public void onStop() {
super.onStop();
Countly.sharedInstance().onStop();
}
#Override
protected void onResume() {
super.onResume();
mTracker.setScreenName(getResources().getString(R.string.main_screen));
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
Here is my NavigationDrawer.class
public class NavigationDrawerFragment extends Fragment {
private static NavigationDrawerAdapter myAdapter;
public static ArrayList<ListItem> myItems = new ArrayList<>();
public static UserCredentials mUserCredentials = new UserCredentials();
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private DynamicListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
static LegendFragment frLegend = new LegendFragment();
Button mEditLayers, mShowLegend;
String personName,userType,tapucontrol;
TextView mLayersText;
static FragmentManager fragmentManager;
Bundle extras;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
if (savedInstanceState == null) {
extras = getActivity().getIntent().getExtras();
if(mUserCredentials.getUserName()==null || mUserCredentials.getPassword()==null){
mUserCredentials.setUserAccount(extras.getString("username"), extras.getString("password"));
}
personName = extras.getString("personname");
userType = extras.getString("usertype");
tapucontrol = extras.getString("tapu");
}
mDrawerListView = (DynamicListView) rootView.findViewById(R.id.dynamiclistivew);
mLayersText = (TextView) rootView.findViewById(R.id.textview_layers);
myAdapter = new NavigationDrawerAdapter(getActivity(), myItems);
mDrawerListView.setAdapter(myAdapter);
fragmentManager = getFragmentManager();
mDrawerListView.setCheeseList(myItems);
mDrawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mEditLayers = (Button) rootView.findViewById(R.id.button);
mShowLegend = (Button) rootView.findViewById(R.id.legendbutton);
mEditLayers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mEditLayers.getText().equals("Düzenle")) {
myAdapter.setEditMode(true);
mEditLayers.setText(getActivity().getString(R.string.ok));
} else {
myAdapter.setEditMode(false);
mEditLayers.setText(getActivity().getString(R.string.editlayers));
}
}
});
return rootView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
null, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
FragmentTransaction ft = fragmentManager.beginTransaction();
if (frLegend.isAdded()) {
ft.remove(frLegend);
ft.commitAllowingStateLoss();
mEditLayers.setVisibility(View.VISIBLE);
mLayersText.setText("Katmanlar");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.main, menu);
// showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
Intent s = new Intent(getActivity(), SearchMainActivity.class);
s.putExtra("username", mUserCredentials.getUserName());
s.putExtra("password", mUserCredentials.getPassword());
s.putExtra("tapu",tapucontrol);
startActivity(s);
break;
case R.id.action_basemaps:
Intent cb = new Intent(getActivity(), BaseMapsActivity.class);
startActivity(cb);
break;
case R.id.action_addlayer:
if (isNetworkAvailable(getActivity())) {
Intent al = new Intent(getActivity(), AddLayerActivity.class);
al.putExtra("usertype", userType);
startActivity(al);
} else {
Toast.makeText(getActivity(), "Lütfen internet bağlantınızı kontrol ediniz.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.action_about:
Intent au = new Intent(getActivity(), AboutActivity.class);
au.putExtras(extras);
startActivity(au);
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class ListItem {
String textdata;
Integer progress;
public ListItem(String textdata, int progress) {
this.textdata = textdata;
this.progress = progress;
}
public boolean equals(Object o) {
ListItem ndListItemObject = (ListItem) o;
return this.textdata.equalsIgnoreCase(ndListItemObject.textdata);
}
}
public void addLayersection(String name, int progress) {
ListItem listItem = new ListItem(name, progress);
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.contains(listItem)) {
myItems.remove(listItem);
} else {
myItems.add(0, listItem);
}
}
}
myAdapter.notifyDataSetChanged();
}
public int getListSizee() {
return myItems.size();
}
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
The Drawer is locked.
Change
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
to
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
Here is the late solution that I find with myself. drawerOpenCloseControl is boolean flag. I am controlling true or false. And then open and close manually.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(drawerOpenCloseControl){
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
drawerOpenCloseControl = false;
}
else{
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerOpenCloseControl = true;
}
break;
}
return super.onOptionsItemSelected(item);
}

Android: "Unable to instantiate Fragment"

Here is my Java code. The problem is whenever I return to my application from foreground, the app crashes giving the error shown in the stack trace below (unable to instantiate framgent).
MainActivity.java
public class MainActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
public static final String KEY_CURRENT_OPTION = "currentOption";
public static final String KEY_SELECT_OPTION = "selectOption";
ProgressDialog dialog = null;
View drawerView;
//ImageView updown;
DrawerLayout mDrawerLayout;
ListView optionsListView;
ActionBarDrawerToggle mDrawerToggle;
private int currentOption = -1;
private boolean isRegistered = false;
BookACabFragment bookNowFragment;
BookACabFragment preBookFragment;
BookingsListFragment bookingsListFragment;
AccountFragment accountFragment;
CouponsFragment couponsFragment;
FavouriteAddressFragment favAddressFragment;
private FavDriversFragment favDriversFragment;
private TypedArray navMenuIcons;
public static SmoothProgressBar mGoogleNow;
//LocationReceiver receiver;
private NavDrawerListAdapter adapterrr;
static int saveInstance = 0;
private ArrayList<NavDrawerItem> navDrawerItems;
String[] optionTitles;
SharedPreferences prefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Log.d(TAG, "before content view");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
// Log.d(TAG, "after content view");
ActionBar actionBar = getActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
// actionBar.setBackgroundDrawable;
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(Html.fromHtml("<font color='#000000'></font>"));
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_main);
optionsListView = (ListView) findViewById(R.id.listview_options_drawer);
mGoogleNow = (SmoothProgressBar) findViewById(R.id.google_now);
drawerView = findViewById(R.id.left_drawer);
optionsListView.setAdapter(new MainDrawerListAdapter(this));
optionsListView.setOnItemClickListener(new DrawerItemClickListener());
optionTitles = getResources().getStringArray(R.array.main_drawer_options);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems.add(new NavDrawerItem(optionTitles[0], navMenuIcons.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(optionTitles[1], navMenuIcons.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(optionTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(optionTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(optionTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(optionTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// navDrawerItems.add(new NavDrawerItem(optionTitles[6], navMenuIcons.getResourceId(6, -1), true, "50+"));
navMenuIcons.recycle();
adapterrr = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editor = prefs.edit();
optionsListView.setAdapter(adapterrr);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.navopener, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey(KEY_CURRENT_OPTION)) {
currentOption = extras.getInt(KEY_CURRENT_OPTION);
}
if (savedInstanceState != null) {
currentOption = savedInstanceState.getInt(KEY_CURRENT_OPTION);
}
selectDrawerItem(currentOption);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(KEY_CURRENT_OPTION, currentOption);
super.onSaveInstanceState(outState);
}
#Override
public void onClick(View v) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(drawerView)) {
mDrawerLayout.closeDrawer(drawerView);
} else {
mDrawerLayout.openDrawer(drawerView);
}
break;
}
return super.onOptionsItemSelected(item);
}
public void GotoTab(int i) {
if (bookingsListFragment == null)
bookingsListFragment = BookingsListFragment.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, BookingsListFragment.newInstance());
ft.commit();
}
/* #Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
//setTitle("REPORT AN ISSUE");
setTitle("Booking Detail" );
ActionBar actionbar = getActionBar();
//actionbar.setIcon(R.drawable.icon);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff00000")));
actionbar.setDisplayHomeAsUpEnabled(true);
MenuInflater menuinflater = getMenuInflater();
menuinflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}*/
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectDrawerItem(position);
mDrawerLayout.closeDrawer(drawerView);
}
}
private void selectDrawerItem(int position) {
if (position == -1) {
position = 0;
}
setTitle(optionTitles[position]);
currentOption = position;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (position) {
case 0:
saveInstance = 1;
Log.e(TAG, "selecting the map fragment");
ft.replace(R.id.content_frame, BookACabFragment.newInstance(true));
ft.commit();
break;
// case 1:
//
// ft.replace(R.id.content_frame, BookACabFragment.newInstance(false));
// ft.commit();
// break;
case 1:
saveInstance = 2;
if (bookingsListFragment == null)
bookingsListFragment = BookingsListFragment.newInstance();
ft.replace(R.id.content_frame, BookingsListFragment.newInstance());
ft.commit();
break;
case 2:
saveInstance = 3;
if (accountFragment == null) {
accountFragment = AccountFragment.newInstance();
}
ft.replace(R.id.content_frame, accountFragment);
ft.commit();
break;
case 3:
saveInstance = 4;
if (favAddressFragment == null) {
favAddressFragment = favAddressFragment.newInstance();
}
ft.replace(R.id.content_frame, favAddressFragment);
ft.commit();
break;
case 4:
saveInstance = 5;
if (couponsFragment == null) {
couponsFragment = CouponsFragment.newInstance();
}
ft.replace(R.id.content_frame, couponsFragment);
ft.commit();
break;
case 5:
saveInstance = 6;
logout();
break;
}
}
/*
#Override
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(), "In resume "+saveInstance, Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(saveInstance==0){
ft.replace(R.id.content_frame, BookACabFragment.newInstance(true));
ft.commit();
}else if(saveInstance==1){
Log.e(TAG, "selecting the map fragment");
ft.replace(R.id.content_frame, BookACabFragment.newInstance(true));
ft.commit();
saveInstance=-1;
}
else if(saveInstance==2){
if(bookingsListFragment == null)
bookingsListFragment = BookingsListFragment.newInstance();
ft.replace(R.id.content_frame, BookingsListFragment.newInstance());
ft.commit();
saveInstance=-1;
}else if(saveInstance==3){
if(accountFragment == null) {
accountFragment = AccountFragment.newInstance();
}
ft.replace(R.id.content_frame, accountFragment);
ft.commit();
saveInstance=-1;
}else if(saveInstance==4){
if (favAddressFragment == null) {
favAddressFragment = favAddressFragment.newInstance();
}
ft.replace(R.id.content_frame, favAddressFragment);
ft.commit();
saveInstance=-1;
}else if(saveInstance==5){
if (couponsFragment == null) {
couponsFragment = CouponsFragment.newInstance();
}
ft.replace(R.id.content_frame, couponsFragment);
ft.commit();
saveInstance=-1;
}
else if(saveInstance==6){
logout();
saveInstance=-1;
}
}
/**4444
* Broadcast receiver for changing the fragment
*/
class FragmentChangeRequestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(KEY_SELECT_OPTION)) {
selectDrawerItem(extras.getInt(KEY_SELECT_OPTION));
}
}
}
private void logout() {
final Token token = IoUtils.getTokenFromPrefs(this);
if (token != null) {
String regId = GcmUtils.getRegistrationId(this);
mGoogleNow.setVisibility(View.VISIBLE);
// dialog = ProgressDialog.show(MainActivity.this, "",
// "Loading...", true);
// dialog.setCanceledOnTouchOutside(false);
AuthAPI.unregisterGCM(token.token, regId, new AuthAPI.OnGcmRegListener() {
#Override
public void onRegistered() {
}
#Override
public void onUnregistered() {
AuthAPI.logout(token, new AuthAPI.OnAuthResultListener() {
#Override
public void onSuccess(Token token) {
Passenger.invalidate();
mGoogleNow.setVisibility(View.GONE);
// dialog.dismiss();
showLogin();
}
#Override
public void onFailure(Exception e) {
}
});
}
#Override
public void onError(Exception e) {
}
});
}
}
private void showLogin() {
IoUtils.deleteTokenFromPrefs(this);
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
MainActivity.this.finish();
}
#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);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
BookACabFragment.java
public class BookACabFragment extends Fragment implements
GoogleMap.OnMapClickListener, GoogleMap.OnMarkerDragListener,
GoogleMap.OnMarkerClickListener, ViewPager.OnPageChangeListener,LocationListener,GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,View.OnClickListener {
String driverLongitude, driverlatitude, text;
String rotation;
float rotationF;
TextView tvdisTime;
ImageView taxiicon,ivCenterMaker;
HttpPost httppost;
StringBuffer buffer;
HttpResponse httpresponse;
InputStream content;
JSONArray daArray = null;
HttpClient httpclient;
JSONArray data = null;
String jsonString;
// HttpClient httpclient;
List<NameValuePair> nameValuePairs;
private ProgressDialog pDialog;
private static final String TAG = "BookACabFragment";
private static final float MAP_SCROLL_FACTOR = 3.33f;
private static final float MAP_SINGLE_MARKER_ZOOM = 14;
GoogleMap googleMap;
SupportMapFragment mapFragment;
SharedPreferences prefs;
SharedPreferences.Editor editor;
SlidingUpPanelLayout slidingLayout;
boolean isPanelExpanded = false;
boolean isConfirmedFragment = false;
SessionManager s;
SessionManager session;
NonSwipeableViewPager viewPager;
LinearLayout slidePanel;
BroadcastReceiver receiver;
boolean isRegistered = false;
String[] ss;
ArrayList<Marker> cabMarkers;
private ArrayList<Cab> mCabs;
public boolean showCabPicker;
LatLng ll;
TextView handleText;
String RDD = "0";
ImageView updown;
int panelHeight;
int activityHeight;
boolean panelFullScreen = false;
public static boolean openSlidingPanel = false;
View NavView1,NavView2,NavView3,NavView4;
LinearLayout NavViewMain;
BasePickerFragment currentPickerFragment;
PickSourceFragment pickSourceFragment;
PickCabTypeFragment pickCabTypeFragment;
PickCabFragment pickCabFragment;
PickDestinationFragment pickDestinationFragment;
PickDestinationFragmentPrebook pickDestinationFragmentPrebook;
ReviewFragment reviewFragment;
int currentPagerItem = 0;
String cabDistance="";
private LocationRequest mLocationRequest;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
// Stores the current instantiation of the location client in this object
private LocationClient mLocationClient;
boolean mUpdatesRequested = false;
private Geocoder geocoder;
private List<Address> addresses;
private LatLng latlngcenter;
String duration = "";
String distance = "";
Cab cAutoassign;
List<Marker> markerList;
ArrayList<LatLng> locations;
int viewCount=0;
private ScheduledExecutorService scheduler;
private ScheduledFuture<?> scheduledFuture;
LinearLayout ll_Rn_Rl;
Button Rn,RL;
static int vps=0;
public BookACabFragment(){}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onDisconnected() {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onClick(View v) {
int id = v.getId();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
switch (id) {
case R.id.bt_Rn:
// Toast.makeText(getActivity(),openSlidingPanel+"clickqwal",Toast.LENGTH_SHORT).show();
openSlidingPanel=true;
ft.replace(R.id.content_frame, BookACabFragment.newInstance(true));
ft.commit();
/
break;
case R.id.bt_RL:
openSlidingPanel=true;
ft.replace(R.id.content_frame, BookACabFragment.newInstance(false));
ft.commit();
// ll_Rn_Rl.setVisibility(View.GONE);
//Your Operation
break;
}
}
public enum Fragments {
SOURCE_PICKER,
CABTYPE_PICKER,
CAB_PICKER,
DESTINATION_PICKER;
}
Fragments currentFrag;
String[] handleTitlesRideNow, handleTitlesPreBook;
public interface NavigationListener {
public void goBack();
public void goForward();
public void goForwardWithoutDestination();
}
public static BookACabFragment newInstance(boolean showCabPicker) {
BookACabFragment fragment = new BookACabFragment();
Bundle args = new Bundle(1);
args.putBoolean("showCabPicker", showCabPicker);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
showCabPicker = args.getBoolean("showCabPicker");
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
editor = prefs.edit();
handleTitlesRideNow = getResources().getStringArray(R.array.handle_titles_ride_now);
handleTitlesPreBook = getResources().getStringArray(R.array.handle_titles_prebook);
ActionBar actionBar = getActivity().getActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
currentFrag = Fragments.SOURCE_PICKER;
pickSourceFragment = PickSourceFragment.newInstance(!showCabPicker);
pickSourceFragment.setOnAttachListener(new PickSourceFragment.OnAttachListener() {
#Override
public void onAttach() {
initMarker();
}
});
if (showCabPicker)
pickCabFragment = PickCabFragment.newInstance();
pickDestinationFragment = PickDestinationFragment.newInstance();
pickDestinationFragmentPrebook = PickDestinationFragmentPrebook.newInstance();
pickCabTypeFragment = PickCabTypeFragment.newInstance();
currentPickerFragment = pickSourceFragment;
reviewFragment = ReviewFragment.newInstance();
// initReceivers();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ActionBar actionBar = getActivity().getActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
actionBar.setHomeButtonEnabled(true);
actionBar.setIcon(android.R.color.transparent);
String fontPath = "fonts/RobotoCondensed-Regular.ttf";
Typeface font2 = Typeface.createFromAsset(getActivity().getAssets(), fontPath);
SpannableStringBuilder SS = new SpannableStringBuilder(" Book Taxi");
SS.setSpan (new CustomTypefaceSpan("", font2), 0, SS.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
actionBar.setTitle(SS);
int ActionBarTitleID = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView)getActivity().findViewById(ActionBarTitleID);
yourTextView.setTextAppearance(getActivity(), android.R.style.TextAppearance_Large);
actionBar.setDisplayHomeAsUpEnabled(true);
return inflater.inflate(R.layout.fragment_bookacab, container, false);
}
#Override
public void onResume() {
super.onResume();
vps= viewPager.getCurrentItem();
viewPager.setCurrentItem(vps);
startTimeScheduledExecutorService();
}
here is the Stack Strace
6428-6428com.cabbooking.passenger EAndroidRuntime﹕ FATAL EXCEPTION main
java.lang.RuntimeException Unable to start activity ComponentInfo{com.cabbooking.passengercom.cabbooking.passengerapp.screens.MainActivity} android.support.v4.app.Fragment$InstantiationException Unable to instantiate fragment com.cabbooking.passengerapp.screens.BookACabFragment$18 make sure class name exists, is public, and has an empty constructor that is public
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2391)
at android.app.ActivityThread.access$600(ActivityThread.java151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java1335)
at android.os.Handler.dispatchMessage(Handler.java99)
at android.os.Looper.loop(Looper.java155)
at android.app.ActivityThread.main(ActivityThread.java5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java796)
at dalvik.system.NativeStart.main(Native Method)
Caused by android.support.v4.app.Fragment$InstantiationException Unable to instantiate fragment com.cabbooking.passengerapp.screens.BookACabFragment$18 make sure class name exists, is public, and has an empty constructor that is public
at android.support.v4.app.Fragment.instantiate(Fragment.java415)
at android.support.v4.app.FragmentState.instantiate(Fragment.java99)
at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java1807)
at android.support.v4.app.Fragment.performCreate(Fragment.java1493)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java908)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java1121)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java1103)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java1896)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java216)
at com.cabbooking.passengerapp.screens.MainActivity.onCreate(MainActivity.java75)
at android.app.Activity.performCreate(Activity.java5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java2311)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2391)
            at android.app.ActivityThread.access$600(ActivityThread.java151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java1335)
            at android.os.Handler.dispatchMessage(Handler.java99)
            at android.os.Looper.loop(Looper.java155)
            at android.app.ActivityThread.main(ActivityThread.java5520)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java796)
            at dalvik.system.NativeStart.main(Native Method)
Caused by java.lang.InstantiationException can't instantiate class com.cabbooking.passengerapp.screens.BookACabFragment$18; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java1319)
at android.support.v4.app.Fragment.instantiate(Fragment.java404)
            at android.support.v4.app.FragmentState.instantiate(Fragment.java99)
            at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java1807)
            at android.support.v4.app.Fragment.performCreate(Fragment.java1493)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java908)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java1121)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java1103)
            at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java1896)
            at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java216)
            at com.cabbooking.passengerapp.screens.MainActivity.onCreate(MainActivity.java75)
            at android.app.Activity.performCreate(Activity.java5066)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java1101)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2391)
            at android.app.ActivityThread.access$600(ActivityThread.java151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java1335)
            at android.os.Handler.dispatchMessage(Handler.java99)
            at android.os.Looper.loop(Looper.java155)
            at android.app.ActivityThread.main(ActivityThread.java5520)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java511)
      
Read the log carefully:
Caused by java.lang.InstantiationException can't instantiate class com.cabbooking.passengerapp.screens.BookACabFragment$18; no empty constructor
The android os could not instantiate the class BookACabFragment$18, not your Fragment BookACabFragment!
I do not think that it is possible to create an anonymous fragment, because of the lack of public accessability.
Update: After reading your code. I think I found your the wrong code:
mapFragment = new SupportMapFragment() {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = mapFragment.getMap();
if (googleMap != null) {
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.setOnMapClickListener(BookACabFragment.this);
googleMap.setOnMarkerDragListener(BookACabFragment.this);
googleMap.setOnMarkerClickListener(BookACabFragment.this);
//googleMap.setMyLocationEnabled(true);
pickedLocation = GeoUtils.getLocationFromPreferences(getActivity());
}
}
};
You cannot create an anonymous fragment. Either put your Fragment to a new class or create it as static-class in your BookACabFragment. I would prefer the first option:
public class MySupportMapFragment extends SupportMapFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Your funky stuff
}
}
Additional hint: Your class has over 2000 lines of code. You should really refactor this monolith.
Try adding an empty constructor to your BookACabFragment.
public BookACabFragment() {
}

keep data between fragment

I'm trying to keep data(PID) from fragmentscan to fragment maintenance using arguments,
but the data always null in my Log.d("tag", "PID SCAN: " + data);
whats wrong with my arguments?
this is my code
public class FragmentScan extends Fragment {
TextView tvPid;
TextView txtName;
TextView txtPrice;
TextView txtDesc;
TextView txtSpec;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://10.0.3.2/skripsi/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_SPESIFICATION = "spesification";
// Progress Dialog
private static final String PID_KEY = "tvPid";
private static final String NAME_KEY = "tvName";
private static final String PRICE_KEY = "tvPrice";
private static final String DESCRIPTION_KEY = "tvDesc";
private static final String SPESIFICATION_KEY = "tvSpec";
private String mPid=null;
private String mName=null;
private String mPrice=null;
private String mDesc=null;
private String mSpec=null;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ZZZ", "ada di oncreateView");
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_layout_four, container, false);
tvPid = (TextView) rootView.findViewById(R.id.tvPid);
txtName = (TextView) rootView.findViewById(R.id.tvName);
txtPrice = (TextView) rootView.findViewById(R.id.tvPrice);
txtDesc = (TextView) rootView.findViewById(R.id.tvDesc);
txtSpec = (TextView) rootView.findViewById(R.id.tvSpec);
Btngetdata = (Button)rootView.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new FragmentMaintenance();
Bundle data = new Bundle();
data.putString("pid", mPid);
fragment.setArguments(data);
FragmentManager frgManager = getFragmentManager();
Log.d("tag", "PID SCAN: " + data);
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
}
});
Button scanBtn = (Button) rootView.findViewById(R.id.btnScan);
//in some trigger function e.g. button press within your code you should add:
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity(), "ERROR:" + e, Toast.LENGTH_LONG).show();
}
}
});
if (savedInstanceState != null) {
Log.d("ZZZ", "ada di di dlm if saved");
mPid = savedInstanceState.getString(PID_KEY);
mName = savedInstanceState.getString(NAME_KEY);
mPrice = savedInstanceState.getString(PRICE_KEY);
mDesc = savedInstanceState.getString(DESCRIPTION_KEY);
mSpec = savedInstanceState.getString(SPESIFICATION_KEY);
tvPid.setText(mPid);
txtName.setText(mName);
txtPrice.setText(mPrice);
txtDesc.setText(mDesc);
txtSpec.setText(mSpec);
}
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Log.d("ZZZ", "Ada di mainactivity");
if (requestCode == 0) {
TextView pid = (TextView) getActivity().findViewById(R.id.tvPid);
if (resultCode == Activity.RESULT_OK) {
pid.setText(intent.getStringExtra("SCAN_RESULT"));
new GetProductDetails(getActivity()).execute(pid.getText().toString());
} else if (resultCode == Activity.RESULT_CANCELED) {
pid.setText("Scan cancelled.");
}
}
}
class GetProductDetails extends AsyncTask<String, Void, String[]> {
/**
* Before starting background thread Show Progress Dialog
*/
private Context mContext;
public GetProductDetails(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
*/
protected String[] doInBackground(String... string) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", string[0]));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
Log.d("ZZZ", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
String[] result = {Integer.toString(success), product.getString(TAG_NAME), > product.getString(TAG_PRICE),
product.getString(TAG_DESCRIPTION),
product.getString(TAG_SPESIFICATION)};
// // display product data in EditText
// txtName.setText(product.getString(TAG_NAME));
// txtPrice.setText(product.getString(TAG_PRICE));
// txtDesc.setText(product.getString(TAG_DESCRIPTION));
Log.d("ZZZ", result[0]);
return result;
} else {
Log.d("ZZZ", Integer.toString(success));
String[] result = {Integer.toString(success)};
return result;
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String[] results) {
// dismiss the dialog once got all details
pDialog.dismiss();
if (results[0] != null) {
Log.d("ZZZ", "SUCCESS" + results[0]);
if (results[0].matches("1")) {
Log.d("ZZZ", "SUCCESS " + results[0]);
TextView name = (TextView) getActivity().findViewById(R.id.tvName);
name.setText(results[1]);
TextView price = (TextView) getActivity().findViewById(R.id.tvPrice);
price.setText(results[2]);
TextView desc = (TextView) getActivity().findViewById(R.id.tvDesc);
desc.setText(results[3]);
TextView spec = (TextView) getActivity().findViewById(R.id.tvSpec);
spec.setText(results[4]);
} else if (results[0].matches("-1")) {
Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show();
} else{
Log.d("ZZZ", "UNKNOWN ERROR");
}
}
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save state information with a collection of key-value pairs
// 4 lines of code, one for every count variable
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(PID_KEY, tvPid.getText().toString());
savedInstanceState.putString(NAME_KEY, txtName.getText().toString());
savedInstanceState.putString(PRICE_KEY, txtPrice.getText().toString());
savedInstanceState.putString(DESCRIPTION_KEY, txtDesc.getText().toString());
savedInstanceState.putString(SPESIFICATION_KEY, txtSpec.getText().toString());
}
}
This my activity
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
SharedPreferences preferences;
String pref;
List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = this.getSharedPreferences(Config.PREFERENCES, MODE_PRIVATE);
pref = preferences.getString(Config.SESSION,null);
// 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);
// Add Drawer Item to dataList
dataList.add(new DrawerItem("Scanner", R.drawable.ic_action_email));
dataList.add(new DrawerItem("Schedule", R.drawable.ic_action_good));
dataList.add(new DrawerItem("Games", R.drawable.ic_action_gamepad));
dataList.add(new DrawerItem("Logout", R.drawable.ic_action_about));
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(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.main, menu);
return true;
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 0:
fragment = new FragmentScan();
break;
case 1:
fragment = new FragmentSchedule();
break;
case 2:
fragment = new FragmentThree();
args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 3:
logout();
Intent in = new Intent(this, LoginActivity.class);
startActivity(in);
finish();
return;
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) {
SelectItem(position);
}
}
//In the same activity you’ll need the following to retrieve the results:
private void logout(){
//TODO delete cookie from db
SharedPreferences.Editor editor = preferences.edit();
editor.remove(Config.SESSION);
editor.remove(Config.USERNAME);
editor.commit();
}
i hope someone can help me to solving this,
thanks before.
I think it's supposed to be not null, perhaps you just didn't retrieve the value properly.
In your logging code, you used:
Log.d("tag", "PID SCAN: " + data);
but actually you stored the pid using:
data.putString("pid", mPid);
which means, you should use key pid to get the value from the bundle, like:
Log.d("tag", "PID SCAN: " + data.getString("pid"));
EDIT:
If it is a process ID you are trying to get, try to look at android.os.Process.myPid();
If pid is your own pre-defined variable (containing something else),
then you need to pass it when you create the fragment like the following:
fragment = new FragmentScan();
args.putString("pid", YOUR_TV_PID_VALUE);
and from the other side (FragmentScan), you can use getArguments() to get the Bundle, and from there, just use getString("pid").
UPDATE:
After reading your code more, it seems you got the cycle a little bit tangled.
but one quick suggestion is: why don't you try it like the following
data.putString("pid", tvPid.getText());
In you original code, your pid in savedInstanceState supposed to be exist after you perform click on scanBtn, finish/cancel the scanning. But I think your code flow is a little bit tangled.
Read here that onSaveInstanceState is called to retrieve per-instance state from an activity before being killed.
=> That means, before you open another intent (performed by scanBtn), onSaveInstanceState is called and storing empty value of the tvPid. And when the main intent is resumed, it gets that bundle which contains empty string of pid. But it should be "", not null.

Categories