Connection timed out android studio android pie version 9 - android

I created android application grocery app using android studio. when i open some devices it showing connection timed out keep on loading. but some other devices working. please check attached screenshot. please tell me which code i need to check
Thank you
Note : Especially Android 9 Pie Mobile devices getting this error
Mainactivity.java
package woodland.bharati;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.webkit.WebView;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.telephony.PhoneNumberUtils;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SubMenu;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import Config.BaseURL;
import Config.SharedPref;
import Fonts.CustomTypefaceSpan;
import Fragment.About_us_fragment;
import Fragment.Contact_Us_fragment;
import Fragment.Empty_cart_fragment;
import Fragment.Home_fragment;
import Fragment.Cart_fragment;
import Fragment.Reward_fragment;
import Fragment.Edit_profile_fragment;
import Fragment.Shop_Now_fragment;
import Fragment.Terms_and_Condition_fragment;
import Fragment.Wallet_fragment;
import woodland.bharati.networkconnectivity.NetworkError;
import util.ConnectivityReceiver;
import util.DatabaseHandler;
import util.Session_management;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, ConnectivityReceiver.ConnectivityReceiverListener {
private static final String TAG = MainActivity.class.getSimpleName();
private BroadcastReceiver mRegistrationBroadcastReceiver;
private TextView totalBudgetCount, totalBudgetCount2, totalBudgetCount3, tv_name, powerd_text;
private ImageView iv_profile;
private DatabaseHandler dbcart;
private Session_management sessionManagement;
private Menu nav_menu;
ImageView imageView;
TextView mTitle;
LinearLayout viewpa;
Toolbar toolbar;
String language="";
LinearLayout My_Order, My_Reward, My_Walllet, My_Cart;
int padding = 0;
private TextView txtRegId;
NavigationView navigationView;
LinearLayout Change_Store;
String Store_Count;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void attachBaseContext(Context newBase) {
newBase = LocaleHelper.onAttach(newBase);
super.attachBaseContext(newBase);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("MYTAG", "This is your Firebase token" + token);
sharedPreferences= getSharedPreferences("lan", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString("language", "english");
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("MainActivity") && value.equals("True")) {
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
subscribeToPushService();
}
Store_Count = SharedPref.getString(MainActivity.this, BaseURL.KEY_STORE_COUNT);
//
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setPadding(padding, toolbar.getPaddingTop(), padding, toolbar.getPaddingBottom());
setSupportActionBar(toolbar);
for (int i = 0; i < toolbar.getChildCount(); i++) {
View view = toolbar.getChildAt(i);
if (view instanceof TextView) {
TextView textView = (TextView) view;
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "Font/Bold.ttf");
textView.setTypeface(myCustomFont);
}
}
getSupportActionBar().setTitle(getResources().getString(R.string.name));
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
dbcart = new DatabaseHandler(this);
checkConnection();
sessionManagement = new Session_management(MainActivity.this);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu m = navigationView.getMenu();
for (int i = 0; i < m.size(); i++) {
MenuItem mi = m.getItem(i);
//for aapplying a font to subMenu ...
SubMenu subMenu = mi.getSubMenu();
if (subMenu != null && subMenu.size() > 0) {
for (int j = 0; j < subMenu.size(); j++) {
MenuItem subMenuItem = subMenu.getItem(j);
applyFontToMenuItem(subMenuItem);
}
}
//the method we have create in activity
applyFontToMenuItem(mi);
}
View headerView = navigationView.getHeaderView(0);
navigationView.getBackground().setColorFilter(0x80000000, PorterDuff.Mode.MULTIPLY);
navigationView.setNavigationItemSelectedListener(this);
nav_menu = navigationView.getMenu();
View header = ((NavigationView) findViewById(R.id.nav_view)).getHeaderView(0);
Change_Store = (LinearLayout) header.findViewById(R.id.change_store_btn);
viewpa=(LinearLayout) header.findViewById(R.id.viewpa);
if (sessionManagement.isLoggedIn()) {
viewpa.setVisibility(View.VISIBLE);
}
if (Store_Count.equals("1")) {
Change_Store.setVisibility(View.INVISIBLE);
} else if (Store_Count.equals("2")) {
Change_Store.setVisibility(View.VISIBLE);
Change_Store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SelectStore.class);
startActivity(intent);
overridePendingTransition(0, 0);
}
});
}
iv_profile = (ImageView) header.findViewById(R.id.iv_header_img);
tv_name = (TextView) header.findViewById(R.id.tv_header_name);
My_Order = (LinearLayout) header.findViewById(R.id.my_orders);
My_Reward = (LinearLayout) header.findViewById(R.id.my_reward);
My_Walllet = (LinearLayout) header.findViewById(R.id.my_wallet);
My_Cart = (LinearLayout) header.findViewById(R.id.my_cart);
My_Order.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, My_Order_activity.class);
startActivity(intent);
}
});
My_Reward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fm = new Reward_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
});
My_Walllet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fm = new Wallet_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
});
My_Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (dbcart.getCartCount() > 0) {
Fragment fm = new Cart_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
} else {
Toast.makeText(MainActivity.this, "No Item in Cart", Toast.LENGTH_SHORT).show();
}
}
});
iv_profile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
if (sessionManagement.isLoggedIn()) {
Fragment fm = new Edit_profile_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
} else {
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
overridePendingTransition(0, 0);
}
}
});
updateHeader();
sideMenu();
if (savedInstanceState == null) {
Fragment fm = new Home_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.contentPanel, fm, "Home_fragment")
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
getFragmentManager().
addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
try {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
Fragment fr = getFragmentManager().findFragmentById(R.id.contentPanel);
final String fm_name = fr.getClass().getSimpleName();
Log.e("backstack: ", ": " + fm_name);
if (fm_name.contentEquals("Home_fragment")) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
toggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
} else if (fm_name.contentEquals("My_order_fragment") ||
fm_name.contentEquals("Thanks_fragment")) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.syncState();
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fm = new Home_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
});
} else {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.syncState();
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
// if (sessionManagement.getUserDetails().
// get(BaseURL.KEY_ID) != null && !sessionManagement.getUserDetails().
// get(BaseURL.KEY_ID).equalsIgnoreCase())
//
// {
// MyFirebaseRegister fireReg = new MyFirebaseRegister(this);
// fireReg.RegisterUser(sessionManagement.getUserDetails().get(BaseURL.KEY_ID));
// }
}
public void updateHeader() {
if (sessionManagement.isLoggedIn()) {
String getname = sessionManagement.getUserDetails().get(BaseURL.KEY_NAME);
String getimage = sessionManagement.getUserDetails().get(BaseURL.KEY_IMAGE);
String getemail = sessionManagement.getUserDetails().get(BaseURL.KEY_EMAIL);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");
if (!previouslyEncodedImage.equalsIgnoreCase("")) {
byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
iv_profile.setImageBitmap(bitmap);
}
// Glide.with(this)
// .load(BaseURL.IMG_PROFILE_URL + getimage)
// .placeholder(R.drawable.icon)
// .crossFade()
// .into(iv_profile);
tv_name.setText(getname);
}
}
private void applyFontToMenuItem(MenuItem mi) {
Typeface font = Typeface.createFromAsset(getAssets(), "Font/Bold.ttf");
SpannableString mNewTitle = new SpannableString(mi.getTitle());
mNewTitle.setSpan(new CustomTypefaceSpan("", font), 0, mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mi.setTitle(mNewTitle);
}
public void sideMenu() {
if (sessionManagement.isLoggedIn()) {
// tv_number.setVisibility(View.VISIBLE);
nav_menu.findItem(R.id.nav_logout).setVisible(true);
nav_menu.findItem(R.id.nav_powerd).setVisible(true);
// nav_menu.findItem(R.id.nav_user).setVisible(true);
} else {
//tv_number.setVisibility(View.GONE);
tv_name.setText(getResources().getString(R.string.btn_login));
tv_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
}
});
nav_menu.findItem(R.id.nav_logout).setVisible(false);
// nav_menu.findItem(R.id.nav_user).setVisible(false);
}
}
public void setFinish() {
finish();
}
public void setCartCounter(String totalitem) {
try {
totalBudgetCount.setText(totalitem);
}catch (Exception e){
}
}
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_cart);
item.setVisible(true);
View count = item.getActionView();
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
menu.performIdentifierAction(item.getItemId(), 0);
}
});
totalBudgetCount = (TextView) count.findViewById(R.id.actionbar_notifcation_textview);
totalBudgetCount.setText("" + dbcart.getCartCount());
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.action_language){
openLanguageDialog();
}
if (id == R.id.action_cart) {
if (dbcart.getCartCount() > 0) {
Fragment fm = new Cart_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
else {
Fragment fm = new Empty_cart_fragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void openLanguageDialog() {
View v = LayoutInflater.from(this).inflate(R.layout.dialog_language,null,false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(v);
TextView lEnglish = v.findViewById(R.id.l_english);
TextView lSpanish = v.findViewById(R.id.l_arabic);
final AlertDialog dialog = builder.create();
lEnglish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LocaleHelper.setLocale(getApplication(),"en");
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
editor.putString("language", "english");
editor.apply();
recreate();
dialog.dismiss();
}
});
lSpanish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LocaleHelper.setLocale(getApplication(),"ar");
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("language", "spanish");
editor.apply();
recreate();
dialog.dismiss();
}
});
dialog.show();
}
#SuppressLint("ResourceType")
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fm = null;
Bundle args = new Bundle();
if (id == R.id.nav_shop_now) {
fm = new Shop_Now_fragment();
} else if (id == R.id.nav_my_profile) {
fm = new Edit_profile_fragment();
} else if (id == R.id.nav_support) {
String smsNumber = "919886143091";
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.Conversation"));
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber)+"#s.whatsapp.net");//phone number without "+" prefix
startActivity(sendIntent);
} else if (id == R.id.nav_aboutus) {
toolbar.setTitle("About");
fm = new About_us_fragment();
args.putString("url", BaseURL.GET_ABOUT_URL);
args.putString("title", getResources().getString(R.string.nav_about));
fm.setArguments(args);
}
else if (id == R.id.nav_youtube) {
toolbar.setTitle("Videos");
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://woodlandbharati.com/videos/"));
startActivity(myWebLink);
}
else if (id == R.id.nav_enquiry) {
toolbar.setTitle("Enquiry Us");
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://woodlandbharati.com/enquiry/"));
startActivity(myWebLink);
}
else if (id == R.id.nav_health) {
toolbar.setTitle("Health Tips");
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://woodlandbharati.com/news/"));
startActivity(myWebLink);
} else if (id == R.id.nav_policy) {
fm = new Terms_and_Condition_fragment();
args.putString("url", BaseURL.GET_TERMS_URL);
args.putString("title", getResources().getString(R.string.nav_terms));
fm.setArguments(args);
} else if (id == R.id.nav_review) {
//reviewOnApp();
} else if (id == R.id.nav_contact) {
fm = new Contact_Us_fragment();
args.putString("url", BaseURL.GET_SUPPORT_URL);
args.putString("title", getResources().getString(R.string.nav_terms));
fm.setArguments(args);
} else if (id == R.id.nav_share) {
shareApp();
} else if (id == R.id.nav_logout) {
sessionManagement.logoutSession();
finish();
} else if (id == R.id.nav_powerd) {
// stripUnderlines(textView);
String url = "http://bhavyabharath.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
finish();
}
if (fm != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentPanel, fm)
.addToBackStack(null).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void startActivityForResult(Intent intent, int requestCode) {
try {
super.startActivityForResult(intent, requestCode);
} catch (Exception ignored) {
}
}

Related

Unable to instantiate fragment could not find Fragment constructor android

I am having this following error. I added constructor on DailyVerseFragment. But still it doesn't work.
I am having this issues for more than one week.
Fatal Exception: java.lang.RuntimeException
Unable to start activity ComponentInfo{com.donghyouny.biblecard/com.donghyouny.biblecard.MainActivity}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.donghyouny.biblecard.DailyVerseFragment: could not find Fragment constructor
package com.donghyouny.biblecard;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FragmentCallback {
Toolbar toolbar;
CardFragment cardFargment;
DailyVerseFragment dailyVerseFragment;
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dailyVerseFragment = new DailyVerseFragment();
// mAuth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
contextOfApplication = getApplicationContext();
toolbar.setTitle("Draw Verse Card");
DrawerLayout drawer = 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();
drawer.openDrawer(GravityCompat.START);
cardFargment = new CardFragment();
Calendar mCalendar = Calendar.getInstance();
/*mCalendar.set(Calendar.HOUR_OF_DAY, 01);
mCalendar.set(Calendar.MINUTE, 01);
mCalendar.set(Calendar.SECOND, 0);*/
mCalendar.set(Calendar.HOUR_OF_DAY, 0);
if(mCalendar.before(Calendar.getInstance())){ // if it's in the past, increment
mCalendar.add(Calendar.DATE, 1);
}
// PackageManager pm = this.getPackageManager();
// ComponentName receiver = new ComponentName(this, DeviceBootReceiver.class);
Intent alarmIntent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
}
}
// 부팅 후 실행되는 리시버 사용가능하게 설정
/* pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);*/
// setAlarm(mCalendar);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction().add(R.id.container, cardFargment).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
// super.onBackPressed();
AlertDialog.Builder alBuilder = new AlertDialog.Builder(this, R.style.AlertDialogCustom);
alBuilder.setMessage("Do you want to exit?");
// "예" 버튼을 누르면 실행되는 리스너
alBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish(); // 현재 액티비티를 종료한다. (MainActivity에서 작동하기 때문에 애플리케이션을 종료한다.)
}
});
// "아니오" 버튼을 누르면 실행되는 리스너
alBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
return; // 아무런 작업도 하지 않고 돌아간다
}
});
alBuilder.setTitle("Program Exit");
alBuilder.show(); // AlertDialog.Bulider로 만든 AlertDialog를 보여준다.
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Bundle bundle = getBundle(menuItem);
// onFragmentSelected(0, bundle);
int id = menuItem.getItemId();
if(id == R.id.menu1){
onFragmentSelected(0, bundle);
}else if(id == R.id.menu2){
onFragmentSelected(1, bundle);
}else if(id == R.id.menu3) {
onFragmentSelected(2, bundle);
}else if(id == R.id.menu4) {
onFragmentSelected(3, bundle);
}else if(id == R.id.menu5) {
onFragmentSelected(4, bundle);
}else if(id == R.id.menu6) {
onFragmentSelected(5, bundle);
}else if(id == R.id.menu7) {
onFragmentSelected(6, bundle);
}else if(id == R.id.menu8) {
onFragmentSelected(7, bundle);
}else if(id == R.id.menu9) {
onFragmentSelected(8, bundle);
}else if(id == R.id.menu10) {
onFragmentSelected(9, bundle);
}else if(id == R.id.menu11) {
onFragmentSelected(10, bundle);
}else if(id == R.id.menu12) {
onFragmentSelected(11, bundle);
}else if(id == R.id.menu13) {
onFragmentSelected(12, bundle);
}else if(id == R.id.menu14) {
onFragmentSelected(13, bundle);
}else if(id == R.id.menu15) {
onFragmentSelected(14, bundle);
}else if(id == R.id.menu16) {
onFragmentSelected(15, bundle);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private Bundle getBundle(#NonNull MenuItem menuItem) {
Bundle bundle = new Bundle();
bundle.putString("value", menuItem.getTitle().toString());
return bundle;
}
#Override
public void onFragmentSelected(int position, Bundle bundle) {
String value = bundle.getString("value");
Fragment curFragment = null;
if(position == 0){
curFragment = new CardFragment();
toolbar.setTitle(value);
}else if(position==1){
curFragment = new DailyVerseFragment(toolbar);
//toolbar.setTitle(value);
}else if(position>=2){
curFragment = new Fragment1(value);
toolbar.setTitle(value);
}
// toolbar.setTitle(value);
getSupportFragmentManager().beginTransaction().replace(R.id.container, curFragment).commit();
}
// a static variable to get a reference of our application context
public static Context contextOfApplication;
public static Context getContextOfApplication()
{
return contextOfApplication;
}
}
package com.donghyouny.biblecard;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.ads.AdView;
public class DailyVerseFragment extends Fragment {
private ImageView imageView;
private TextView bibleType;
private TextView verse;
private TextView content;
public Bible bible;
private SharedPreferences checkDialog;
private SharedPreferences saveDialog;
private SharedPreferences shareDialog;
private ImageView like;
private ImageView check;
private ImageView save;
private TextView likecount, savecount, link;
public static final int REQUEST_CODE = 101;
private String key;
private Toolbar toolbar;
private boolean flag;
private AdView mAdView;
private String categoryName;
private DrawableImage DrawbleImage;
private AlertReceiver AlertReceivr;
public DailyVerseFragment(){}
public DailyVerseFragment(Toolbar value) {
this.toolbar = value;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Activity a = getActivity();
if (a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_daily_verse, container, false);
// toolbar = rootView.findViewById(R.id.toolbar);
// ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
verse = rootView.findViewById(R.id.verse);
content = rootView.findViewById(R.id.content);
imageView = rootView.findViewById(R.id.imageView);
save = rootView.findViewById(R.id.save);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("bibleNum", Context.MODE_PRIVATE);
final int bibleNum = sharedPreferences.getInt("bibleNum", 1);
Log.d("DailyVerseNum", String.valueOf(bibleNum));
MyDatabaseHelper db = new MyDatabaseHelper(getActivity());
Cursor cursor = db.readDailyCardData(bibleNum);
cursor.moveToFirst();
bible = new Bible();
Log.d("cursorid", String.valueOf(cursor.getInt(0)));
bible.setId(cursor.getInt(0));
bible.setVerse(cursor.getString(1));
bible.setContent(cursor.getString(2));
bible.setNum(cursor.getInt(3));
bible.setCnum(cursor.getInt(4));
bible.setVnum(cursor.getInt(5));
bible.setImage(cursor.getBlob(6));
bible.setTimestamp(cursor.getString(7));
Log.d("content", bible.getContent());
Log.d("bible.getCnum", String.valueOf(bible.getCnum()));
Cursor cursor1 = db.getCategoryName(bible.getCnum());
cursor1.moveToFirst();
categoryName = cursor1.getString(0);
display();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveDialog = getActivity().getSharedPreferences("saveDialog", Context.MODE_PRIVATE);
boolean isFirst = saveDialog.getBoolean("first", true);
if(isFirst){
saveDialogPopup();
}else{
onSave(bible);
}
}
});
setHasOptionsMenu(true);
return rootView;
}
private void checkMethod(Bible bible) {
MyDatabaseHelper db = new MyDatabaseHelper(getContext());
db.updateData(bible);
}
private void checkDialogPopup() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Check Button");
builder.setMessage("If you want to specify which verse is already read, this button will move the one you read to the lowest of the previously show list. But once you click this button, you cannot revert it. Do you want to proceed?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(),"You select 'Yes'.",Toast.LENGTH_SHORT).show();
checkMethod(bible);
}
});
builder.setNegativeButton("Don't show this message, again.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = checkDialog.edit();
editor.putBoolean("firstTime", false);
editor.commit();
Toast.makeText(getContext(),"You select 'Don't show this message, again.'",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
private void onSave(Bible bible) {
Log.d("getId", String.valueOf(bible.getId()));
MyDatabaseHelper db1 = new MyDatabaseHelper(getContext());
Cursor cursor = db1.getSaveDataById(bible.getId());
flag=true;
cursor.moveToFirst();
Log.d("countcursor", String.valueOf(cursor.getCount()));
if (cursor != null && cursor.moveToFirst()) {
Toast.makeText(getContext(),"It is already saved.",Toast.LENGTH_SHORT).show();
flag = false;
}else if(flag){
db1.insertToSave(bible);
cursor.close();
}
}
private void saveDialogPopup() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Save Button");
builder.setMessage("If you select this button, the verse you read will be saved and if you want to see that verse that you saved, you should go to verse list and on the top right, you will see yellow folder icon. If you click that icon. It will take you to 'favorite bible verse'. If you want to save?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onSave(bible);
}
});
builder.setNegativeButton("Don't show this message, again.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = saveDialog.edit();
editor.putBoolean("first", false);
editor.commit();
Toast.makeText(getContext(),"You select not \'Don\'t show this message, again\'.",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
double getScreenInches() {
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
double wi = (double) width / (double) dm.xdpi;
double hi = (double) height / (double) dm.ydpi;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void display(){
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
params.width = metrics.widthPixels;
params.height = (int)(metrics.heightPixels/2.8);
Log.d("width", String.valueOf(params.width));
Log.d("height", String.valueOf(params.height));
imageView.setLayoutParams(params);
Glide.with(getContext()).load(bible.getImage()).apply(new RequestOptions().centerCrop()).into(imageView);
//imageView.setImageResource(R.drawable.church);
verse.setText(bible.getVerse().toString());
content.setText(bible.getContent().toString());
Log.d("content", bible.getContent().toString());
int inch = (int)( getScreenInches()+0.5 );
Log.d("inch", String.valueOf(3*inch));
//content.setTextSize(3*inch);
toolbar.setTitle(categoryName);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.share_actions, menu);
}
public void shareDialogPopup(){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Share Button");
builder.setMessage("You can share bible verse that you read by clicking this button. Do you want to proceed?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(),"You select \'Yes\'.",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, bible.getVerse()+"\n"+bible.getContent()+"\n"+"https://play.google.com/store/apps/details?id=the.holy.catholic.bible");
Intent chooser = Intent.createChooser(intent, "Share");
startActivity(chooser);
}
});
builder.setNegativeButton("Don\'t show this message, again",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = shareDialog.edit();
editor.putBoolean("printMsg", false);
editor.commit();
Toast.makeText(getContext(),"You select not \'Don\'t show this message, again\'.",Toast.LENGTH_SHORT).show();
}
});
/*AlertDialog alert = builder.create();
alert.show();
alert.getWindow().getAttributes();
TextView textView = (TextView) alert.findViewById(android.R.id.message);
textView.setTextSize(15);
Button btn1 = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
Button btn2 = alert.getButton(DialogInterface.BUTTON_POSITIVE);
btn1.setTextSize(12);
btn2.setTextSize(12);*/
builder.show();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
shareDialog = getActivity().getSharedPreferences("shareDialog", Context.MODE_PRIVATE);
boolean printMsg = shareDialog.getBoolean("printMsg", true);
if(printMsg){
shareDialogPopup();
}else{
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, bible.getVerse()+"\n"+bible.getContent()+"\n"+"https://play.google.com/store/apps/details?id=the.holy.catholic.bible");
Intent chooser = Intent.createChooser(intent, "Share");
startActivity(chooser);
break;
}
}
return super.onOptionsItemSelected(item);
}
}
The Problem that caused your crash is that you want to instantiate your fragment with a constructor with parameter. but you in android you should create fragment with a non parameter constructor.
so how to solve this problem to pass parameters in to your fragment:
in DailyVerseFragment :
public static DailyVerseFragment newInstance(String myString) {
DailyVerseFragment myFragment = new DailyVerseFragment();
Bundle args = new Bundle();
args.putString("key", myString);
myFragment.setArguments(args);
return myFragment;
}
and in onCreate() function of fragment get it like :
getArguments().getString("key");
and if you want to send Objects you can use putParcable/getParcable.
but my suggestion for you to get toolbar in your fragment is to access it in your fragment like this:
((AppCompatActivity) getActivity()).getSupportActionBar()

java.lang.NullPointerException at firebase.auth.FirebaseUser.getEmail() and says currentUser() returns null

"In my MainActivity , I perform fragment transaction to the profile fragment in my app . In Profile I use FirebaseAuth to get Current User Email Address which then says getEmail() may produce Null Pointer Exception.. But in MainActivity Itself there is a AuthStateListener which should ask the user to sign in if the user is not signed in.. But why it is not happening .. "
"I have read other answers which say NullPointerException on getUid on FirebaseUser is returning Null Pointer exception and those answers didn't help me..."
"
Below I'm Posting my mainActivity and then Profile Fragment
I MARKED THE LINES WITH ARROW'S <-
"
package com.github.chillmonk2.mycollege;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private final static int RC_SIGN_IN = 2;
private final static String TAG = MainActivity.class.getSimpleName();
public static Context contextMain;
FirebaseAuth mFirebaseAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
final Fragment newsFragment = new NewsFragment();
final Fragment eventsFragment = new EventsFragment();
final Fragment peopleFragment = new PeopleFragment();
final Fragment profileFragment = new ProfileFragment();
final FragmentManager fm = getFragmentManager();
Fragment active = newsFragment;
int code ;
public static String isAdmin = "FALSE";
#Override
protected void onStart() {
super.onStart();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
// MainFragment fragment = new MainFragment();
//
// FragmentTransaction transaction = getFragmentManager().beginTransaction();
// transaction.replace(R.id.container, fragment, "MainFragment");
// transaction.commit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
contextMain = getApplicationContext();
//I added this if statement to keep the selected fragment when rotating the device
/*if (savedInstanceState == null) {
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
new NewsFragment()).commit();
}
*/
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
} else {
// User is signed out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build()
))
.build(),
RC_SIGN_IN);
}
}
};
fm.beginTransaction().add(R.id.fragment_container, profileFragment, "3").hide(profileFragment).commit(); <--- HERE IS THE TRANSACTION
fm.beginTransaction().add(R.id.fragment_container, peopleFragment, "2").hide(peopleFragment).commit();
fm.beginTransaction().add(R.id.fragment_container,eventsFragment, "1").hide(eventsFragment).commit();
fm.beginTransaction().add(R.id.fragment_container,newsFragment, "0").commit();
getSupportActionBar().setTitle("News");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
code = requestCode;
if(requestCode==RC_SIGN_IN)
{
if(resultCode==RESULT_OK)
{
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
}
else if (resultCode ==RESULT_CANCELED)
{
Toast.makeText(this, "Sign in Failed", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
if(mAuthStateListener==null)
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
Log.d("MainActivity.class","OnResume Method");
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
Log.d("MainActivity.class",mAuthStateListener+"onPause Method Inside");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.app_menu:
AuthUI.getInstance().signOut(this);
return true;
case R.id.app_menu_settings:
Intent intent = new Intent(MainActivity.contextMain,SettingsActivity.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_news:
fm.beginTransaction().hide(active).show(newsFragment).commit();
getSupportActionBar().setTitle("News");
active = newsFragment;
return true;
case R.id.nav_events:
fm.beginTransaction().hide(active).show(eventsFragment).commit();
active = eventsFragment;
getSupportActionBar().setTitle("Events");
return true;
case R.id.nav_profile:
fm.beginTransaction().hide(active).show(profileFragment).commit();
active = profileFragment;
getSupportActionBar().setTitle("Profile");
return true;
case R.id.nav_Meetups:
fm.beginTransaction().hide(active).show(peopleFragment).commit();
active = peopleFragment;
getSupportActionBar().setTitle("People");
return true;
}
return false;
}
};
}
ProfileFragment
package com.github.chillmonk2.mycollege;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
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 com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import org.w3c.dom.Text;
public class ProfileFragment extends Fragment {
private FirebaseUser mUser;
private TextView mUserName;
private TextView mRegdNo;
private TextView mEmailText;
private TextView mBioText;
private TextView mSkillsText;
private TextView mAchievementsText;
private TextView mAcademicsText;
private TextView mHobbiesText;
private ImageView mMentorImage;
String email;
DbHelper mDb;
public ProfileFragment()
{
//empty Constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Profile");
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
mDb = new DbHelper(MainActivity.contextMain);
mUser = FirebaseAuth.getInstance().getCurrentUser();
if(mUser == null)
email = mUser.getEmail();<------HERE IS THE EXCEPTION
email = new String();
// email = "sk.mannam#gmail.com";
//int res1 = mDb.insertUser(new Student(),email);
Log.e("TAG","Current User Email is "+ email);
ImageView editProfile = rootView.findViewById(R.id.edit_profile);
editProfile.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),EditProfile.class);
startActivity(intent);
}
});
mUserName = rootView.findViewById(R.id.userName);
mRegdNo = rootView.findViewById(R.id.regdNoBelowName);
mMentorImage = rootView.findViewById(R.id.mentorImage);
mEmailText = rootView.findViewById(R.id.emailText);
mBioText = rootView.findViewById(R.id.bioText);
mSkillsText = rootView.findViewById(R.id.skillsText);
mAchievementsText = rootView.findViewById(R.id.achievementsText);
mAcademicsText = rootView.findViewById(R.id.academicsText);
mHobbiesText = rootView.findViewById(R.id.hobbiesText);
Student student = new Student();
// Toast.makeText(getActivity(),"Success",Toast.LENGTH_SHORT).show();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.contextMain);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code
int res = mDb.insertUser(student,FirebaseAuth.getInstance().getCurrentUser().getEmail());
if(res!=-1)
{
Log.e("TAG",res+" is the result id in shared Preferences");
}
else
{
Log.e("TAG",res+" is the result id in shared Preferences");
}
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
UpdateUi();
return rootView;
}
void UpdateUi()
{
DbHelper mDbHelper = new DbHelper(getActivity());
Log.e("TAG","Calling getStudent");
Student student1 = mDb.getStudent(email);
Log.e("TAG","Returned from Student");
mUserName.setText(student1.mSurname+" "+student1.mFirstName+" "+student1.mLastName);
mRegdNo.setText(student1.mRegdNo);
if(student1.mMentor.toLowerCase().equals("yes"))
mMentorImage.setVisibility(ImageView.VISIBLE);
else
mMentorImage.setVisibility(ImageView.INVISIBLE);
mEmailText.setText(student1.getmEmail());
mBioText.setText(student1.getmBio());
mSkillsText.setText(student1.getmSkills());
mAchievementsText.setText(student1.getmAchievements());
mAcademicsText.setText(student1.getmAcademicInterests());
mHobbiesText.setText(student1.getmActivites());
}
#Override
public void onResume() {
super.onResume();
UpdateUi();
}
}
If the FirebaseAuth.getCurrentUser is producing nullPointerException then why AuthStateListener is not asking for user to login.. Please help ...Thanks In Advance..

Get Acknowledge in Fragment from MainActivity, when my menu filter (sorting in MainActivity) is clicked

I have menu item in MainActivity it is filter(sort), I want that if user click on filter menu like A-z or z-a, in my MainActivity's onclick it is clicked but i want to get acknowledge in fragments as well
[nhewuhfduehiuhuewhucuewcueucueuncneincineincinencneincineinciniencineicnnecnnecneicniencnnecncncncnicnincincncnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnncncicieicieicicnicnncncicn]
code:
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Adapter.ViewPagerAdapter;
import com.tekitsolutions.remindme.Fragment.HomeFragment;
import com.tekitsolutions.remindme.Fragment.OfficeFragment;
import com.tekitsolutions.remindme.Fragment.OtherFragment;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Profile;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RemindMe;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Utils.CommonUtils.CREATE_PASSCODE_ACTIVITY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GET_PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IMAGE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PHONE_NUMBER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_SEARCH;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.USERNAME;
public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, AdapterInterface, HamburgerMenuInterface, SearchListener, MenuItemListener {
private static final String TAG = MainActivity.class.getSimpleName();
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.recycler_view)
RecyclerView listView;
private String phoneNum = null, getImage = null, getUsername = null;
private int first = 0, position = 0;
private ActionBar actionBar;
private DatabaseAdapter dbAdapter;
private ReminderListAdapter listAdapter;
private List<Reminder> listItems = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private MenuItemListener searchListener;
private DrawerLayout drawer;
private SharedPreferences profilePreference;
private TextView navUsername, navMobile;
private ImageView navImage;
private View headerView;
private NavigationView navigationView;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
CREATE_PASSCODE_ACTIVITY = 0;
setThemeAndLoadLocale(MainActivity.this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
ButterKnife.bind(this);
setToolbar(toolbar, getString(R.string.app_name));
profilePreference = getSharedPreferences(PROFILE, MODE_PRIVATE);
getDataPhoneNumber();
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
navUsername = headerView.findViewById(R.id.profile_name);
navMobile = headerView.findViewById(R.id.mobile_number);
navImage = headerView.findViewById(R.id.profile_image);
if (!phoneNum.isEmpty()) {
first = 1;
getProfileData();
}
Menu menu = navigationView.getMenu();
MenuItem tools = menu.findItem(R.id.nav_general_setting);
SpannableString s = new SpannableString(tools.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s.length(), 0);
tools.setTitle(s);
Menu menu2 = navigationView.getMenu();
MenuItem tools2 = menu2.findItem(R.id.nav_communicate);
SpannableString s2 = new SpannableString(tools2.getTitle());
s2.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s2.length(), 0);
tools2.setTitle(s2);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new HomeFragment(), getResources().getString(R.string.fragment_home));
adapter.AddFragment(new OfficeFragment(), getResources().getString(R.string.fragment_office));
adapter.AddFragment(new OtherFragment(), getResources().getString(R.string.fragment_other));
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
listAdapter = new ReminderListAdapter(this, listItems, MainActivity.this, this, this);
listView.setHasFixedSize(true);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddReminderActivity.class));
}
});
dbAdapter = new DatabaseAdapter(this);
HomeFragment homeFragment = new HomeFragment();
homeFragment.setListener(this);
}
#Override
public void onClickFavoriteById(int isFavorite, long id) {
}
private void setData() {
if (getUsername != null && !getUsername.isEmpty()) {
navUsername.setText(getUsername.trim());
}
if (phoneNum != null && !phoneNum.isEmpty()) {
navMobile.setVisibility(View.VISIBLE);
navMobile.setText(phoneNum);
}
if (getImage != null && !getImage.isEmpty()) {
Bitmap bitmap = convertBase64ToBitMap(getImage);
navImage.setImageBitmap(bitmap);
} else {
navImage.setImageResource(R.drawable.user_image);
}
}
private void storeInSharedPreference() {
editor = getSharedPreferences(PROFILE, MODE_PRIVATE).edit();
editor.putString(USERNAME, getUsername);
editor.putString(IMAGE, getImage);
editor.apply();
}
private void getProfileData() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<List<Profile>> profileDetails = apiInterface.getProfileDetails(phoneNum);
profileDetails.enqueue(new Callback<List<Profile>>() {
#Override
public void onResponse(Call<List<Profile>> call, Response<List<Profile>> response) {
int statusCode = response.code();
if (statusCode == 200) {
List<Profile> responseList = response.body();
Profile profile = responseList.get(0);
showLog("username: " + profile.getProfileName());
getUsername = profile.getProfileName();
if (getUsername == null) {
showLog("Null");
} else {
showLog("Not null");
}
getImage = profile.getImage();
phoneNum = profile.getProfileNo();
setData();
storeInSharedPreference();
}
}
#Override
public void onFailure(Call<List<Profile>> call, Throwable t) {
showLog("Failed: " + t.getMessage());
}
});
}
private void getDataFromSharedPref() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
getUsername = profilePreference.getString(USERNAME, "");
getImage = profilePreference.getString(IMAGE, "");
}
private void getDataPhoneNumber() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Intent intent = null;
switch (item.getItemId()) {
case R.id.nav_profile:
intent = new Intent(this, ProfileActivity.class);
intent.putExtra(GET_PROFILE, true);
intent.putExtra(IMAGE, getImage);
intent.putExtra(USERNAME, getUsername);
startActivity(intent);
break;
case R.id.nav_favorite:
intent = new Intent(MainActivity.this, AddFavoriteReminder.class);
startActivity(intent);
break;
case R.id.nav_setting:
intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
break;
case R.id.nav_passcode:
intent = new Intent(this, PasscodeActivity.class);
startActivity(intent);
break;
case R.id.nav_share:
String link = "https://drive.google.com/drive/folders/1sDS_hGb5s5SjyDIK3me3oY8cS1Oo1I4F?usp=sharing";
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
SpannableString ss = new SpannableString("Android is a Software stack");
String shareBodyText = link;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));
return true;
case R.id.nav_help:
intent = new Intent(MainActivity.this, HelpActivity.class);
startActivity(intent);
break;
case R.id.nav_feedback:
intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("message/rfc822");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"jimmytrivedi#outlook.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Remind Me Feedback");
intent.putExtra(Intent.EXTRA_TEXT, "Developer Team,");
try {
startActivity(Intent.createChooser(intent, "Send Email"));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public void onClickReminderList(int position) {
}
private Bitmap convertBase64ToBitMap(String profileImage) {
try {
byte[] encodeByte = Base64.decode(profileImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch (Exception e) {
showLog("" + e.getMessage());
return null;
}
}
#Override
protected void onResume() {
super.onResume();
CREATE_PASSCODE_ACTIVITY = 0;
if (RemindMe.isChanged()) {
RemindMe.setChanged(false);
recreate();
}
getDataFromSharedPref();
setData();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.search:
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
startActivityForResult(intent, PICK_SEARCH);
break;
case R.id.filter:
break;
case R.id.ascending:
position = 1;
break;
case R.id.descending:
position = 2;
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fragment_search, menu);
getMenuInflater().inflate(R.menu.menu_filter, menu);
return true;
}
#Override
public void onClickHamburger(long id) {
}
#Override
public void onClickListItem(int position) {
}
#Override
public void setToolbar(Toolbar toolBar, String title) {
super.setToolbar(toolBar, title);
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onSelectedProviderSearchItem(General general) {
}
#Override
public void onSelectedParticularPaymentSearchItem(ParticularPayment particularPayment) {
}
#Override
public void onSelectedReminderSearchItem(Reminder reminder) {
}
#Override
public void unused(int position) {
}
#Override
public void onFilterItem(int position) {
}
}
Interface
MenuItemListener
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
public interface MenuItemListener {
void onFilterItem(int position);
}
HomeFragment:
package com.tekitsolutions.remindme.Fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tekitsolutions.remindme.Activity.AddReminderActivity;
import com.tekitsolutions.remindme.Activity.MainActivity;
import com.tekitsolutions.remindme.Activity.ReminderDetailActivity;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Receiver.AlarmReceiver;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RecyclerViewClickListener;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_FAVORITE;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_TYPE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.HOME;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IS_EDIT;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_HOME;
public class HomeFragment extends Fragment implements AdapterInterface, HamburgerMenuInterface, Callback<String>, SearchListener, MenuItemListener {
private static final String TAG = HomeFragment.class.getSimpleName();
public MainActivity activity;
public Context context;
View view;
private DatabaseAdapter dbAdapter;
private List<Reminder> listItems = new ArrayList<>();
private ReminderListAdapter listAdapter;
private MenuItemListener menuItemListener;
private RecyclerView listView;
private TextView tvNoData;
private AdapterInterface listener;
private HamburgerMenuInterface menuInterface;
private AlertDialog.Builder builder;
private Reminder reminder;
private long reminderId = 0;
private int getFavorite = 0;
public HomeFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = view.findViewById(R.id.recycler_view);
tvNoData = view.findViewById(R.id.tv_no_data);
dbAdapter = new DatabaseAdapter(getContext());
listAdapter = new ReminderListAdapter(getActivity(), listItems, HomeFragment.this, this, this);
listView.setHasFixedSize(false);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
listView.addOnItemTouchListener(new RecyclerViewClickListener.RecyclerTouchListener(getContext(),
listView, new RecyclerViewClickListener.ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}
));
loadAllReminders();
}
#Override
public void onStart() {
super.onStart();
loadAllReminders();
}
private void loadAllReminders() {
listItems.clear();
List<Reminder> list = dbAdapter.getReminderById(REMINDER_TYPE_ID, HOME);
if (list.size() > 0) {
tvNoData.setVisibility(View.GONE);
listItems.addAll(list);
listAdapter.notifyDataSetChanged();
} else {
tvNoData.setVisibility(View.VISIBLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.menuItemListener = (MenuItemListener) getActivity();
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onFilterItem(int position) {
showLog("test: " + position);
}
public void setListener(MenuItemListener listener) {
this.menuItemListener = listener;
}
}
You can do this with EventBus or Interface. You can follow these steps for EventBus.
Implement EventBus
implementation 'org.greenrobot:eventbus:3.1.1'
EventBustDataEvents.class
public class EventBusDataEvents{
public static class isClick {
boolean isClick;
public isClick(boolean isClick) {
this.isClick = isClick;
}
public boolean getIsClick() {
return isClick;
}
public void setIsClick(boolean isClick) {
this.isClick = isClick;
}
}
}
MainActivity.class
EventBus.getDefault().postSticky(new EventBusDataEvents.isClick(true));
Fragment.class
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void isClick(EventBusDataEvents.isClick click) {
if (click.isClick()) {
}
}
#Override
public void onStart() {
super.onStart();
try {
EventBus.getDefault().register(this);
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
EventBus.getDefault().unregister(this);
} catch (Exception e) {
}
}
Or Interface
IMainActivity.class // interface class
public interface IMainActivity {
void onClick();}
MainActivity.class
private IMainActivity listener; //This will be described above as a field.
public void setOnEventListener(IMainActivity listener) {
IMainActivity = listener;
}
//buttonClickEvent
listener.OnClick();
Fragment.class
//onCreateView
setOnEventListener(new IMainActivity() {
#Override
public void onClick() {
}
});

Json don't update result in the seconde time

I have an activity where I can do a search through URL json file, so the 3 parameters pass from EditText of MainActivity to the second activity (annonces), the URL Json recovers the three values ​​and the results is normally displayed , but the problem if I made a return to MainActivity and I change the value of EditTexts and I click search, the results do not change.
this is my project :
MainActivity.java
package com.example.dzweber.waslup;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
AutoCompleteTextView cat;
String[] categories={"informatique","infographie","mathématique","Génie civil","Biologie"};
#Override
protected void onCreate(Bundle savedInstanceState) {
if(annonces.instance != null) {
annonces.instance.finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cat=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView2);
ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1,categories);
cat.setAdapter(adapter);
cat.setThreshold(1);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home) {
}
else if (id == R.id.login) {
Intent i = new Intent(this,login.class);
startActivity(i);
}
else if (id == R.id.avanced_search) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}
else if (id == R.id.annonces) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void as(View view) {
EditText loc;
EditText key;
loc = (EditText)findViewById(R.id.a_loc);
key = (EditText)findViewById(R.id.a_keys);
Intent intent = new Intent(getBaseContext(), annonces.class);
intent.putExtra("ca", cat.getText().toString());
intent.putExtra("lo",loc.getText().toString());
intent.putExtra("ke", key.getText().toString());
startActivity(intent);
}
public void connect(View view) {
}
}
annonces.java
package com.example.dzweber.waslup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.androidquery.AQuery;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONObject;
public class annonces extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static ArrayList<annonce_item> Items = new ArrayList<annonce_item>();
public static TextView txtv;
public static String data = "";
String skey = "";
String sloc = "";
String scat = "";
String date="";
String loc="";
String cat="";
String vue="";
String titre="";
String id="";
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public static annonces instance = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fetchD p = new fetchD();
//p.execute();
instance = this;
skey= getIntent().getStringExtra("ke");
sloc= getIntent().getStringExtra("lo");
scat= getIntent().getStringExtra("ca");
setContentView(R.layout.activity_annonces);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new AsyncCaller().execute();
TextView t = (TextView) findViewById(R.id.testing);
t.setText(scat);
// String generate = "https://www.waslup.pw/generation-json";
// String myurl = "https://www.waslup.pw/wp-content/uploads/wpdata.json";
// new MyAsyncTaskgetNews().execute(generate);
// new MyAsyncTaskgetNews().execute(myurl);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void finish() {
super.finish();
instance = null;
}
public void buclick(View view) {
}
#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.annonces, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home) {
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
finish();
}
else if (id == R.id.login) {
Intent i = new Intent(this,login.class);
startActivity(i);
}
else if (id == R.id.avanced_search) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}
else if (id == R.id.annonces) {
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class MyCustomAdapter extends BaseAdapter {
ArrayList<annonce_item> Items = new ArrayList<annonce_item>();
MyCustomAdapter(ArrayList<annonce_item> Items) {
this.Items = Items;
}
#Override
public int getCount() {
return Items.size();
}
#Override
public String getItem(int position) {
return Items.get(position).ititre;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater linflater = getLayoutInflater();
View view1 = linflater.inflate(R.layout.activity_annonce_item, null);
TextView id1 = (TextView) view1.findViewById(R.id.id);
TextView date1 = (TextView) view1.findViewById(R.id.date);
TextView cat1 = (TextView) view1.findViewById(R.id.cat);
TextView loc1 = (TextView) view1.findViewById(R.id.loc);
TextView titre1 = (TextView) view1.findViewById(R.id.titre);
TextView vue1 = (TextView) view1.findViewById(R.id.vue);
date1.setText(Items.get(i).idate);
id1.setText(Items.get(i).iid);
cat1.setText(Items.get(i).icat);
loc1.setText(Items.get(i).iloc);
titre1.setText(Items.get(i).ititre);
vue1.setText(Items.get(i).ivue);
return view1;
}
}
/*
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new AsyncCaller().execute();
}*/
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(annonces.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("/tChargement des annonces en cours ... ");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://www.waslup.pw/wp-admin/admin-ajax.php?action=do_ajax&fn=get_posts&count=10&key="+skey+"&cat="+scat+"&loc="+sloc);
HttpURLConnection httpuc = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpuc.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputstream));
String line ="";
while(line != null){
line = bf.readLine();
data= data + line;
}
JSONArray JA = null;
JA = new JSONArray(data);
annonces.Items.removeAll(annonces.Items);
for (int i=0 ; i<JA.length();i++){
JSONObject JO =(JSONObject) JA.get(i);
date =""+ JO.get("date");
loc =""+ JO.get("loc");
cat =""+ JO.get("Cat");
vue =""+ JO.get("vue");
titre =""+ JO.get("title");
id =""+ JO.get("Id");
annonces.Items.add(new annonce_item(id,date,loc,cat,vue,titre));
}
} catch (MalformedURLException e) {
} catch (JSONException e) {
} catch (IOException e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
final MyCustomAdapter myadpter = new MyCustomAdapter(Items);
ListView ls = (ListView) findViewById(R.id.listannonce);
ls.setAdapter(myadpter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView titre = (TextView) view.findViewById(R.id.titre);
Toast.makeText(getApplicationContext(), titre.getText(), Toast.LENGTH_LONG).show();
myadpter.notifyDataSetChanged();
TextView id2 = (TextView) view.findViewById(R.id.id);
Intent intent = new Intent(getBaseContext(), annonce_details.class);
intent.putExtra("id_from_annonces_activity", id2.getText());
startActivity(intent);
}
});
}
}
}
I reviewed your code and solved your problem.
There are two things need to discuss.
Your API providing the results according to localisation.If we change first two fields results will remain same and web service is fetching only one item with localisation 'oran'. But if we change localisation from 'oran' to 'alger' web service is displaying 4 results.
Here is the problem in your code.You are not concatenating your results properly in your data string. I have updated your code and now your code of AsyncCaller in announces Activity should be like:
Here is the code
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(annonces.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("/tChargement des annonces en cours ... ");
pdLoading.show();
}
#SuppressLint("NewApi")
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://www.waslup.pw/wp-admin/admin-ajax.php?action=do_ajax&fn=get_posts&count=10&key="+skey+"&cat="+scat+"&loc="+sloc);
HttpURLConnection httpuc = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpuc.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder total = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
total.append(line).append('\n');
}
JSONArray JA = null;
JA = new JSONArray(total.toString());
annonces.Items.removeAll(annonces.Items);
for (int i=0 ; i<JA.length();i++){
JSONObject JO =(JSONObject) JA.get(i);
date =""+ JO.get("date");
loc =""+ JO.get("loc");
cat =""+ JO.get("Cat");
vue =""+ JO.get("vue");
titre =""+ JO.get("title");
id =""+ JO.get("Id");
annonces.Items.add(new annonce_item(id,date,loc,cat,vue,titre));
}
} catch (MalformedURLException e) {
} catch (JSONException e) {
Log.d("js_ex:",e.toString());
} catch (IOException e) {
Log.d("io_ex:",e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
final MyCustomAdapter myadpter = new MyCustomAdapter(Items);
ListView ls = (ListView) findViewById(R.id.listannonce);
ls.setAdapter(myadpter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView titre = (TextView) view.findViewById(R.id.titre);
Toast.makeText(getApplicationContext(), titre.getText(), Toast.LENGTH_LONG).show();
myadpter.notifyDataSetChanged();
TextView id2 = (TextView) view.findViewById(R.id.id);
Intent intent = new Intent(getBaseContext(), annonce_details.class);
intent.putExtra("id_from_annonces_activity", id2.getText());
startActivity(intent);
}
});
}
}
In this code i added this part
StringBuilder total = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
total.append(line).append('\n');
}
JSONArray JA = null;
JA = new JSONArray(total.toString());

performItemClick on item in Android Navigation Drawer not working

I have a sliding drawer, and in the drawer is a ListView with 4 items. I would like to use performItemClick to programmatically click one of the items in the drawer, but no matter what I try the code seemingly does nothing. When the item is clicked it's supposed to replace the fragment currently in view with another fragment, and change the action bar title. But none of those things happen with I run performItemClick.
Here is the performItemClick, in a BroadcastReceiver which is receiving a Broadcast
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mDrawerList.performItemClick(mDrawerList.getAdapter().getView(1, null, null),1,mDrawerList.getAdapter().getItemId(1));
Log.d("receiver", "Got message + item clicked");
}
};
And here is the code for the actual activity which contains the performItemClick and the drawer itself, along with the drawers fragments (the performItemClick is near the bottom).
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.view.GravityCompat;
import android.text.Html;
#SuppressLint("ResourceAsColor")
public class MainActivity extends SherlockFragmentActivity {
private String Data, Band, Number, Class, Teacher, Title, Date, Type, Description, DescriptionAll, DescriptionCheck;
// Declare Variables
DrawerLayout mDrawerLayout;
LinearLayout mDrawerLinear;
TextView mWelcomePerson;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String actionbar_colors, background_colorsString;
private String Show_View;
String[] title;
String[] count;
int[] icon;
private String counterss;
private int counters;
Fragment fragment1 = new FragmentsView();
Fragment fragment2 = new FragmentsHomeworkDue();
Fragment fragment3 = new FragmentSettings();
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedprefers = getSharedPreferences("first_run", Context.MODE_PRIVATE );
if(sharedprefers.contains("first_run")){
}else{
SharedPreferences.Editor localEditor = getSharedPreferences("first_run", Context.MODE_PRIVATE ).edit();
localEditor.putString("first_run", "ran for the first time");
localEditor.commit();
Intent intenter = new Intent(this, MainActivity.class);
finish();
startActivity(intenter);
}
setContentView(R.layout.drawer_main);
SharedPreferences sharedpre = getSharedPreferences("show_view", Context.MODE_PRIVATE );
Show_View = sharedpre.getString("show_view", "");
SharedPreferences sharedpref = getSharedPreferences("actionbar_color", Context.MODE_PRIVATE );
if(!sharedpref.contains("actionbar_color")){
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#03a9f4")));
}else{
actionbar_colors = sharedpref.getString("actionbar_color", null);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(actionbar_colors)));
}
ActionBar bar = getSupportActionBar();
bar.setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
mTitle = mDrawerTitle = getTitle();
SharedPreferences Today_Homework = getApplicationContext().getSharedPreferences("due_today", Context.MODE_PRIVATE);
if(Today_Homework.contains("duetoday_content")){
parse_due_today_string();
}else{
counterss = "";
}
if(Show_View.equals("Homework Due")){
title = new String[] { "Homework Due", "Schedule", "Options", "Logout" };
icon = new int[] { R.drawable.ic_action_duehomework, R.drawable.ic_action_go_to_today, R.drawable.ic_action_settings, R.drawable.ic_action_logout };
if(counterss == null && counterss.isEmpty()){
count = new String[] { "", "", "", "" };
}
else{
count = new String[] { counterss, "", "", "" };
}
}else{
if(counterss == null && counterss.isEmpty()){
count = new String[] { "", "", "", "" };
}else{
count = new String[] { "", counterss, "", "" };
}
title = new String[] { "Schedule", "Homework Due", "Options", "Logout" };
icon = new int[] { R.drawable.ic_action_go_to_today, R.drawable.ic_action_duehomework, R.drawable.ic_action_settings, R.drawable.ic_action_logout };
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLinear = (LinearLayout) findViewById(R.id.left_drawer);
mWelcomePerson = (TextView) findViewById(R.id.Person);
mWelcomePerson.setText("Lincoln Bernard");
mDrawerList = (ListView) findViewById(R.id.listview_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mMenuAdapter = new MenuListAdapter(MainActivity.this, title,
icon, count);
mDrawerList.setAdapter(mMenuAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
getSupportActionBar().setTitle(mDrawerTitle);
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("up_navigation"));
}
public void parse_due_today_string() {
SharedPreferences Today_Homework = getApplicationContext().getSharedPreferences("due_today", Context.MODE_PRIVATE);
String Due_Today = Today_Homework.getString("duetoday_content", "");
ArrayList<String> description = new ArrayList<String>( );
StringBuilder DescriptionAll = new StringBuilder();
InputStream is = new ByteArrayInputStream(Due_Today.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
int i = 0;
while ((Due_Today = reader.readLine()) != null) {
String[] part = Due_Today.split("\",\"", -1);
int noOfItems = part.length;
int counter=0;
DescriptionCheck = counter<noOfItems ? part[counter] : "";
counter++;
Band = counter<noOfItems ? part[counter] : "";
counter++;
Number = counter<noOfItems ? part[counter] : "";
counter++;
Class = counter<noOfItems ? part[counter] : "";
counter++;
Teacher = counter<noOfItems ? part[counter] : "";
counter++;
Title = counter<noOfItems ? part[counter] : "";
counter++;
Date = counter<noOfItems ? part[counter] : "";
counter++;
Type = counter<noOfItems ? part[counter] : "";
counter++;
Data = counter<noOfItems ? part[counter] : "";
counter++;
if (Type != null && !Type.isEmpty()){
counters = ++i;
counterss = Integer.toString(counters);
Log.i("Counter","Number of children: "+ counters);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerLinear)) {
mDrawerLayout.closeDrawer(mDrawerLinear);
} else {
mDrawerLayout.openDrawer(mDrawerLinear);
}
}
return super.onOptionsItemSelected(item);
}
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) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(Show_View.equals("Homework Due")){
switch (position) {
case 0:
ft.replace(R.id.content_frame,fragment2);
break;
case 1:
ft.replace(R.id.content_frame, fragment1);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
}
}else{
switch (position) {
case 0:
ft.replace(R.id.content_frame,fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
}
}
ft.commit();
mDrawerList.setItemChecked(position, true);
/
setTitle(title[position]);
mDrawerLayout.closeDrawer(mDrawerLinear);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("receiver", "Got");
mDrawerList.performItemClick(mDrawerList.getAdapter().getView(1, null, null),1,mDrawerList.getAdapter().getItemId(1));
Log.d("receiver", "Got message");
}
};
#Override
public void onBackPressed() {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
manager.popBackStack();
} else {
super.onBackPressed();
}
}
}
MenuListAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MenuListAdapter extends BaseAdapter {
Context context;
String[] mTitle;
String[] mCount;
int[] mIcon;
LayoutInflater inflater;
public MenuListAdapter(Context context, String[] title,
int[] icon, String[] count) {
this.context = context;
this.mTitle = title;
this.mIcon = icon;
this.mCount = count;
}
#Override
public int getCount() {
return mTitle.length;
}
#Override
public Object getItem(int position) {
return mTitle[position];
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView txtTitle;
ImageView imgIcon;
TextView txtCount;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.drawer_list_item, parent,
false);
txtTitle = (TextView) itemView.findViewById(R.id.title);
txtCount = (TextView) itemView.findViewById(R.id.counter);
imgIcon = (ImageView) itemView.findViewById(R.id.icon);
txtTitle.setText(mTitle[position]);
txtCount.setText(mCount[position]);
imgIcon.setImageResource(mIcon[position]);
return itemView;
}
}
What I have done is something like this inside my Expandable listview adapter for Drawer..
View.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
switch (groupPosition)
{
case 0:
switch (childPosition)
{
case 0:
if (groupPosition == 0 && childPosition == 0)
{ some code }
Edit: this switch starts different activity (or change view if fragment) on each respective item click.. in your case their will be fragments..

Categories

Resources