Basic info
I am using the Settings Activity and navigation menu : and i have button to display the data (which is the number) from the settings to a textview. It's a sms app
Problem
I have the textview in context_main (The first screen when you start the app) But i would really like to have the textview in my fragment and when i press the button "the onlick" will display the value from settings.
The Button is in the fragment. and when i click the button it works^^ for the context_main se below code.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = prefs.getString("example_text", "");
radertst.setText(restoredText);
}
But when i press a button to send a sms and i linked it with the textfield for where the number is but then i get this.
09-16 20:47:03.501 5389-5389/c.timno.smsgsm20 E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.timno.smsgsm20, PID: 5389
java.lang.NullPointerException
at c.timno.smsgsm20.FirstFragment$1$override.onClick(FirstFragment.java:102)
at c.timno.smsgsm20.FirstFragment$1$override.access$dispatch(FirstFragment.java)
at c.timno.smsgsm20.FirstFragment$1.onClick(FirstFragment.java:0)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18475)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
This my
MainActivity java class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TextView tstnr;
TextView radertst;
EditText nantxt;
Button sendSMSaon;
EditText aonTxt;
TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
nantxt =(EditText) findViewById(R.id.nummer);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The fragment java file
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText numTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
TextView ifirt;
TextView tstnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
numTxt = (EditText)view.findViewById(R.id.nummer);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
tstnr = (TextView) view.findViewById(R.id.numretladd);
msgTxt.setVisibility(View.INVISIBLE);
aonTxt.setVisibility(View.INVISIBLE);
aoffTxt.setVisibility(View.INVISIBLE);
rela1txt.setVisibility(View.INVISIBLE);
rela2txt.setVisibility(View.INVISIBLE);
//testnedan
LayoutInflater lf = getActivity().getLayoutInflater();
view = lf.inflate(R.layout.first_layout, container, false);
//ovantest
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumber = nyanumtxt.getText().toString();
sendMsg(theNumber, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgrela2);
}
}
);
return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
if you look at
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
The numTxt is where i want the value to be loaded and it's in the first layout xml not context_main. So for some reason it wont be loaded there. Imgur image
If I'm understanding you correctly, R.id.raderanumtxt is in the MainActivity's layout file and not FirstFragment's.
That means that it won't be found in the onCreateView() method of FirstFragment the way you're accessing it. The view object there is the layout you just loaded:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt); // <- this assignment won't work
...
}
You're also inflating R.layout.first_layout twice, which is unnecessary.
To get access to a View in the Activity, you can do something like this:
View view = getActivity().findViewById(R.id.viewid);
EDIT:
Without seeing your layouts, I can't be sure, but try and replace:
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt);
... with:
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
That way you're looking for R.id.raderanumtxt in the entire Activity layout. This will only work if the Activity is available and the layout has already been added, so to be safer I'd move this assignment to onViewCreated() instead of onCreateView().
Related
I do everything according to great guides from Youtube. https://www.youtube.com/watch?v=W-L6Cr2WP18 - I recommend. Unfortunately, instead of activity, I use a fragment and I have an error.
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private String userEmail, userName;
private GoogleApiClient googleApiClient;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore rootRef;
private FirebaseAuth.AuthStateListener authStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(googleSignInAccount != null){
String userEmail = googleSignInAccount.getEmail();
String userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
firebaseAuth = FirebaseAuth.getInstance();
rootRef = FirebaseFirestore.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser == null){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
private void signOut(){
Map<String, Object> map = new HashMap<>();
map.put("tokenId", FieldValue.delete());
rootRef.collection("users").document(userEmail).update(map).addOnSuccessListener(new OnSuccessListener<Void>(){
#Override
public void onSuccess(Void aVoid){
firebaseAuth.signOut();
if(googleApiClient.isConnected()){
Auth.GoogleSignInApi.signOut(googleApiClient);
}
}
});
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
firebaseAuth.addAuthStateListener(authStateListener);
}
#Override
protected void onStop() {
super.onStop();
if(googleApiClient.isConnected()){
googleApiClient.disconnect();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//wybieranie fragmentu
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new Menu1Goals();
break;
case R.id.nav_menu2:
fragment = new Menu2();
break;
case R.id.nav_menu3:
fragment = new Menu3();
break;
}
//replacing the fragment - zmienianie fragmentów
//Transakcja fragmentu to seria zmian dotyczących fragmentu, które chcemy wykonać w tym samym momencie
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
//przekazywanie wybranego fragmentu do interfejsu
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
//------------------------------------Top Menu----------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
//getting the search view from the menu
MenuItem searchViewItem = menu.findItem(R.id.menuSearch);
//getting search manager from systemservice
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
//getting the search view
final SearchView searchView = (SearchView) searchViewItem.getActionView();
//you can put a hint for the search input field
searchView.setQueryHint("Czego wspólnie poszukamy?");
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//by setting it true we are making it iconified
//so the search input will show up after taping the search iconified
//if you want to make it visible all the time make it false
searchView.setIconifiedByDefault(true);
//here we will get the search query
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//do the search here
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_button:
signOut();
return true;
case R.id.action_settings:
//settings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//------------------------------------------------------------------------------------------
Fragment:
public class DailyFragment extends Fragment{
Toast toast;
private FirebaseFirestore rootRef;
private CollectionReference dailyGoalsRef;
private String userEmail, userName;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_daily, container, false);
FloatingActionButton fab2 = layout.findViewById(R.id.fab2);
fab2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Zadania na dzisiaj");
final EditText editText = new EditText(getContext());
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
editText.setHint("Podaj cel");
editText.setHintTextColor(Color.GRAY);
builder.setView(editText);
builder.setPositiveButton("Utwórz", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nazwa_celu = editText.getText().toString().trim();
addGoalsList(nazwa_celu);
}
});
builder.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");
return layout;
}
private void addGoalsList(String nazwa_celu){
String goalsListId = dailyGoalsRef.document().getId();
GoalsModel goalsModel = new GoalsModel(goalsListId, nazwa_celu, userName);
dailyGoalsRef.document(goalsListId).set(goalsModel).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "Lista celów stworzona pomyślnie!");
}
});
}
}
To solve this, change the following lines of code:
if(googleSignInAccount != null){
String userEmail = googleSignInAccount.getEmail();
String userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
with
if(googleSignInAccount != null){
userEmail = googleSignInAccount.getEmail();
userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
This fields are already declared as global.
You are using in your fragment the following line of code:
dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");
Where the userEmail is null. This is happening because you are not passing the userEmail from the activity to the fragment. Just declaring it as a global variable does not solve the problem.
To solve this, create a method in your activity that returns the userEmail.
public String getUserEmail() {return userEmail;}
And in your fragment, create a String field String userEmail as global and call that method like this:
userEmail = ((MainActivity) getActivity()).getUserEmail();
I want my imagebutton to hightlight it self, as the normal glow effect when a "normal" button is pressed. So i tried to put the image in, but then there is a "gray field" in the back of the image so i made it transparent so only the image will show but then the glow effect disappeared. Is there a solution to this? :)
please see imgur image as a example- Example image here
if it is to "hard" I can live with the gray field behind the image but is it possible then to make it green with the same highlight effect?
Should i put the code in MainActivity or my fragment java?
Fragment java
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
//TextView nya;
//TextView nsp;
TextView tstnr;
#SuppressWarnings("ResourceType")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
return inflater.inflate(R.layout.first_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
view = getActivity().findViewById(R.id.content_frame);
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
//nsp = (TextView) view.findViewById(R.id.nummertestsp);
// tstnr = (TextView) view.findViewById(R.id.numretladd);
// view = getActivity().findViewById(R.id.content_frame);
taframnummer.setVisibility(INVISIBLE);
msgTxt.setVisibility(INVISIBLE);
aonTxt.setVisibility(INVISIBLE);
aoffTxt.setVisibility(INVISIBLE);
rela1txt.setVisibility(INVISIBLE);
rela2txt.setVisibility(INVISIBLE);
sendSMSaoff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgrela2);
}
}
);
// return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
Here my MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//TextView tstnr;
TextView radertst;
Button sendSMSaon;
EditText aonTxt;
//TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
// nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
else if (id == R.id.nav_share) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://hellmertz.se"));
startActivity(browserIntent);
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Put the imageView that you want to highlight above a View with bright color and set the visibility of the view equal to View.GONE. Now with your ImageButton
((ImageButton)findViewById(R.id.myImageBtn)).setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
myView.setVisibility(View.VISIBLE);
break;
}
case MotionEvent.ACTION_UP:
myView.setVisibility(View.GONE);
break;
// Your action here on button click
case MotionEvent.ACTION_CANCEL: {
myView.setVisibility(View.GONE);
break;
}
}
return true;
}
});
You can user selector drawable and have 3 different button drawables for each state. Create these file is drawables folder and add this line to button android:background="#drawable/button_selector"
button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed -->
<item android:drawable="#drawable/camera_button_hold" android:state_pressed="true"/>
<!-- focused -->
<item android:drawable="#drawable/camera_button_hold" android:state_focused="true"/>
<!-- default -->
<item android:drawable="#drawable/camera_button_normal"/>
</selector>
camera_button_hold.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#673ab7"/>
</shape>
camera_button_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="#673ab7"/>
</shape>
I'm trying to implement a splash screen on my app. After the loading of the splash screen, I have two issues.
If the user is connected, an activity is started. If not, an other is started.
But, with my implementation, when the user is connected, the splash screen is very long (8 or 9 sec), but I don't know why.
That is my first class which check if the user is connected, and it load some shared preferences? So maybe it's that?
public class AnnaActivity extends AppCompatActivity {
public PrefManager pref;
private AllRequest req;
private static final String REQUEST_TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.pref = new PrefManager(getApplicationContext());
boolean isco = pref.getIsConnect();
if (isco) {
Log.e("SPLASH", "IsConnected");
Intent loginActivity = new Intent(this, NavigationDrawerActivity.class);
startActivity(loginActivity);
finish();
} else {
Log.e("SPLASH", "launch login activity");
Intent loginActivity = new Intent(this, MainActivity.class);
startActivity(loginActivity);
finish();
}
}
}
that is my splash drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/colorPrimaryDark"/>
<item android:bottom="8dp"
android:top="8dp"
android:left="8dp"
android:right="8dp">
<bitmap android:gravity="center"
android:src="#mipmap/ic_launcher"
android:antialias="true"/>
</item>
</layer-list>
And my splach style
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">#drawable/splash_drawable</item>
</style>
(Edit post) The navigation drawerActivity
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Response.Listener, Response.ErrorListener{
public TextView TextViewEmailAddress;
public TextView TextViewLogin;
private PrefManager pref;
private AllRequest req;
public RequestQueue mQueue;
private static final String REQUEST_TAG = "LogOutActivity";
private String address;
private String login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
this.TextViewEmailAddress = (TextView)header.findViewById(R.id.textView_drawer_mail);
this.TextViewLogin = (TextView)header.findViewById(R.id.textView_drawer_login);
this.pref = new PrefManager(getApplicationContext());
this.req = new AllRequest(getApplicationContext());
this.mQueue = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
.getRequestQueue();
address = this.pref.getEmail();
login = this.pref.getLogin();
this.TextViewEmailAddress.setText(address);
this.TextViewLogin.setText(getText(R.string.text_view_login_drawer) + " " + login);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_mon_compte) {
Intent intent = new Intent(NavigationDrawerActivity.this, MyAccountActivity.class);
startActivity(intent);
} else if (id == R.id.nav_deconnection) {
deconnexion();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void deconnexion(){
LayoutInflater factory = LayoutInflater.from(this);
final View alertDialogView = factory.inflate(R.layout.alertdialog_logout, null);
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setView(alertDialogView);
adb.setTitle(R.string.alertDialod_logout_Title);
adb.setPositiveButton((R.string.alertDialog_logout_PositiveBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String accessToken = pref.getAccessToken();
req.revokeTokenRequest(REQUEST_TAG, accessToken, NavigationDrawerActivity.this, NavigationDrawerActivity.this);
pref.logout();
Intent intent = new Intent(NavigationDrawerActivity.this, MainActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton((R.string.alertDialog_logout_NegativeBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
adb.show();
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("errrrrrror :(", "it's not working");
}
#Override
public void onResponse(Object response) {
Log.e("pololololo","it's working :D");
}
}
I WAS WORKING BY THE EXAMPLE YOU JUST GAVE ME AS DUPLICATE, READ THE ENTIRE POST, TY
I'm making a simple app with sliding menu by using the template provided by android studio. And I have to use fragments to switch between items of the sliding menu.
What I wanna do? (check app design at the bottom)
When I click on button pass data it should set the text in the Fragment B to the text that I entered in a Fragment A but without going directly to the Fragment B. So when I press the button pass data then I wanna go to the sliding menu and select item that containts fragment B and then I wanna see the text from Fragment A. Thanks in advance.
public class MainActivity extends AppCompatActivity implements FragmentA.DataPassListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
displayFragmentA();
} else if (id == R.id.nav_gallery) {
displayFragmentB();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void passData(String data) {
FragmentB fragmentB = new FragmentB();
Bundle args = new Bundle();
args.putString("data", data);
fragmentB.setArguments(args);
//getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragmentB).commit();
//it works with the commented part but I dont wanna go directly to the fragment when I press pass data button
}
public void displayFragmentA() {
FragmentA frag = new FragmentA();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, frag);
fragmentTransaction.commit();
}
public void displayFragmentB() {
FragmentB frag = new FragmentB();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, frag);
fragmentTransaction.commit();
}
}
Fragment A code:
public class FragmentA extends Fragment {
DataPassListener mCallback;
public interface DataPassListener {
public void passData(String data);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Make sure that container activity implement the callback interface
try {
mCallback = (DataPassListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DataPassListener");
}
}
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
final EditText input = (EditText) view.findViewById(R.id.etInputID);
Button passDataButton = (Button) view.findViewById(R.id.bPassDataID);
passDataButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.passData(input.getText().toString());
}
});
return view;
}
}
Fragment B code:
public class FragmentB extends Fragment {
TextView showReceivedData;
public FragmentB() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_b, container, false);
showReceivedData = (TextView) view.findViewById(R.id.showReceivedData);
Bundle args = getArguments();
if (args != null) {
showReceivedData.setText(args.getString("data"));
} else {
Toast.makeText(getActivity(), "didnt get the bundle from mainactivity", Toast.LENGTH_LONG).show();
}
return view;
}
}
Design of the app:
If these two fragments use same activity,
to set value to fragment :
getActivity().getIntent().putExtra("key", "value");
To get value from fragment :
getActivity().getIntent().getExtras().getString("key");
I'm writing an app for school and everything works fine when I run the app in the emulator.
The problem is when I connect my phone through usb and run the app on the phone.
Whenever I do something which requires the mListener (in any fragment in the whole app), I get a nullpointerexception on my mListener.
I have searched but have not found a solution or similar problem.
I have the problem in all of my fragments, but I will just show 1 fragment here:
Code of a fragment:
public class QuizFragment extends Fragment {
private OnFragmentQuizInteractionListener mListener;
List<Vraag> quesList;
int qid=0;
Vraag currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
TextView txtResult;
Button btnToonAntwoord;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Quiz");
final View view = inflater.inflate(R.layout.quiz_layout, container, false);
//btnStart = (Button) getActivity().findViewById(R.id.btnStart);
//btnStart.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// mListener.initQuiz();
// }
//});
//reset the score to 0
mListener.resetScore();
qid=0;
QuizDbHelper db=new QuizDbHelper(view.getContext());
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView) view.findViewById(R.id.textView1);
rda=(RadioButton)view.findViewById(R.id.radio0);
rdb=(RadioButton)view.findViewById(R.id.radio1);
rdc=(RadioButton)view.findViewById(R.id.radio2);
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(true);
rdb.setEnabled(true);
rdc.setEnabled(true);
butNext=(Button)view.findViewById(R.id.btnNext);
btnToonAntwoord=(Button)view.findViewById(R.id.btnToonAntwoord);
txtResult = (TextView) view.findViewById(R.id.resultTextview);
setQuestionView(view);
setOnClickListeners(view);
return view;
}
private void setOnClickListeners(View v){
final View thisView = v;
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(qid<8){
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(true);
rdb.setEnabled(true);
rdc.setEnabled(true);
//zet het resultaat terug op niets
txtResult.setText("");
//Wanneer het goed is, voeg 1 bij de score bij
RadioGroup grp = (RadioGroup) thisView.findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) thisView.findViewById(grp.getCheckedRadioButtonId());
if (currentQ.getANSWER().equals(checkChecked(answer.getId()))) {
mListener.incrementScore();
}
currentQ=quesList.get(qid);
setQuestionView(thisView);
}else{
//ga naar het eindscherm met het resultaat.
mListener.navigeerEindscore();
}
}
});
btnToonAntwoord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) thisView.findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) thisView.findViewById(grp.getCheckedRadioButtonId());
//toon de juiste boodschap aan de hand van het antwoord die gegeven is.
if (currentQ.getANSWER().equals(checkChecked(answer.getId()))) {
txtResult.setText(currentQ.getGoedeFeedback());
}else{
txtResult.setText(currentQ.getSlechteFeedback());
}
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(false);
rdb.setEnabled(false);
rdc.setEnabled(false);
}
});
}
private String checkChecked(int id) {
if(id == R.id.radio0){
return "A";
}else if(id == R.id.radio1){
return "B";
}else{
return "C";
}
}
private void setQuestionView(View v)
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentQuizInteractionListener) {
mListener = (OnFragmentQuizInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnResultFragmentInteractionListener");
}
}
public interface OnFragmentQuizInteractionListener {
void incrementScore();
void resetScore();
void navigeerEindscore();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
mainActivity:
{
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,DashboardFragment.OnFragmentLoginInteractionListener,LoginFragment.OnFragmentLoginInteractionListener, RegistratieFragment.OnFragmentRegistratieInteractionListener,QuizFragment.OnFragmentQuizInteractionListener, ResultFragment.OnResultFragmentInteractionListener{
private FragmentManager fragmentManager;
public int quizScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_main);
quizScore = 0;
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("Theme1", "Blauw");
//toolbar ophalen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Log.i("huidige preferences", themeName);
//toolbar instellen
setSupportActionBar(toolbar);
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();
/**if (themeName.equals("Blauw")) {
setTheme(R.style.AppTheme_blauw);
Log.i("MyActivity", "in blauw");
} else if (themeName.equals("Groen")) {
this.setTheme(R.style.AppTheme_groen);
Log.i("MyActivity", "in groen");
} else if (themeName.equals("Roze")) {
this.setTheme(R.style.AppTheme_roze);
Log.i("MyActivity", "in roze");
}**/
fragmentManager = getFragmentManager();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
fragmentManager.beginTransaction().replace(R.id.content_frame, new DashboardFragment()).commit();
}
//backknop werkt hoe hij moet werken
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
int count = getFragmentManager().getBackStackEntryCount();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
fragmentManager.beginTransaction().replace(R.id.content_frame, new InstellingenFragment()).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
//region dashboard
public void MijnProfielClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MijnProfielFragment())
.addToBackStack("MijnProfiel")
.commit();
}
public void AlarmClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new PilAlarmFragment())
.addToBackStack("Pilalarm")
.commit();
}
public void KalenderClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MenstruatieFragment())
.addToBackStack("Kalender")
.commit();
}
//endregion
//Navigatiemethodes LOGIN
public void Login() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new DashboardFragment())
.addToBackStack("Login")
.commit();
}
//Navigatiemethodes REGISTREREN
public void Registreer() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new DashboardFragment())
.addToBackStack("Registreer")
.commit();
}
public void Annuleren() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new LoginFragment())
.addToBackStack("Registreer")
.commit();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_dashboard_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new DashboardFragment()).addToBackStack("dashboard").commit();
break;
case R.id.nav_mijnprofiel_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new MijnProfielFragment()).addToBackStack("mijnprofiel").commit();
break;
case R.id.nav_categorieen_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new CategorieenFragment()).addToBackStack("categorieen").commit();
break;
case R.id.nav_pilalarm_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new PilAlarmFragment()).addToBackStack("pilalarm").commit();
break;
case R.id.nav_menstruatie_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new MenstruatieFragment()).addToBackStack("menstruatie").commit();
break;
case R.id.nav_quiz_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new QuizFragment()).addToBackStack("quiz").commit();
break;
case R.id.nav_instellingen_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new InstellingenFragment()).addToBackStack("instellingen").commit();
break;
case R.id.nav_partners_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new PartnersFragment()).addToBackStack("partners").commit();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//region Partner onclick listeners
public void onVivesPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.vives.be/");
}
public void onSensoaPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.sensoa.be/");
}
public void onUgentPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.ugent.be/");
}
public void onUCCVPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.ucvvgent.be/nl/");
}
public void onOnePartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.one.be//");
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
//endregion
//region quizfragment
#Override
public void incrementScore() {
quizScore++;
}
#Override
public void resetScore() {
quizScore = 0;
}
#Override
public void navigeerEindscore() {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ResultFragment()).commit();
}
#Override
public int getScore() {
return quizScore;
}
//endregion
The error I'm getting (doesn't matter what fragment, it's always nullpointerexception on the mlistener)
java.lang.NullPointerException: Attempt to invoke interface method 'void be.vives.pwo_kinderwens.Quiz.QuizFragment$OnFragmentQuizInteractionListener.resetScore()' on a null object reference
at be.vives.pwo_kinderwens.Quiz.QuizFragment.onCreateView(QuizFragment.java:55)
at android.app.Fragment.performCreateView(Fragment.java:2053)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
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:5294)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
The problem is that your mListener is not implemented.
I would try the following:
I would add a method to QuizFragment like :
public void setFragmentQuizInteractionListener(OnFragmentQuizInteractionListener mListener)
{
this.mListener = mListener;
}
And then
case R.id.nav_quiz_layout:
QuizFragment quizFragment = new QuizFragment();
quizFragment.setFragmentQuizInteractionListener(this);
fragmentManager.beginTransaction().replace(R.id.content_frame, quizFragment ).addToBackStack("quiz").commit();
break;
And drop the onAttach() method.
Probably not the nicest way but worth a try.
You need to override
public void onAttach (Activity activity)
instead of
public void onAttach (Context context)
The latter was included in API level 23, so previous versions of Android will not call it.
See onAttach (Activity activity)
Use onAttach method in Fragment. Check Fragment Lifecycle
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}