Onclick button Event in fragment - java

I've tried two types of code to get this to work and it keeps giving me force closes when I press the button to go into another Activity. I'm using a Fragment and there's a button in that Fragments code but I can't seem to get it to work.
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.androidbelieve.activity.LoginActivity;
import com.androidbelieve.helper.SQLiteHandler;
import com.androidbelieve.helper.SessionManager;
import java.util.HashMap;
public class PrimaryFragment extends Fragment {
private TextView txtName;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout rootView = (RelativeLayout) inflater.inflate(R.layout.primary_layout, container, false);
txtName = (TextView) rootView.findViewById(R.id.username);
btnLogout = (Button) rootView.findViewById(R.id.logout);
// SqLite database handler
db = new SQLiteHandler(getActivity().getApplicationContext());
// session manager
session = new SessionManager(getActivity().getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
// Displaying the user details on the screen
txtName.setText(name);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
Button button = (Button) rootView.findViewById(R.id.saleentry);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateDetail();
}
});
return rootView;
}
public void updateDetail() {
Intent intent = new Intent(getActivity(), SentFragment.class);
startActivity(intent);
}
I was trying to go to another page using button, but it always fail.
Here is my stacktrace..this is the result when i used onclicklistener
04-07 22:42:37.285 27777-27777/com.androidbelieve.drawerwithswipetabs >E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidbelieve.drawerwithswipetabs, PID: 27777
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, >com.android.systemui=overlay:system}
android.content.ActivityNotFoundException: Unable to find explicit >activity class >{com.androidbelieve.drawerwithswipetabs/com.androidbelieve.drawerwithswipet>abs.SentFragment}; have you declared this activity in your >AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1801)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1514)
at android.app.Activity.startActivityForResult(Activity.java:3930)
at android.app.Activity.startActivityForResult(Activity.java:3890)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:907)
at android.support.v4.app.Fragment.startActivity(Fragment.java:916)
at com.androidbelieve.drawerwithswipetabs.PrimaryFragment.updateDetail(PrimaryFragment.java:75)
at com.androidbelieve.drawerwithswipetabs.PrimaryFragment$2.onClick(PrimaryFragment.java:67)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21156)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5456)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

firstly you have to add frame layout in your xml layout.
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
then use this code on click
Button button = (Button) rootView.findViewById(R.id.saleentry);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new SentFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.remove(new PrimaryFragment ());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});

Related

Android app crashes after RatingBar DialogFragment closes

The purpose of my app is to retrieve a value out of 5 from a rating bar through a custom dialog and display it in a TextView in the main activity. When I tap the button I've outlined in red in the image below, the app crashes and shuts down.
The app consists of 2 classes/activities. The main activity and the custom dialog activity.
The code for both files can be found below:
MainActivity.java:
package com.example.mealrater;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements MealRaterDialog.SaveRating {
public EditText restaurant, dish;
public TextView ratingDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
restaurant = findViewById(R.id.etRestaurant);
dish = findViewById(R.id.etDish);
RateMealButton();
}
#Override
public void finishMealRaterDialog(String rating) {
ratingDisplay = findViewById(R.id.tvRatingDisplay);
ratingDisplay.setText(rating);
}
private void RateMealButton() {
Button rate = findViewById(R.id.btnRate);
rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
MealRaterDialog mealRaterDialog = new MealRaterDialog();
mealRaterDialog.show(fm, "RateMeal");
}
});
}
}
MealRaterDialog.java:
package com.example.mealrater;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RatingBar;
import androidx.fragment.app.DialogFragment;
public class MealRaterDialog extends DialogFragment {
String rating;
public interface SaveRating {
void finishMealRaterDialog(String rating);
}
public MealRaterDialog() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.meal_rater, container);
getDialog().setTitle("Rate your meal");
Button save = view.findViewById(R.id.btnSaveRating);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RatingBar ratingBar = view.findViewById(R.id.rbMeal);
rating = String.valueOf(ratingBar.getRating());
SaveItem(String.valueOf(rating));
}
});
return view;
}
private void SaveItem(String rating) {
MealRaterDialog.SaveRating activity = (MealRaterDialog.SaveRating) getActivity();
activity.finishMealRaterDialog(rating);
getDialog().dismiss();
}
}
I'm new to Android Studio and would also like to receive tips on how to improve this question. Thank you.
Logcat error:
2021-04-28 16:04:35.240 18144-18144/com.example.mealrater E/libc: Access denied finding property "ro.serialno"
2021-04-28 16:04:42.709 18144-18144/com.example.mealrater E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mealrater, PID: 18144
java.lang.NullPointerException: Attempt to invoke virtual method 'float android.widget.RatingBar.getRating()' on a null object reference
at com.example.mealrater.MealRaterDialog$1.onClick(MealRaterDialog.java:35)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
There are severall fixes for this.
First of all, You should define the ratingBar widget before the onClick. Right now it is creating the variable each time you click on the button. Define it after Button save = view.findViewById(R.id.btnSaveRating); line.
Second of all, As you are using a Dialog fragment, all the logic of the click should be called on the override funtion called onViewCreated(). Not in the OnCreateView() as you are doing right now. Let me know if it works for you.
I've tried to reproduce this error and I find a solution that works for me.
You have to create the rating bar with the view (outside of the listener).
This should be your onCreateView in your MealRaterDialog.java class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.meal_rater, container);
getDialog().setTitle("Rate your meal");
Button save = view.findViewById(R.id.btnSaveRating);
RatingBar ratingBar = view.findViewById(R.id.rbMeal);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rating = String.valueOf(ratingBar.getRating());
SaveItem(String.valueOf(rating));
}
});
return view;
}
Hope it works!

How to call a Fragment from activity. When the view doesn't belong to corresponding layout

In my scenario, I've a fragmemt where there are list of options(Recycler view) that a user can select.
Example: my profile, change password, logout.
If the user clicks the change password from the Fragment A recycler view adapter, then the user is navigated to Activity A. Where the user can change the password. once submit button is clicked in Activity A then user should be navigated to the Fragment A.
Code in Activity A
package com.example.expresso.sapthagiri.yogirproduct;
import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ChangePassword extends AppCompatActivity {
Button submit, back;
EditText old_password, new_password, re_enter_password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_password);
submit = findViewById(R.id.submit);
back = findViewById(R.id.backButton);
old_password = findViewById(R.id.oldPassword);
new_password = findViewById(R.id.newPassword);
re_enter_password = findViewById(R.id.reEnterPassword);
final ProfileFragment profileFragment = new ProfileFragment();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setFragment(profileFragment);
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setFragment(profileFragment);
}
});
}
private void setFragment(android.support.v4.app.Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment).commit();
}
}
Actual issue as of now: I'm trying to load the fragment A but R.id.main_frame doesn't belong to setContentView(R.layout.activity_change_password);.
private void setFragment(android.support.v4.app.Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment).commit();
}
Kindly help me overcome to issue. Million thanks in advance! :)
You are confusing the navigation architecture of android. When you start Activity A it adds Activity A to the activity stack. Therefore the Activity with Fragment A is still in that stack of activities. So all you have to do is finish the activity A. Which will basically do a pop operation on that activity stack.
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed(); //or finish()
}
});
This will do the trick.

onClick method not found

I'm new to this and i'm doing an app for a university project and I wanted to put a VideoView in my app, so I watched this video ("https://www.youtube.com/watch?v=SrPHLj_q_OQ&t=421s") and did it and worked. But then I add to copy the code from content_main.xml to a fragment and it stopped working and giving an error on the "android:onClick" on the Button. And when I press CTRL+F1 to inspect it says this:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
Heres my xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:background="#003e6f"
android:orientation="vertical"
tools:context=".InicioFragment">
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_gravity="center_horizontal"
android:layout_height="197dp" />
<Button
android:id="#+id/button2"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#FF6600"
android:text="Play"
android:onClick="videoplay"
android:textColor="#ffffff" />
<ImageView
android:id="#+id/imagem2"
android:layout_width="match_parent"
android:layout_height="360dp"
android:layout_alignParentBottom="true"
android:adjustViewBounds="false"
android:background="#drawable/tech3" />
</LinearLayout>
Heres my java:
package intro.android.migueloliveiraapp;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
clk = (Button) findViewById(R.id.button2);
videov = (VideoView) findViewById(R.id.videoView);
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);
//Carregar o layout do fragent incial "InicioFragment"
InicioFragment inicioFragment = new InicioFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment, inicioFragment, inicioFragment.getTag())
.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_oliveira) {
Quem_Oliveira quem_oliveiraFragment = new Quem_Oliveira();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
quem_oliveiraFragment, quem_oliveiraFragment.getTag())
.commit();
Toast.makeText(this, "Oliveira", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_profissao) {
Profissao profissaoFragment = new Profissao();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
profissaoFragment, profissaoFragment.getTag())
.commit();
Toast.makeText(this, "Profissão", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_feitos) {
Principais_feitos principais_feitosFragment = new Principais_feitos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
principais_feitosFragment, principais_feitosFragment.getTag())
.commit();
Toast.makeText(this, "Principais Feitos", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_academicas) {
Habilitacoes_Academicas habilitacoes_academicasFragment = new Habilitacoes_Academicas();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
habilitacoes_academicasFragment, habilitacoes_academicasFragment.getTag())
.commit();
Toast.makeText(this, "Habilitações Académicas", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_galeria) {
Galeria galeriaFragment = new Galeria();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
galeriaFragment, galeriaFragment.getTag())
.commit();
Toast.makeText(this, "Galeria", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_contactos) {
Contactos contactosFragment = new Contactos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
contactosFragment, contactosFragment.getTag())
.commit();
Toast.makeText(this, "Contactos", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//video view
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Heres my InicioFragment java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
}
heres my updated InicioFragment.java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.net.Uri;
import android.widget.Button;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
clk = (Button) view.findViewById(R.id.button);
videov = (VideoView) view.findViewById(R.id.videoView);
// bind the views here.
Button button2 = view.findViewById(R.id.button);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
You can use this for click.
Button mPlayVideo;
//In oncreate
mPlayVideo = findViewById(R.id.button2);
mPlayVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
In your xml your tools:context=".InicioFragment refers to your fragment and not your activity.
Your method is found inside the activity and not the fragment class and this is why are getting this error.
You can check Call an activity method from a fragment
But I can recommend using the onClick attribute inside your activities and inside fragment use normal click listener:
View view = findViewById(R.id.viewId);
view .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
This is because you created videoplay() method inside your MainActivity.java . You should put your videoplay() method into the InicioFragment.java as it is the corresponding file for the xml layout you have mentioned above.
Initialize your variables like bellow inside your onCreateView method on InicioFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inicio, container, false);
Button btn1 = view.findViewById(R.id.button_id);
.....
.....
return view;
}
public void videoplay(View v){
.........
.....
}
The following error:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
means that you forget to add the corresponding method in your Activity class when using android:onClick="videoplay" attribute. So, you need to add the following method to your activity:
public void videoplay(View v){
// do something here.
}
The most important part is, android:onClick tag is only working when you're using it inside the content layout of Activity.. So, android:onClick doesn't work when you're using it inside the fragment layout. You need to use the onClickListener instead.
You need to bind the view and add the onClickListener with something like this:
public class InicioFragment extends Fragment {
public InicioFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// bind the views here.
Button button2 = view.findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
}
Pay attention on your xml file that this file's context is your InicioFragment (tools:context=".InicioFragment" )
Therefore, videoplay(View v) should be inside your InicioFragment class.
That's the reason why is not found. It won't search on your MainActivity.
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.testclassfragment, container, false);
Button clk = (Button) view.findViewById(R.id.button);
VideoView videov = (VideoView) view.findViewById(R.id.videoView);
return view;
}
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Since you also have a variable for your button another option is to do:
clk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TESTING", "Clicked");
}
});

Null pointer exception when onOptionsItemSelected is called

The java code is as follows: The layout seems fine. The only problem seems to occur when i click the navigation bar icon on the top left corner.
package com.example.chirag.carparlour;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle abdt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button book = (Button)findViewById(R.id.book);
Button sub = (Button)findViewById(R.id.sub);
Button offers = (Button)findViewById(R.id.offers);
Button support = (Button)findViewById(R.id.support);
Button comp = (Button)findViewById(R.id.comp);
DrawerLayout dl = (DrawerLayout)findViewById(R.id.drawerlayout);
ActionBarDrawerToggle abdt = new ActionBarDrawerToggle(this, dl , R.string.Open, R.string.Close);
dl.addDrawerListener(abdt);
abdt.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, bookawash.class);
startActivity(intent);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, subscriptions.class);
startActivity(intent);
}
});
offers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
support.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
comp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(abdt.onOptionsItemSelected(item))
{return true;}
return super.onOptionsItemSelected(item);
}}
and the error in the log is as follows:
FATAL EXCEPTION: main
Process: com.example.chirag.carparlour, PID: 4879
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.app.ActionBarDrawerToggle.onOptionsItemSelected(android.view.MenuItem)' on a null object reference
at com.example.chirag.carparlour.MainActivity.onOptionsItemSelected(MainActivity.java:86)
at android.app.Activity.onMenuItemSelected(Activity.java:2914)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:408)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:198)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:113)
at android.support.v7.widget.ToolbarWidgetWrapper$1.onClick(ToolbarWidgetWrapper.java:187)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21166)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Whenever I click the navigation icon on the top left corner, the app crashes and it shows this error. It works fine if you just slide the screen. And when I do not have this method, the app doesn't crash but the navigation bar doesn't show either. This hasn't happened before.
Please help!
I think the problem is this: (in the onCreate):
ActionBarDrawerToggle abdt = new ActionBarDrawerToggle(this, dl , R.string.Open, R.string.Close);
Switch to:
abdt = new ActionBarDrawerToggle(this, dl , R.string.Open, R.string.Close);

Opening activity from fragment force close error

So today I created tab view bar and fragments and added some image buttons to one of the fragments.
When I add android:onClick="name"on the button code and write Intent in .java file, it gives me force close error when I click on that button.
Here's my code:
fragment.xml
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnProgramiPL5x5"
android:minHeight="80dp"
android:background="#mipmap/btn_programi_pl_5x5"
android:onClick="ProgramiPowerlifting5x5"/>
fragment.java
package hr.app.liftme.liftmehr;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
/**
* A simple {#link Fragment} subclass.
*/
public class FragmentPowerlifting extends Fragment {
public FragmentPowerlifting() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_powerlifting, container, false);
}
ProgramiPowerlifting5x5.java
package hr.app.liftme.liftmehr;
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;
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_programi_powerlifting5x5);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
}
}
Error i get is this:
01-26 23:00:44.766 14491-14491/hr.app.liftme.liftmehr E/AndroidRuntime: FATAL EXCEPTION: main
Process: hr.app.liftme.liftmehr, PID: 14491
java.lang.IllegalStateException: Could not find method ProgramiPowerlifting5x5(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'btnProgramiPL5x5'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
I don't know what is the problem, when I link two activities I use this, name.class, but that didn't worked in this case so i used getActivity and it still does not work.
I would really appreciate help!
Thanks!
The problem here is:
Could not find method ProgramiPowerlifting5x5(View) in a parent or ancestor Context
The onClick attribute refers to the parent Context (as parent Activity) so the fragment's method is not triggered and not handled by this attribute.
You have to handle the click in the Activity:
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
...
// change the method's name to avoid confusion with constuctor
public void ProgramiPowerLifting(View view){
Intent intent = new Intent(this, ProgramiPowerlifting5x5.class);
startActivity(intent);
}
}
Or trigger the same method into your fragment:
public class ProgramiPowerlifting5x5 extends AppCompatActivity {
private ProgramPowerFragment fragment;
...
public void ProgramiPowerLifting(View view){
fragment.ProgramiPowerLifting(view);
}
}
This great answer uses a callback interface which, personally, I'd suggest. Or you can easily forget the onClick xml attribute and do it dynamically with setOnClickListener().
So, let's try the easy way:
public class FragmentPowerlifting extends Fragment {
public FragmentPowerlifting() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// store the layout in a view variable
View v = inflater.inflate(R.layout.fragment_powerlifting, container, false);
// use this view ("v") to retrieve elements on the layout by its id
ImageButton imgButton = (ImageButton) v.findViewById(R.id.btnProgramiPL5x5);
// set a listener to the button
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// open a new activity when onClick is triggered
Intent intent = new Intent(getActivity(), ProgramiPowerLiftingActivity.class);
startActivity(intent);
}
}
// return the inflated view to display it
return v;
}
}

Categories