App Crashing when calling a Fragment from an Activity - java

I'm developing an app where I have a fragment as my home page. I'm currently trying to call that fragment from an activity but unfortunately it is crashing. I had even implemented the FragmentTransaction and it still doesnt want to pick it up.
logcat
05-02 22:22:40.331 5927-5927/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 5927
java.lang.NullPointerException: Attempt to invoke virtual method' android.support.v4.app.FragmentTransactio android.support.v4.app.FragmentTransaction.replace(int, android.support.v4.app.Fragment)' on a null object reference at com.example.treycoco.calorietracker.CalorieDetails$1$1.onClick(CalorieDetails.java:79)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
update logcat
example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 19224
java.lang.IllegalArgumentException: No view found for id 0x7f0e0080 (com.example.treycoco.calorietracker:id/FragmentHolder) for fragment FragmentHome{d567f7e #0 id=0x7f0e0080}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1059)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
caloriedetails.java
public class CalorieDetails extends AppCompatActivity {
private TextView foodName, calories, dateTaken;
private Button shareButton;
private int foodId;
private Button deleteButton;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_details);
foodName = (TextView) findViewById(R.id.detsFoodName);
calories = (TextView) findViewById(R.id.detscaloriesValue);
dateTaken = (TextView) findViewById(R.id.detsDateText);
deleteButton = (Button) findViewById(R.id.deleteButton);
Food food = (Food) getIntent().getSerializableExtra("userObj");
foodName.setText(food.getFoodName());
calories.setText(String.valueOf(food.getCalories()));
dateTaken.setText(food.getRecordDate());
foodId = food.getFoodId();
foodName.setTextColor(Color.WHITE);
dateTaken.setTextColor(Color.WHITE);
calories.setTextSize(34.9f);
calories.setTextColor(Color.WHITE);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: put delete functionality here
android.support.v7.app.AlertDialog.Builder alert = new
android.support.v7.app.AlertDialog.Builder(CalorieDetails.this);
alert.setTitle("Delete?");
alert.setMessage("Are you sure you want to delete this item?");
alert.setNegativeButton("No", null);
alert.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHandler dba = new
DatabaseHandler(getApplicationContext());
dba.deleteFood(foodId);
Toast.makeText(CalorieDetails.this, "Food Item
Deleted!", Toast.LENGTH_SHORT).show();
FragmentHome fragmentHome = new FragmentHome()
fragmentTransaction =
getSupportedFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.FragmentHolder,
fragmentHome);
fragmentTransaction.commit();
CalorieDetails.this.finish();
}
});
alert.show();
}
});
}
}
caloriedetails.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
tools:context=".CalorieDetails"
android:background="#drawable/imgbackground2"
style="#style/AppTheme"
>
<ImageView
android:id="#+id/logo"
android:src="#drawable/weight"
android:layout_centerHorizontal="true"
android:layout_width="180dp"
android:layout_height="180dp" />
<LinearLayout
android:id="#+id/layout"
android:elevation="4dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/logo"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/detsFoodName"
android:elevation="4dp"
android:text="dkdad"
android:textSize="19sp"
android:textStyle="bold"
android:layout_marginTop="18dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detsCaloriesTitle"
android:text="Calories:"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detscaloriesValue"
android:text="200"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detsDateText"
android:text="Consumed on..."
android:textStyle="italic"
android:textSize="14sp"
android:layout_marginTop="14dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/deleteButton"
android:text="DELETE"
android:textColor="#ffff"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:layout_gravity="center_horizontal"
android:layout_width="200dp"
android:background="#color/colorBackground2"
android:layout_height="wrap_content" />
</LinearLayout>

You have declared the fragmentManager and fragmentTransaction but not yet initialized.
FragmentHome fragmentHome = new FragmentHome();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.FragmentHolder, fragmentHome);
fragmentTransaction.commit();
Remove this line from onClick method,
CalorieDetails.this.finish();
Because you are going to add the fragment in activity so dont finish the activity.
Add this code in your caloriedetails.xml file
<LinearLayout
android:id="#+id/FragmentHolder"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Please do some google search before start implement.

Your fragmentTransaction is null as you don't initialize it hence the exception.
Do this
FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction();

Related

Main Activity overlay with fragment

I have a problem where when I call my fragment by pushing a button in main activity, its overlay with the main activity. It make both of them on top of each other. I would want the fragment to cover a part of the main activity so the item behind are not viewable. I already user replace() when I want to start the fragment but it still did not work. I can still see the main activity behind of the fragment like picture below:
I want to avoid using visible for the main activity because in my main project there is a lot of item (CalenderView, RecyclerView, etc) behind it.
Here is my main activity code:
public class MainActivity extends AppCompatActivity {
private Button mShowPaymentButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShowPaymentButton = findViewById(R.id.show_payment_button);
/*FrameLayout blurContainer = findViewById(R.id.fragment_container);
Blurry.with(this)
.radius(25)
.sampling(2)
.onto(blurContainer);*/
mShowPaymentButton.setOnClickListener(v -> {
FragmentManager fragmentManager = getSupportFragmentManager();
BigDecimal amount = new BigDecimal("10.00");
PaymentFragment paymentFragment = PaymentFragment.newInstance(amount);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_from_top, R.anim.slide_out_to_top);
fragmentTransaction.replace(R.id.fragment_container, paymentFragment, paymentFragment.getTag());
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
});
}}
MainActivity xml:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/show_payment_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Fragment code:
public class PaymentFragment extends Fragment {
private static final String ARG_AMOUNT = "amount";
private Button mPayButton;
private ProgressBar mProgressBar;
EditText mCardNumberEditText;
EditText mExpiryDateEditText;
EditText mCvvEditText;
ImageButton closeButton;
EditText mErrorTextView;
private BigDecimal amount;
public PaymentFragment() {
// Required empty public constructor
}
public static PaymentFragment newInstance(BigDecimal amount) {
PaymentFragment fragment = new PaymentFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_AMOUNT, amount);
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_payment, container, false);
mPayButton = view.findViewById(R.id.pay_button);
//mProgressBar = view.findViewById(R.id.progress_bar);
mCardNumberEditText = view.findViewById(R.id.card_number_edit_text);
mExpiryDateEditText = view.findViewById(R.id.expiry_date_edit_text);
mCvvEditText = view.findViewById(R.id.cvv_edit_text);
//mErrorTextView = view.findViewById(R.id.error_text_view);
mPayButton = view.findViewById(R.id.pay_button);
closeButton = view.findViewById(R.id.close_button_payment);
amount = (BigDecimal) getArguments().getSerializable(ARG_AMOUNT);
mPayButton.setText("Pay RM "+amount);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentTransaction.remove(PaymentFragment.this).commit();
}
});
mPayButton.setOnClickListener(v -> {
// Show the progress bar
//mProgressBar.setVisibility(View.VISIBLE);
mPayButton.setEnabled(false);
String cardNumber = mCardNumberEditText.getText().toString();
String expiryDate = mExpiryDateEditText.getText().toString();
String cvv = mCvvEditText.getText().toString();
if (cardNumber.isEmpty() || expiryDate.isEmpty() || cvv.isEmpty()) {
//mErrorTextView.setText("Please enter all required fields.");
//mErrorTextView.setVisibility(View.VISIBLE);
} else {
/* mProgressBar.postDelayed(() -> {
mProgressBar.setVisibility(View.GONE);
mPayButton.setEnabled(true);
fragmentTransaction.remove(PaymentFragment.this);
fragmentTransaction.commit();
}, 2000);*/
fragmentTransaction.remove(this).commit();
}
});
TranslateAnimation animation = new TranslateAnimation(0, 0, -view.getHeight(), 0);
animation.setDuration(500);
view.startAnimation(animation);
return view;
}
}
fragment xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#590E0E0E"
android:orientation="vertical"
android:padding="16dp">
<ImageButton
android:id="#+id/close_button_payment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:backgroundTint="#AAAAAA"
android:src="#drawable/close_payment_button" />
<TextView
android:text="Add your payment information"
android:textSize="20sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/card_number_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Card number:" />
<EditText
android:id="#+id/card_number_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<TextView
android:id="#+id/expiry_date_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expiry date:" />
<EditText
android:id="#+id/expiry_date_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="date" />
<TextView
android:id="#+id/cvv_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CVV:" />
<EditText
android:id="#+id/cvv_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<Button
android:id="#+id/pay_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pay" />
<TextView
android:id="#+id/error_text_view"
android:layout_width="378dp"
android:layout_height="30dp"
android:textColor="#color/purple_200"
android:visibility="invisible" />
</LinearLayout>
Any advice and suggestion would really help. Thanks in advance. There is no error from my code but maybe can be optimize.
Change your activity_main.xml like:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
...
</androidx.constraintlayout.widget.ConstraintLayout>

onTouchListener for custom view keeps crashing my app [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I'm currently making a soundboard app for Android with custom neomorphic buttons. My goal for the app is for the button to change style (look like it's pressed) when I click it using an onTouchListener. However my app crashes whenever I try to add an onTouchListener (in the initButton() function on MainAcitvity.java). I attached my code as well as links to the neomrphic library I used below:
Neomorphic View Library:
https://medium.com/#fornewid/neumorphism-in-android-9cf15e2122dc
https://github.com/fornewid/neumorphism
MainActivity.java
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.titleText);
String text = "R6 Soundboard";
SpannableString ss = new SpannableString(text);
ForegroundColorSpan fcsYellow = new ForegroundColorSpan(Color.rgb(255,236,141));
ss.setSpan(fcsYellow, 1,2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ss);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.view_pager);
setUpViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabTextColors(Color.WHITE, Color.WHITE);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setText("Defenders");
tabLayout.getTabAt(1).setText("Attackers");
initButton();
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new defendersTab(), "Defenders");
adapter.addFragment(new attackersTab(), "Attackers");
viewPager.setAdapter(adapter);
}
#SuppressLint("ClickableViewAccessibility")
private void initButton(){
final NeumorphCardView DefR1C1 = (NeumorphCardView) findViewById(R.id.buttonDR1C1);
DefR1C1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
DefR1C1.setShapeType(ShapeType.PRESSED);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
DefR1C1.setShapeType(ShapeType.FLAT);
}
return false;
}
});
/*
final MediaPlayer mp = MediaPlayer.create(this, R.raw.lionroar);
DefR1C1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if(mp.isPlaying()) {
//STOP PLAYING
mp.seekTo(0);
}
mp.start();
return false;
}
});
*/
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:theme="#style/AppTheme.AppBarOverlay">
<TextView
android:id="#+id/titleText"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/avenir"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:text="R6 Soundboard"
android:textColor="#FFF"
android:textSize="30sp" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextColor="#fff"
android:background="?attr/colorPrimaryDark" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
fragment_defenders_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark">
<soup.neumorphism.NeumorphCardView
android:id="#+id/buttonDR1C1"
android:layout_width="175dp"
android:layout_height="175dp"
android:layout_alignParentStart="true"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
app:neumorph_backgroundColor="#color/colorPrimaryDark"
app:neumorph_inset="12dp"
app:neumorph_insetBottom="12dp"
app:neumorph_insetEnd="12dp"
app:neumorph_insetStart="12dp"
app:neumorph_insetTop="12dp"
app:neumorph_lightSource="leftTop"
app:neumorph_shadowColorDark="#color/solid_dark_color"
app:neumorph_shadowColorLight="#color/solid_light_color"
app:neumorph_shadowElevation="3dp"
app:neumorph_shapeType="flat">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="62.5dp"
android:fontFamily="#font/proximanovasoft"
android:text="Lion Scan"
android:textColor="#ffffff"
android:textSize="20dp" />
</LinearLayout>
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
android:id="#+id/buttonDR1C2"
android:layout_width="175dp"
android:layout_height="175dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
app:neumorph_backgroundColor="#color/colorPrimaryDark"
app:neumorph_inset="12dp"
app:neumorph_insetBottom="12dp"
app:neumorph_insetEnd="12dp"
app:neumorph_insetStart="12dp"
app:neumorph_insetTop="12dp"
app:neumorph_lightSource="leftTop"
app:neumorph_shadowColorDark="#color/solid_dark_color"
app:neumorph_shadowColorLight="#color/solid_light_color"
app:neumorph_shadowElevation="3dp"
app:neumorph_shapeType="flat">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="62.5dp"
android:fontFamily="#font/proximanovasoft"
android:text="Thermite"
android:textColor="#ffffff"
android:textSize="20dp" />
</LinearLayout>
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
android:id="#+id/buttonDR2C1"
android:layout_width="175dp"
android:layout_height="175dp"
android:layout_below="#+id/buttonDR1C2"
android:layout_alignParentEnd="true"
android:layout_marginTop="11dp"
android:layout_marginEnd="20dp"
app:neumorph_backgroundColor="#color/colorPrimaryDark"
app:neumorph_inset="12dp"
app:neumorph_insetBottom="12dp"
app:neumorph_insetEnd="12dp"
app:neumorph_insetStart="12dp"
app:neumorph_insetTop="12dp"
app:neumorph_lightSource="leftTop"
app:neumorph_shadowColorDark="#color/solid_dark_color"
app:neumorph_shadowColorLight="#color/solid_light_color"
app:neumorph_shadowElevation="3dp"
app:neumorph_shapeType="flat">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="62.5dp"
android:fontFamily="#font/proximanovasoft"
android:text="Barricade"
android:textColor="#ffffff"
android:textSize="20dp" />
</LinearLayout>
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
android:id="#+id/buttonDR2C2"
android:layout_width="175dp"
android:layout_height="175dp"
android:layout_below="#+id/buttonDR1C1"
android:layout_alignParentStart="true"
android:layout_marginStart="20dp"
android:layout_marginTop="12dp"
app:neumorph_backgroundColor="#color/colorPrimaryDark"
app:neumorph_inset="12dp"
app:neumorph_insetBottom="12dp"
app:neumorph_insetEnd="12dp"
app:neumorph_insetStart="12dp"
app:neumorph_insetTop="12dp"
app:neumorph_lightSource="leftTop"
app:neumorph_shadowColorDark="#color/solid_dark_color"
app:neumorph_shadowColorLight="#color/solid_light_color"
app:neumorph_shadowElevation="3dp"
app:neumorph_shapeType="flat">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="62.5dp"
android:fontFamily="#font/proximanovasoft"
android:text="Planting"
android:textColor="#ffffff"
android:textSize="20dp" />
</LinearLayout>
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
android:id="#+id/buttonDR3C1"
android:layout_width="175dp"
android:layout_height="175dp"
android:layout_below="#+id/buttonDR2C2"
android:layout_alignParentEnd="true"
android:layout_marginTop="11dp"
android:layout_marginEnd="20dp"
app:neumorph_backgroundColor="#color/colorPrimaryDark"
app:neumorph_inset="12dp"
app:neumorph_insetBottom="12dp"
app:neumorph_insetEnd="12dp"
app:neumorph_insetStart="12dp"
app:neumorph_insetTop="12dp"
app:neumorph_lightSource="leftTop"
app:neumorph_shadowColorDark="#color/solid_dark_color"
app:neumorph_shadowColorLight="#color/solid_light_color"
app:neumorph_shadowElevation="3dp"
app:neumorph_shapeType="flat">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="62.5dp"
android:fontFamily="#font/proximanovasoft"
android:text="Fuze"
android:textColor="#ffffff"
android:textSize="20dp" />
</LinearLayout>
</soup.neumorphism.NeumorphCardView>
<soup.neumorphism.NeumorphCardView
android:id="#+id/buttonDR3C2"
android:layout_width="175dp"
android:layout_height="175dp"
android:layout_below="#+id/buttonDR2C1"
android:layout_alignParentStart="true"
android:layout_marginStart="20dp"
android:layout_marginTop="12dp"
app:neumorph_backgroundColor="#color/colorPrimaryDark"
app:neumorph_inset="12dp"
app:neumorph_insetBottom="12dp"
app:neumorph_insetEnd="12dp"
app:neumorph_insetStart="12dp"
app:neumorph_insetTop="12dp"
app:neumorph_lightSource="leftTop"
app:neumorph_shadowColorDark="#color/solid_dark_color"
app:neumorph_shadowColorLight="#color/solid_light_color"
app:neumorph_shadowElevation="3dp"
app:neumorph_shapeType="flat">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="62.5dp"
android:fontFamily="#font/proximanovasoft"
android:text="Drone"
android:textColor="#ffffff"
android:textSize="20dp" />
</LinearLayout>
</soup.neumorphism.NeumorphCardView>
</RelativeLayout>
</FrameLayout>
SectionsPageAdapter.java
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return super.getPageTitle(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
edit: on request, I added the crash log and a picture of my app working before I tried to make the buttons actually work using onTouchListener
2020-12-14 10:54:31.781 8217-8217/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jkcarraher.rainbowsixsoundboard, PID: 8217
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jkcarraher.rainbowsixsoundboard/com.jkcarraher.rainbowsixsoundboard.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void soup.neumorphism.NeumorphCardView.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void soup.neumorphism.NeumorphCardView.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
at com.jkcarraher.rainbowsixsoundboard.MainActivity.initButton(MainActivity.java:70)
at com.jkcarraher.rainbowsixsoundboard.MainActivity.onCreate(MainActivity.java:54)
at android.app.Activity.performCreate(Activity.java:7995)
at android.app.Activity.performCreate(Activity.java:7979)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Thank you for any insight you can provide!
Your NeumorphCardView is not initialized correctly, and that why it is throwing a NullPointerException. My guess is that you didn't set up your TabLayout in your activity_main.xml correctly. Specifically, what is your android:id="#+id/tabs" referring to? I don't think you successfully attached your fragment_defenders_tab to your activity_main successfully.
Your error is that your are using activity_main.xml in your MainActivity.java. However, the XML file you provided is called fragment_defenders_tab. You didn't reference this at all in your code.
So, the simple fix should be to just change this:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
To this:
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_defenders_tab);

Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference (Crash on button click)

hi am currently new to android studio and i have encounter this problem where am totally stuck and i have no ideal on how to solve the problem the app works fine just that when i click on convert button it crashes , Please help
The error i got
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.wxy.sg_cheapskate.MainActivity.onConvertButtonClicked(MainActivity.java:85)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Xml for the app
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.wxy.sg_cheapskate.converterActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Currency Converter"
android:id="#+id/CurrencyConverter"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:textSize="30dp"
android:textStyle="bold"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/NumberEditText"
android:hint="Enter Value!"
android:layout_below="#+id/CurrencyConverter"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/NumberEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/radioGroup"
android:layout_marginTop="5dp">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="USD TO SGD"
android:id="#+id/Ustosg"
android:checked="false"
android:textSize="25dp"
android:layout_marginTop="15dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RINGGIT TO SGD"
android:id="#+id/Mytosg"
android:checked="false"
android:textSize="25dp"
android:layout_marginTop="15dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YUAN TO SGD"
android:id="#+id/prctosg"
android:checked="false"
android:textSize="25dp"
android:layout_marginTop="15dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EURO TO SGD"
android:id="#+id/eutosg"
android:checked="false"
android:textSize="25dp"
android:layout_marginTop="15dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YEN TO SGD"
android:id="#+id/japtosg"
android:checked="false"
android:textSize="25dp"
android:layout_marginTop="15dp"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Convert"
android:id="#+id/convertBtn"
android:layout_below="#+id/radioGroup"
android:layout_centerHorizontal="true"
android:onClick="onConvertButtonClicked"
android:textStyle="bold"
android:textSize="25dp"
android:layout_marginTop="10dp"/>
Java
public class MainActivity extends AppCompatActivity implements ActionBar.TabListener, NavigationView.OnNavigationItemSelectedListener {
SectionPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
static final String LOG_TAG = "SlidingTabsBasicFragment";
private SlidingTabLayout mSlidingTabLayout;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar mToolbar;
private NavigationView mDrawer;
private EditText Number;
private RadioButton usd2sgd;
private RadioButton ringgit2sgd;
private RadioButton yuan2sgd;
private RadioButton euro2sgd;
private RadioButton yen2sgd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar)findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
mDrawer = (NavigationView) findViewById(R.id.main_drawer);
mDrawer.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mSectionsPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
Number = (EditText)findViewById(R.id.NumberEditText);
usd2sgd = (RadioButton)findViewById(R.id.Ustosg);
ringgit2sgd = (RadioButton)findViewById(R.id.Mytosg);
yuan2sgd = (RadioButton)findViewById(R.id.prctosg);
euro2sgd = (RadioButton)findViewById(R.id.eutosg);
yen2sgd = (RadioButton)findViewById(R.id.japtosg);
}
public void onConvertButtonClicked (View v) {
double value = new Double(Number.getText().toString());
if (usd2sgd.isChecked())
value = ConvertMoney.UsTosg(value);
if (ringgit2sgd.isChecked())
value = ConvertMoney.MyTosg(value);
if (yuan2sgd.isChecked())
value = ConvertMoney.PrcTosg(value);
if (euro2sgd.isChecked())
value = ConvertMoney.EuTosg(value);
if (yen2sgd.isChecked())
value = ConvertMoney.JapTosg(value);
Number.setText(new Double(value).toString());
}
Firstly focus on Lee's comment.
Second, cast String to double like this :
double value = Double.parseDouble("Double string here");
What Shubham is trying to say is rename your variable Number to something else, let's say num then change every occurrence of Number to num. Reason being, Number is a java class and cannot be used as a variable name.
num= (EditText) findViewById(R.id.NumberEditText);
...
double value = Double.parseDouble(num.getText());
...
num.setText(String.valueOf(value));
That exception is exclusively thrown if you're using an object without initializing it. Check whether you've correctly initialized the Number object. You could check whether Number is initialized or not by doing :
if(Number!=null){
//stuff here
}

Java, XML - onClick crashes my program

UPDATE: So I forgot to clarify this, but the button is at first non-existent on the App UNTIL dynamically added. Once the layout has been inflated with the button, the button then causes the crash. I apologize for the issues that came up from this development.
So there is a button that keeps crashing my program no matter what (unless I remove the onClick). I tested every line in my Java code to see what was causing it but even after leaving it empty, it still crashes it.
From my MainActivity.Java, the method that causes the crash:
public void changeState(View v) {
String owe = "O";
String debt = "D";
button = (Button) findViewById(R.id.decl);
if (button.getText().toString().equals("D")) {
button.setText("O");
} else {
button.setText(("D"));
}
}
Also from the Java file, the layout inflation method that creates the button causing the crashes:
public void create(MenuItem v) {
newContact = new LinearLayout(this);
newContact.setOrientation(LinearLayout.HORIZONTAL);
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = vi.inflate(R.layout.newcontact, null);
view.setOnTouchListener(new OnSwipeTouchListener(this) {
public void onSwipeRight() {
}
});
// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert);
insertPoint.addView(view);
}
The above Java code inflates this xml file:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#CCFFFF"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="81dp"
android:orientation="horizontal">
<EditText
android:id="#+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="12dp"
android:layout_weight="2"
android:ems="10"
android:hint="Name"
android:inputType="textPersonName"
android:padding="14dp"
android:shadowColor="#0066FF"
android:textColor="#000000"
android:textColorHint="#8F8F8F" />
<Button
android:id="#+id/decl"
android:layout_width="0dp"
android:layout_weight=".75"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="D"
android:textColor="#FFFFFF"
android:textSize="20dp"/>
<!--android:onClick="changeState"-->
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="vertical">\
<EditText
android:id="#+id/amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="(Ex 123.25)"
android:inputType="numberDecimal"
android:shadowColor="#0066FF"
android:textColor="#000000"
android:textColorHint="#8F8F8F"
android:textSize="16dp" />
<EditText
android:id="#+id/owed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="(Ex $, coffee)"
android:shadowColor="#0066FF"
android:textColor="#000000"
android:textColorHint="#8F8F8F"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="3dp"
android:orientation="vertical"
android:background="#CFCFCF"
/>
The Button:
<Button
android:id="#+id/decl"
android:layout_width="0dp"
android:layout_weight=".75"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="D"
android:textColor="#FFFFFF"
android:textSize="20dp"
android:onClick="changeState"
/>
Crash log
08-09 22:44:22.792 1951-1951/com.xephos.detra E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xephos.detra, PID: 1951
java.lang.IllegalStateException: Could not find a method changeState(View) in the activity class android.app.Application for onClick handler on view class android.widget.Button with id 'decl'
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at ...
Edit:
Put this in your MainActivity after setContentView():
public void create(MenuItem v) {
newContact = new LinearLayout(this);
newContact.setOrientation(LinearLayout.HORIZONTAL);
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = vi.inflate(R.layout.newcontact, null);
Button b = (Button)view.findViewById(R.id.decl);
if (b != null) {
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button)v;
if ("D".equals(b.getText().toString())) {
b.setText("O");
} else {
b.setText(("D"));
}
}
});
}
view.setOnTouchListener(new OnSwipeTouchListener(this) {
public void onSwipeRight() {
}
});
// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert);
insertPoint.addView(view);
}

Unable to start activity ComponentInfo Java.lang.nullExeption

I'm new in android and I have a program that gives data from localhost via HTTP and parse it to XML and show it in a list in android.But I can't switch to new page(the page that shows the list).My program has java.lang.NullPointerException exception and I can't found where It gives null.please help me and tell me what should I do.
this is error message:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sara.patientapplication/com.example.sara.patientapplication.ViewAllPatientActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.sara.patientapplication.ViewAllPatientActivity.onCreate(ViewAllPatientActivity.java:45)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)at android.app.ActivityThread.access$600(ActivityThread.java:130)at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:137)at android.app.ActivityThread.main(ActivityThread.java:4745)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:786)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)at dalvik.system.NativeStart.main(Native Method)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)at android.app.ActivityThread.access$600(ActivityThread.java:130)at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:137)at android.app.ActivityThread.main(ActivityThread.java:4745)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:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
this is my main layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".mainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show All Patients"
android:id="#+id/ShowAllPatients"
android:layout_marginTop="25dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add New Patient"
android:id="#+id/AddNewP"
android:layout_below="#+id/ShowAllPatients"
android:layout_marginTop="10dp"/>
</RelativeLayout>
and this is main Activity.there are a button and when I press it I expect go to a list but at that time exception Occurs.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Button ShowAllPatient=(Button)findViewById(R.id.ShowAllPatients);
Button AddNewPatient=(Button)findViewById(R.id.AddNewP);
ShowAllPatient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),ViewAllPatientActivity.class);
startActivity(i);
}
});
}
this my list layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/list"></ListView>
</LinearLayout>
and this is my the list activity:
public class ViewAllPatientActivity extends ListActivity {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser=new XMLParser();
static final String URL="http://localhost/AllPatient.php";
static final String Patient_ID="PatientId";
static final String First_Name="PatientFirstName";
static final String Last_Name="PatientLastName";
//static final String Blood_Type="BloodType";
//static final String Phone_Number="phoneNumber";
//static final String Practitioner_ID="practitionerId";
//static final String Email="Email";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.all_patient);
// String xml=parser.GetXml(URL);
Document doc=parser.DomElement("http://localhost/AllPatient.php");
NodeList nl = doc.getElementsByTagName(Patient_ID);
for (int i=0;i<nl.getLength();i++){
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(Patient_ID,parser.GetValue(e , Patient_ID));
map.put(First_Name,parser.GetValue(e,First_Name));
map.put(Last_Name,parser.GetValue(e,Last_Name));
// map.put(Blood_Type,parser.GetValue(e,Blood_Type));
// map.put(Phone_Number,parser.GetValue(e,Phone_Number));
// map.put(Email,parser.GetValue(e,Email));
// map.put(Practitioner_ID,parser.GetValue(e,Practitioner_ID));
menuItems.add(map);
}
ListAdapter adapter=new SimpleAdapter(this,menuItems,R.layout.list_item,
new String[]{Patient_ID,First_Name,Last_Name},new int[]{R.id.pid,R.id.fName,R.id.lName});
setListAdapter(adapter);
ListView lv=getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String Patient_id = ((TextView) view.findViewById(R.id.pid)).getText().toString();
String First_name = ((TextView) view.findViewById(R.id.fName)).getText().toString();
String Last_name = ((TextView) view.findViewById(R.id.lName)).getText().toString();
Intent in = new Intent(getApplicationContext(), SingleListPatient.class);
in.putExtra(Patient_ID, Patient_id);
in.putExtra(First_Name, First_name);
in.putExtra(Last_Name, Last_name);
startActivity(in);
}
});
}
and also I have some layout for a single list Item:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" />
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fName"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" /><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lName"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" /></LinearLayout>
and
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:padding="10dp"
android:id="#+id/firstN"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:padding="10dp"
android:id="#+id/lastN"
android:layout_toRightOf="#+id/firstN"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:padding="10dp"
android:text="Patient ID: "
android:id="#+id/paId"
android:layout_below="#+id/firstN"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:padding="10dp"
android:id="#+id/patientid"
android:layout_toRightOf="#+id/paId"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:padding="10dp"
android:text="Blood Type: "
android:id="#+id/bt"
android:layout_below="#+id/paId"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:padding="10dp"
android:id="#+id/btype"
android:layout_toRightOf="#+id/bt"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:padding="10dp"
android:text="Phone Number: "
android:id="#+id/pn"
android:layout_below="#+id/bt"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:padding="10dp"
android:id="#+id/pnum"
android:layout_toRightOf="#+id/pn"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:padding="10dp"
android:text="Email: "
android:id="#+id/em"
android:layout_below="#+id/pn"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold"
android:padding="10dp"
android:id="#+id/mail"
android:layout_toRightOf="#+id/em"/>
</RelativeLayout>
please help me.
thanks.
Change:
Intent i=new Intent(getApplicationContext(),ViewAllPatientActivity.class);
startActivity(i);
To:
Intent i=new Intent( mainActivity.this,ViewAllPatientActivity.class);
startActivity(i);
And check if:
Document doc is null

Categories

Resources