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!
Related
My first thread here - sorry if the text formatting is bad.
I use Android Studio 3.1.3 API27 and work on an app for Smartphone.
The app currently consists of 1 activity (split in 3 fragments), a second activity and 5 xml files.
By using a ViewPager, I'm able to swipe through the 3 fragments.
The 2nd fragment (middle fragment) contains 2 buttons that each open the 2nd activity, which contains many color buttons.
When clicking on the color buttons, I can change the background colors of the 1st fragment.
After choosing a color, the 2nd activity gets closed and I'm back in activity 1 -> fragment2.
It works, but the PROBLEM is that I always have to swipe to the 3rd fragment,
then back to the 2nd and then to the 1st.
If I don't do this, the colors of fragment 1 will remain the old ones.
Now I'm looking for a way to update the layout of fragment 1 as soon as I press a color button of activity 2.
I already tried this:
when writing the SharedPreferences (Activity2), I use editor.apply() instead of editor.commit()
when reading the SharedPreferences (Activity1 -> Fragment1), I use Context.MODE_MULTI_PROCESS instead of Context.MODE_PRIVATE
using viewpage.setOffscreenPageLimit(0); in the MainActivity inside of my public void SetUpViewPager(ViewPager viewpage) method.
Nothing helped, though.
This is how it looks like:
MainActivity.java (Activity 1):
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
ViewPager vp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager vp = findViewById(R.id.vp);
SetUpViewPager(vp);
}
public void SetUpViewPager(ViewPager viewpage)
{
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.AddPageFragment(new Page_1(), "Page 1");
Adapter.AddPageFragment(new Page_2(), "Page 2");
Adapter.AddPageFragment(new Page_3(), "Page 3");
viewpage.setOffscreenPageLimit(0);
viewpage.setAdapter(Adapter);
}
public class MyViewPagerAdapter extends FragmentPagerAdapter
{
private List<Fragment> MyFragment = new ArrayList<>();
private List<String> MyPageTitle = new ArrayList<>();
public MyViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
public void AddPageFragment(Fragment Frag, String Title)
{
MyFragment.add(Frag);
MyPageTitle.add(Title);
}
#Override
public Fragment getItem(int i)
{
return MyFragment.get(i);
}
#Nullable
#Override
public CharSequence getPageTitle(int position)
{
return MyPageTitle.get(position);
}
#Override
public int getCount()
{
return 3;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Page_1.java (Activity 1 -> Fragment 1):
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;
public class Page_1 extends Fragment
{
int backgroundColorLeft, backgroundColorRight, textColorLeft, textColorRight; // Variables for SharedPreferences
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageOne = inflater.inflate(R.layout.page1, container, false); // Link view to layout?
return PageOne;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
SharedPreferences prefs = getActivity().getSharedPreferences("bgColor", Context.MODE_MULTI_PROCESS); // Load saved shared file
backgroundColorLeft = prefs.getInt("backgroundColorLeft", backgroundColorLeft); // Load saved background color for left layout
textColorLeft = prefs.getInt("textColorLeft", textColorLeft); // Load saved text color for left layout
backgroundColorRight = prefs.getInt("backgroundColorRight", backgroundColorRight); // Load saved background color for right layout
textColorRight = prefs.getInt("textColorRight", textColorRight); // Load saved text color for right layout
RelativeLayout relLayoutLeft = getActivity().findViewById(R.id.rel_layout_left); // Link variable to ID of left layout
relLayoutLeft.setBackgroundColor(backgroundColorLeft); // Change background color of left layout
TextView tvLeft = getActivity().findViewById(R.id.tv_left); // Link variable to ID
tvLeft.setTextColor(textColorLeft); // Change text color of left layout
RelativeLayout relLayoutRight = getActivity().findViewById(R.id.rel_layout_right); // Link variable to ID of right layout
relLayoutRight.setBackgroundColor(backgroundColorRight); // Change background color of right layout
TextView tvRight = getActivity().findViewById(R.id.tv_right); // Link variable to ID
tvRight.setTextColor(textColorRight); // Change text color of right layout
super.onActivityCreated(savedInstanceState);
}
}
Page_2.java (Activity 1 -> Fragment 2):
package com.example.konstantin.clipcodes_swiping;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import static android.content.Context.MODE_PRIVATE;
public class Page_2 extends Fragment
{
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageTwo = inflater.inflate(R.layout.page2, container, false);
Button buttonLeft = PageTwo.findViewById(R.id.button_left); // Link variable to ID of left button
buttonLeft.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int pos = 1; // Set position to left
setPosition(pos); // Load setColor method and send 2 color values
}
});
Button buttonRight = PageTwo.findViewById(R.id.button_right); // Link variable to ID of right button
buttonRight.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int pos = 2; // Set position to right
setPosition(pos); // Load setColor method and send 2 color values
}
});
return PageTwo;
}
public void setPosition (int pos) // Start second activity to choose colors
{
Intent intentPos = new Intent(getActivity(), Page_4_Colors.class); // Create intent for current Activity and target activity
SharedPreferences prefs = getActivity().getSharedPreferences("bgColor", Context.MODE_MULTI_PROCESS); // Create new SharedPreferences instance
SharedPreferences.Editor editor = prefs.edit(); // Assign variable to editor function
editor.putInt("position", pos); // Write selected position (int) inside of editor
editor.apply(); // Save values, close process
getActivity().startActivity(intentPos); // Start second activity
}
}
Page_3.java (Activity 1 -> Fragment 3):
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Page_3 extends Fragment
{
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageThree = inflater.inflate(R.layout.page3, container, false);
return PageThree;
}
}
Page_4_Colors.java (Activity 2):
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class Page_4_Colors extends Activity
{
int pos;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.page4_colors);
SharedPreferences prefs = getSharedPreferences("bgColor", MODE_MULTI_PROCESS); // Load saved shared file
pos = prefs.getInt("position", pos); // Load saved position (int)
Log.wtf("Position", String.valueOf(pos)); // Show pos value in Log
Button buttonWhite = findViewById(R.id.button_white);
buttonWhite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.white), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonYellow = findViewById(R.id.button_yellow);
buttonYellow.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.yellow), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonOrange = findViewById(R.id.button_orange);
buttonOrange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.orange), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonRed = findViewById(R.id.button_red);
buttonRed.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.red), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonGreen = findViewById(R.id.button_green);
buttonGreen.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.green), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonBlue = findViewById(R.id.button_blue);
buttonBlue.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.blue), getResources().getColor(R.color.white)); // Load setColor method and send 2 color values
}
});
}
public void setColor (int backgroundColor, int textColor) // Write color values into SharedPreferences
{
SharedPreferences prefs = getSharedPreferences("bgColor", MODE_MULTI_PROCESS); // Create new SharedPreferences instance
SharedPreferences.Editor editor = prefs.edit(); // Assign variable to editor function
if (pos == 1)
{
editor.putInt("backgroundColorLeft", backgroundColor); // Write background color (int) inside of editor
editor.putInt("textColorLeft", textColor); // Write text color (int) inside of editor
}
if (pos == 2)
{
editor.putInt("backgroundColorRight", backgroundColor); // Write background color (int) inside of editor
editor.putInt("textColorRight", textColor); // Write text color (int) inside of editor
}
editor.apply(); // Save values, close process
this.finish(); // Close this activity
}
}
Thanks for any help!
use EventBus
unregister and register EventBus in Page_1 onStop() and onStart()
EventBus.getDefault().unregister(this)
EventBus.getDefault().register(this)
and use this for post the value
EventBus.getDefault().post(new MessageEvent("Change Color"));
and this function will handle the MessageEvent
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
//change the color here
//add this function in Page_1
}
when you update the value of color. put in MessageEvent documentation
You can update the UI (or at least the color related part) for each fragment in the onResume() method, thus, when you return from the second activity, it will refresh.
When a Fragment is made visible (i.e., the selected page in your ViewPager), its setUserVisibleHint() method is called. You can override that method in your Fragment and use it to trigger a refresh.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//you can check if the color is changed then refresh the fragment if not then don't do anything
//here you should refresh your fragment , this will called every time you
//view this fragment in all cases even if you didn't move to the
//third tab
}
}
How To Refresh A Fragment
Fragment currentFragment = getFragmentManager().findFragmentByTag("YourFragmentTag");
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();
This question already has answers here:
I'm having problems with running the code on my device [duplicate]
(3 answers)
Closed 4 years ago.
I am currently getting these errors when running my code on a device
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 9401
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:46)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
now based on what I see here are the libraries for the code its stating in the error. Please help im a beginner
Events.java
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
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.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.app.FragmentManager;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events,
container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View
view, int position, long id) {
Intent intent = new Intent(view.getContext(),
AddEvent.class);
Uri currentVehicleUri =
ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton)
getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),
AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity
context
EventContract.EventEntry.CONTENT_URI, // Provider
content URI to query
projection, // Columns to include in the
resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
Fragment Java(it says im getting an error around here:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
if (mHost != null) {
writer.print(prefix); writer.print("mHost=");
writer.println(mHost);
}
if (mParentFragment != null) {
writer.print(prefix); writer.print("mParentFragment=");
writer.println(mParentFragment);
In conclusion I'm trying to run the app but everytime I go into a certain section, in this case being Events.java being nav_events.xml layout, I keep getting the error and don't know how to fix it
Your error is found on line 46 of your Events.java file.
You're inflating a view and declaring it a ListView in Java (on line 46) when it seems to be a LinearLayout in your XML file.
Also right after that you're using getView(). You can only use that function correctly after onCreateView() has returned a View, definitely not within it.
EDIT after comment:
You haven't returned the View yet as you can't execute any code after a return statement.
Now without your layout file I can only speculate but probably replace
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
with
View rootView = (LinearLayout) inflater.inflate(R.layout.nav_events, container, false);
Then replace all occurrences of getView() in that code block with rootView.
And at the very end
return rootView;
I caught the error message
"5-14 12:39:13.104 2518-2518/com.example.fdai3744.neueleereapp E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.fdai3744.neueleereapp, PID: 2518 java.lang.RuntimeException: Unable to instantiate activity ..."
and here's my Java Code
package com.example.fdai3744.neueleereapp;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button button_1 = (Button) findViewById(R.id.button1); //Button
public TextView text1 = (TextView)findViewById(R.id.text1); // Textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button
#Override
public void onClick(View v) {
text1.setText("Button 1 wurde geklickt!");
}
});
}
}
If I start my App the emulator throws an error message "App has stopped". How should I prevent this error?
Well, your view hierarchy needs to be alive before your retrieve individual Views from it and the method setContentView() brings it to life(or instantiates it).
How?
setContentView(View) is a method exclusively available for Activity.
Internally it calls the setContentView(View) of Window. This method
sets the activity content to an explicit view. This view is placed
directly into the activity's view hierarchy. Calling this function
"locks in" various characteristics of the window that can not, from
this point forward, be changed. Hence it is called only once.
So, instead of initializing the Views as instance variables, instantiate them inside onCreate() after setContentView().
Also read: Android: setContentView and LayoutInflater
caused by
public Button button_1 = (Button) findViewById(R.id.button1); //Button
public TextView text1 = (TextView)findViewById(R.id.text1); // Textview
never assign view before setContentView() is called
your modified code
package com.example.fdai3744.neueleereapp;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button button_1;
public TextView text1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1 = (Button) findViewById(R.id.button1); //Button
text1 = (TextView)findViewById(R.id.text1); // Textview
button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button
#Override
public void onClick(View v) {
text1.setText("Button 1 wurde geklickt!");
}
});
}
}
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();
}
});
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;
}
}