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()
Related
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) {
}
}
"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..
I am working on a small application to save the data of the book (such as the name of the book, the type of the book, the author of the book and the year of publication) in a database, but when the data is returned from the databases using CursorLoader It's shown twice in ListView
This is a code of AddBook activity.
package training.android.com.librarycard;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
public class AddBook extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_BOOK_LOADER = 0;
Spinner mBookType;
EditText mBookTitle, mBookAuthor, mBookPublishYear;
String bookType;
int position;
private boolean bookHasChanged = false;
private Uri currentBookUri;
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
bookHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
Intent intent = getIntent();
if (intent != null) {
currentBookUri = intent.getData();
if (currentBookUri == null) {
setTitle("Add a book");
invalidateOptionsMenu();
} else {
setTitle("Edit a book");
getLoaderManager().initLoader(EXISTING_BOOK_LOADER, null, this);
}
}
mBookType = findViewById(R.id.spinner);
mBookTitle = findViewById(R.id.book_title);
mBookAuthor = findViewById(R.id.book_author);
mBookPublishYear = findViewById(R.id.publish_year);
mBookType.setOnTouchListener(touchListener);
mBookAuthor.setOnTouchListener(touchListener);
mBookTitle.setOnTouchListener(touchListener);
mBookPublishYear.setOnTouchListener(touchListener);
setupBookTypeSpinner();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (currentBookUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_save:
setBook();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!bookHasChanged) {
NavUtils.navigateUpFromSameTask(AddBook.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener
= new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
NavUtils.navigateUpFromSameTask(AddBook.this);
}
};
showUnsavedChangeDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
private void showUnsavedChangeDialog(DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Discard your changes and quit editing?");
builder.setPositiveButton("Discard", discardButtonClickListener);
builder.setNegativeButton("Keep editing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this book ?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteBook();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteBook() {
if (currentBookUri != null) {
int rowDeleted = getContentResolver().delete(currentBookUri, null, null);
if (rowDeleted == 0)
Toast.makeText(this, "Delete book failed", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Delete book successful", Toast.LENGTH_SHORT).show();
}
finish();
}
public void setupBookTypeSpinner() {
final ArrayAdapter<CharSequence> bookTypeAdapter = ArrayAdapter.createFromResource(
this, R.array.books_type, R.layout.support_simple_spinner_dropdown_item);
bookTypeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mBookType.setAdapter(bookTypeAdapter);
mBookType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
bookType = parent.getSelectedItem().toString();
position = parent.getSelectedItemPosition();
Log.i("BookTypeSelection", bookType+"");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void setBook() {
String bookTitle = mBookTitle.getText().toString().trim();
String bookAuthor = mBookAuthor.getText().toString().trim();
String publishYear = mBookPublishYear.getText().toString().trim();
if (currentBookUri == null && TextUtils.isEmpty(bookTitle) && TextUtils.isEmpty(bookAuthor)
&& TextUtils.isEmpty(publishYear))
return;
Database database = new Database(this);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE, bookTitle);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR, bookAuthor);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR, publishYear);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE, bookType);
if (currentBookUri == null) {
Uri uri = getContentResolver().insert(LibraryCardContract.LibraryCard.CONTENT_URI, values);
if (uri == null) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
} else {
int rowAffected = getContentResolver().update(currentBookUri, values, null, null);
if (rowAffected == 0) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
}
db.insert(LibraryCardContract.LibraryCard.TABLE_NAME, null, values);
Toast.makeText(this, "Insert new book", Toast.LENGTH_SHORT).show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String [] projection = {
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR };
return new CursorLoader(this,currentBookUri,projection,
null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(data.moveToFirst()){
String title = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String publishYear = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
mBookTitle.setText(title);
mBookAuthor.setText(author);
mBookType.setSelection(position);
mBookPublishYear.setText(publishYear);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mBookTitle.setText("");
mBookType.setSelection(position);
mBookAuthor.setText("");
mBookPublishYear.setText("");
}
#Override
public void onBackPressed() {
if(!bookHasChanged){
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
};
showUnsavedChangeDialog(discardButtonClickListener);
}
}
And this is a code of Home activity that contains a listView to
display the data.
package training.android.com.librarycard;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
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.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.Models.BookCursorAdapter;
import training.android.com.librarycard.Models.BookDetail;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final int BOOK_LOADER = 0;
private ListView mBookList;
private BookCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mBookList = findViewById(R.id.books_rv);
cursorAdapter = new BookCursorAdapter(this, null);
mBookList.setAdapter(cursorAdapter);
mBookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Home.this, AddBook.class);
Uri currentPetUri = ContentUris.withAppendedId(LibraryCardContract.LibraryCard.CONTENT_URI, id);
intent.setData(currentPetUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(BOOK_LOADER, null, this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddBook.class);
startActivity(intent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public 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.menu, 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();
switch (id) {
case R.id.delete_all_books:
deleteAllBooks();
return true;
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
private void deleteAllBooks() {
int rowDeleted = getContentResolver().delete(LibraryCardContract.LibraryCard.CONTENT_URI,
null, null);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
LibraryCardContract.LibraryCard._ID,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR};
return new CursorLoader(this, LibraryCardContract.LibraryCard.CONTENT_URI,
projection,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
> This is a code of **BookCursorAdapter** class.
package training.android.com.librarycard.Models;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.R;
/**
* Created by Hassan on 4/9/2018.
*/
public class BookCursorAdapter extends CursorAdapter {
public BookCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context)
.inflate(R.layout.book_list,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView bookTitle = view.findViewById(R.id.book_name_tv);
TextView bookAuthor = view.findViewById(R.id.author_tv);
TextView bookType = view.findViewById(R.id.book_type_tv);
TextView publishYear = view.findViewById(R.id.publish_year_tv);
String title = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String year = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
bookAuthor.setText(author);
bookTitle.setText(title);
bookType.setText(type);
publishYear.setText(year);
}
#Override
public int getCount() {
return super.getCount();
}
}
Screenshot of the application
enter image description here
I want put edittext from first activity to new secondactivity view text.
What to do when I have an erro like this displayed in android monitor :
com.example.xx.DrawerAddAd.seeAdd(DrawerAddAd.java:129)
com.example.xx.DrawerAddAd.access$100(DrawerAddAd.java:40)
com.example.xx.DrawerAddAd$2.onClick(DrawerAddAd.java:116)
also:
Render problem:
Couldn't resolve resource #id/visible
Tip: Try to refresh the layout.
DrawerAddAd class code:
package com.example.xx.drawer;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import com.example.xx.R;
import com.example.xxx.model.POJO.view.ProductDetails;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import butterknife.BindView;
public class DrawerAddAd extends AppCompatActivity {
public static ArrayList<String> fragments = new ArrayList<>();
private final int REQUEST_CODE = 1;
private ImageButton camera_imageButton;
private Spinner spinner_category;
private Button button_seeAd_product;
private Button button_add_product;
#BindView(R.id.title_Ad_editText)
EditText titleAd_editText;
#BindView(R.id.text_Ad_editText)
EditText textAd_editText;
#BindView(R.id.price_editText)
EditText price_editText;
#BindView(R.id.checkBox_season)
CheckBox checkBox_season;
#BindView(R.id.checkBox_year)
CheckBox checkBox_year;
#BindView(R.id.checkBox_detail)
CheckBox checkBox_detail;
#BindView(R.id.checkBox_wholesale)
CheckBox checkBox_whoLesale;
private int REQUEST_CAMERA = 1, SELECT_FILE = 1;
private Button btnSelect;
private ImageView Image;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_add_ad);
final TextInputLayout title_ad_layout = (TextInputLayout) findViewById(R.id.add_title_ad_layout);
final TextInputLayout text_ad_layout = (TextInputLayout) findViewById(R.id.add_text_ad_layout);
final TextInputEditText title_Ad_editText = (TextInputEditText) findViewById(R.id.title_Ad_editText);
final TextInputEditText text_Ad_editText = (TextInputEditText) findViewById(R.id.text_Ad_editText);
setTextWatcher(title_Ad_editText, title_ad_layout);
setTextWatcher(text_Ad_editText, text_ad_layout);
spinner_category = (Spinner) findViewById(R.id.spinner_category);
button_seeAd_product = (Button) findViewById(R.id.button_seeAd_product);
button_add_product = (Button) findViewById(R.id.button_ad_product);
camera_imageButton = (ImageButton) findViewById(R.id.camera_imageButton);
camera_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
button_seeAd_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean error = false;
if (TextUtils.isEmpty(title_Ad_editText.getText().toString())) {
title_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (TextUtils.isEmpty(text_Ad_editText.getText().toString())) {
text_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (!error) {
seeAdd();
}
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.fragments, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner_category.setAdapter(adapter);
}
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
// ImageView imageView =
// String title = titleAd_editText.getText().toString();
// String text = textAd_editText.getText().toString();
// String price = price_editText.getText().toString();
//
//
// intent.putExtra("titleAdd", title);
// intent.putExtra("textAdd", text);
// intent.putExtra("price", price);
startActivity(intent);
}
private void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch (view.getId()) {
case R.id.checkBox_season:
if (checked) {
} else {
}
break;
case R.id.checkBox_year:
if (checked) {
} else {
}
break;
case R.id.checkBox_detail:
if (checked) {
} else {
}
break;
case R.id.checkBox_wholesale:
if (checked) {
} else {
}
break;
}
}
private void setTextWatcher(final TextInputEditText editText, final TextInputLayout inputLayout) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (inputLayout.isErrorEnabled()) {
inputLayout.setErrorEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
private void selectImage() {
final CharSequence[] items = {"Zrób zdjęcie", "Wybierz z katalogu", "Anuluj"};
AlertDialog.Builder builder = new AlertDialog.Builder(DrawerAddAd.this);
builder.setTitle("Dodaj zdjęcie");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(DrawerAddAd.this);
if (items[item].equals("Zrób zdjęcie")) {
userChosenTask = "Zrób zdjęcie";
if (result)
cameraIntent();
} else if (items[item].equals("Wybierz z katalogu")) {
userChosenTask = "Wybierz z katalogu";
if (result)
galleryIntent();
} else if (items[item].equals("Anuluj")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Wybierz plik"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Image.setImageBitmap(bm);
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Image.setImageBitmap(thumbnail);
}
}
ProductDetails class code:
package com.example.xxx.model.POJO.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import com.example.xxx.R;
public class ProductDetails extends AppCompatActivity {
private TextView title, text, price, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title = (TextView) findViewById(R.id.title_textView);
text = (TextView) findViewById(R.id.text_textView);
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
title.setText(title_textView);
text.setText(text_textView);
// price = (TextView) findViewById(R.id.price_textView);
// date = (TextView) findViewById(R.id.date_textView);
// String titleAdd = bundle.getString("titleAdd");
// String textAdd = bundle.getString("textAdd");
// String price = bundle.getString("price");
// title.setText(titleAdd);
// text.setText(textAdd);
// price.setText(price);
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();
}
});
}
}
I don't know what to do ...
Thanks, Slawek.
it means title_Ad_editText is null.
Check your xml file and title_Ad_editText variable.
couple things I could see, redo this:
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
to this:
private void seeAdd() {
Intent intent = new Intent(DrawerAddAd.this, ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
then in your intent, you need to call the extra exactly as set, change this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
to this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("title");
String text_textView = intent.getStringExtra("text");
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have 1 problem and Who can help me?.
I have 1 Activity run when start App
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.Serializable;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
Button btnLogin, btnRegister, btnFindPassword;
EditText editUsername, editPassword;
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
btnLogin = (Button) findViewById(R.id.button_login);
btnRegister = (Button) findViewById(R.id.button_register);
btnFindPassword = (Button) findViewById(R.id.button_findPassword);
editUsername = (EditText) findViewById(R.id.editText_username);
editPassword = (EditText) findViewById(R.id.editText_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarActivity);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Đăng nhập");
Login();
Register();
FindPassword();
}
public void Login(){
btnLogin.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = db.getDataTableUser();
int temp = 1;
if (res.getCount() == 0) {
showMessage("Error", "Tài khoản không tồn tại");
return;
}
while (res.moveToNext()) {
String username, password, idUser;
idUser = res.getString(0);
username = res.getString(1);
password = res.getString(2);
if (editUsername.getText().toString().equals(username) == true&&editPassword.getText().toString().equals(password) == true) {
doOpenManagePage(idUser);
temp = 0;
break;
}
}
if (temp==1){
showMessage("Error", "Account does not exist");
}
}
}
);
}
public void Register(){
btnRegister.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenRegister();
}
}
);
}
public void FindPassword(){
btnFindPassword.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenFindPasswordStep1();
}
}
);
}
public void doOpenRegister(){
Intent newIntent = new Intent(this, Register.class);
startActivity(newIntent);
}
public void doOpenFindPasswordStep1(){
Intent newIntent = new Intent(this, FindPasswordStep1.class);
startActivity(newIntent);
}
public void doOpenManagePage(String idUser){
Intent newIntent = new Intent(this, ManagePage.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_manage_page, 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_logout) {
return true;
}
else if (id==R.id.action_search){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then it send IdUser to this Activity
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class ManagePage extends AppCompatActivity{
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_page);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_note);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doOpenInsertNote(idUser);
}
});
}
public String getIdUser(){
Bundle extras = getIntent().getExtras();
String idUser = extras.getString("IdUser");
return idUser;
}
public void doOpenInsertNote(String idUser){
Intent newIntent = new Intent(this, InsertNote.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
}
When i run it 1st time, this app is ok, it can go to next Activity
package com.example.khuatduytan.doantotnghiep;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
public class InsertNote extends AppCompatActivity implements View.OnClickListener {
private ImageButton insertDate;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et, content_InsertNote, money_InsertNote;
private Button btnSubmitNote, btnCancelNote;
private Spinner SelectTypeNote;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
insertDate = (ImageButton) findViewById(R.id.dateInsert);
cal = Calendar.getInstance();
et = (EditText) findViewById(R.id.dateInsert_editText);
btnSubmitNote = (Button) findViewById(R.id.insertNote);
btnCancelNote = (Button) findViewById(R.id.cancelNote);
content_InsertNote = (EditText) findViewById(R.id.noiDung);
money_InsertNote = (EditText) findViewById(R.id.soTien);
SelectTypeNote = (Spinner) findViewById(R.id.loai);
db = new DatabaseHelper(this);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
insertDate.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
setBtnSubmitNote(idUser);
setBtnCancelNote();
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / " + selectedYear);
}
};
private void setBtnSubmitNote(final String idUser){
btnSubmitNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmDialog(idUser);
}
});
}
private void setBtnCancelNote(){
Intent newIntent = new Intent(this, ManagePage.class);
startActivity(newIntent);
}
private void confirmDialog(final String idUser) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String date = null, content = null, money = null, TypeNote_Selected;
int Type_Note = 0, id_User;
id_User = Integer.parseInt(idUser);
date = et.getText().toString();
content = content_InsertNote.getText().toString();
money = money_InsertNote.getText().toString();
TypeNote_Selected = SelectTypeNote.getSelectedItem().toString();
if(TypeNote_Selected.equals("Thu")){
Type_Note = 0;
} else{
Type_Note = 1;
}
if(date.equals("")||content.equals("")||money.equals("")){
Toast.makeText(InsertNote.this, "Bạn chưa nhập đủ dữ liệu", Toast.LENGTH_LONG).show();
}
else {
long isInserted = db.insertNoteTable(date, content, Type_Note, money, id_User);
if (isInserted == -1) {
Toast.makeText(InsertNote.this, "Thêm ghi chú không thành công", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(InsertNote.this, "Thêm ghi chú thành công", Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.show();
}
}
`
But when i run it second time, When i click button to open Activity
InsertNote, I receive a error
03-26 16:12:32.161 2614-2614/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khuatduytan.doantotnghiep/com.example.khuatduytan.doantotnghiep.ManagePage}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.khuatduytan.doantotnghiep.ManagePage.onCreate(ManagePage.java:21)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I tried to print what i send from Activity Main to Activity ManagePage by Toast, it display exactly what i want to send.
But i dont know why this error display.
Can you help me?
Sorry about my English
You call setBtnCancelNote() method in the onCreate() method of your InsertNote activity. so as soon as InsertNote starts it tries to launch the ManagePage activity.
The problem is your ManagePage activity expects the value IdUser in the bundle received from the intent. But you do not pass this value to ManagePage activity when you start it from InsertNote activity.
You probably want to add this line to your setBtncancelNote() method in InsertPage activity -
newIntent.putExtra("IdUser", //The Values here);
If you pass this value then ManageNote will not crash.
please add more info like line numbers, otherwise its difficult to debug it remotely ..
Anyway, my guess is you have to check for null pointers when you do stuff like getIntent().getExtras()
just put some breakpoints there, and step by step and you'll figure it out