App Stops when using countdown timer - java

I'm working on an a Quiz App which has five fragments and every fragment has one Question in it. Fragments move in two ways.
When user clicks on an option then the next fragment appears Immediately.
I've a countdown timer that if user does not click on any option then after 10 seconds the fragment is moved to new fragment.
I've implemented the click functions. when user clicks on the option app takes it to the next fragment but if in that next fragment user clicks no option then app stops Immediately.
Kindly have a look on this, I'm sharing code.
Question.java (Fragment1)
package com.example.sheikhspc.testapp;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Question1 extends Fragment implements View.OnClickListener {
public Question1() {
// Required empty public constructor
}
int counter = 0;
View view;
Fragment frag = null;
TextView tv;
ImageView imageView1, imageViewR, imageView2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_question1, container, false);
imageView1 = (ImageView) view.findViewById(R.id.wrong1);
imageViewR = (ImageView) view.findViewById(R.id.right);
imageView2 = (ImageView) view.findViewById(R.id.wrong2);
tv = (TextView) view.findViewById(R.id.timer1);
imageView1.setOnClickListener(this);
imageViewR.setOnClickListener(this);
imageView2.setOnClickListener(this);
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tv.setText("Remaining Time: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
frag = new Question2();
FragmentManager fmm = getFragmentManager();
FragmentTransaction fragmentTransactionn = fmm.beginTransaction();
fragmentTransactionn.addToBackStack(null);
fragmentTransactionn.replace(R.id.container, frag);
fragmentTransactionn.commit();
}
}.start();
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.wrong1:
frag = new Question2();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container,frag);
fragmentTransaction.commit();
break;
case R.id.right:
frag = new Question2();
FragmentManager fm1 = getFragmentManager();
FragmentTransaction fragmentTransaction1 = fm1.beginTransaction();
fragmentTransaction1.replace(R.id.container,frag);
fragmentTransaction1.commit();
break;
case R.id.wrong2:
frag = new Question2();
FragmentManager fm2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fm2.beginTransaction();
fragmentTransaction2.replace(R.id.container,frag);
fragmentTransaction2.commit();
break;
default:
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tv.setText("Remaining Time: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
frag = new Question2();
FragmentManager fmm = getFragmentManager();
FragmentTransaction fragmentTransactionn = fmm.beginTransaction();
fragmentTransactionn.addToBackStack(null);
fragmentTransactionn.replace(R.id.container, frag);
fragmentTransactionn.commit();
}
}.start();
break;
}
}
}
Question2.java (Fragment2)
package com.example.sheikhspc.testapp;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class Question2 extends Fragment implements View.OnClickListener {
public Question2() {
// Required empty public constructor
}
Fragment frag = null;
TextView tv;
View view;
ImageView imageView1, imageViewR, imageView2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_question2, container, false);
tv = (TextView)view.findViewById(R.id.timer2);
imageView1 = (ImageView) view.findViewById(R.id.wrong1);
imageViewR = (ImageView) view.findViewById(R.id.right);
imageView2 = (ImageView) view.findViewById(R.id.wrong2);
imageView1.setOnClickListener(this);
imageViewR.setOnClickListener(this);
imageView2.setOnClickListener(this);
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tv.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
tv.setText("done!");
frag = new Question3();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container,frag);
fragmentTransaction.commit();
}
}.start();
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.wrong1:
frag = new Question3();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container,frag);
fragmentTransaction.commit();
break;
case R.id.right:
frag = new Question3();
FragmentManager fm1 = getFragmentManager();
FragmentTransaction fragmentTransaction1 = fm1.beginTransaction();
fragmentTransaction1.replace(R.id.container,frag);
fragmentTransaction1.commit();
break;
case R.id.wrong2:
frag = new Question3();
FragmentManager fm2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fm2.beginTransaction();
fragmentTransaction2.replace(R.id.container,frag);
fragmentTransaction2.commit();
break;
default:
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tv.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
tv.setText("done!");
frag = new Question3();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container,frag);
fragmentTransaction.commit();
}
}.start();
break;
}
}
}
Error Log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sheikhspc.testapp, PID: 32330
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference
at com.example.sheikhspc.testapp.Question1$1.onFinish(Question1.java:58)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
I/Process: Sending signal. PID: 32330 SIG: 9
Application terminated.
Second.java (Activity where all the fragments are displayed)
package com.example.sheikhspc.testapp;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.os.CountDownTimer;
import android.provider.DocumentsContract;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class Second extends AppCompatActivity {
Fragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
frag = new Question1();
fragmentTransaction.replace(R.id.container,frag);
fragmentTransaction.commit();
}
}

You will need to cancel the timer before you replace the fragment on click.
When you create a new instance of CountDownTimer in onCreate method assign it to a variable for e.g.
CountDownTimer timer = new CountDownTimer(10000, 1000) {...};
timer.start();
And then in onClick method i.e. when user clicks any option stop the timer for e.g.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnNext:
// Add this line to avoid crash
timer.cancel();
frag = new FragmentQuestion2();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container,frag);
fragmentTransaction.commit();
break;
}

Related

FragmentPagerAdapter always starts from the first page

I have a Fragment pager adapter with five fragments and inside the third fragment I want to call an other activity which sends a selected picture to the container. It works fine but, every time the picture is selected from the other activity and the pager adapter starts from the first fragment in the fragment-activity instead of third fragment-activity. Do I have to force the pager adapter from the other activity or should I change something in the fragment-activity?
Code:
Fragment-activity:
package com.example.android.womb_the_game;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
public class Circulation extends FragmentActivity {
ViewPager vp;
public static FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_circulation);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
vp = findViewById(R.id.view_pager);
adapterViewPager=new Adapter_Circulation(getSupportFragmentManager(), this);
vp.setAdapter(adapterViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(vp);
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();
}
});
}
}
FragmentPagerAdapter:
package com.example.android.womb_the_game;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import android.content.Context;
public class Adapter_Circulation extends FragmentPagerAdapter {
private static int NUM_ITEMS = 5;
Context context;
public Adapter_Circulation(FragmentManager fm, Context c) {
super(fm);
this.context = c;
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return Frg0.newInstance ();
case 1:
return Frg1.newInstance();
case 2:
return Frg2.newInstance();
case 3:
return Frg3.newInstance();
case 4:
return Frg4.newInstance();
}
return null; //does not happen
}
#Override
public int getCount() {
return NUM_ITEMS; //three fragments
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "RULES";
case 1:
return "EVENTS";
case 2:
return "PLAN";
case 3:
return "SHOOT";
case 4:
return "JUMP";
}
return null;
}
}
Fragment3:
package com.example.android.womb_the_game;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class Frg3 extends Fragment{
private ImageButton shoot;
private ImageButton snipe;
private ImageButton aim;
public static Frg3 newInstance() {
Bundle args = new Bundle();
Frg3 fragment = new Frg3();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_frg3, container, false);
shoot = (ImageButton) rootView.findViewById(R.id.shoot);
snipe = (ImageButton) rootView.findViewById(R.id.snipe);
aim = (ImageButton) rootView.findViewById(R.id.aim);
final View.OnClickListener mListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.shoot:
FragmentManager FM0 = getFragmentManager();
FragmentTransaction FT0 = FM0.beginTransaction();
frg_shoot F10 = new frg_shoot();
FT0.add(R.id.fragment_container1, F10);
FT0.replace(R.id.fragment_container1, F10);
FT0.commit();
break;
case R.id.snipe:
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
frg_snipe F1 = new frg_snipe();
FT.add(R.id.fragment_container1, F1);
FT.replace(R.id.fragment_container1, F1);
FT.commit();
break;
case R.id.aim:
FragmentManager FM1 = getFragmentManager();
FragmentTransaction FT1 = FM1.beginTransaction();
frg_aim F11 = new frg_aim();
FT1.add(R.id.fragment_container1, F11);
FT1.replace(R.id.fragment_container1, F11);
FT1.commit();
break;
}
}
};
rootView.findViewById(R.id.shoot).setOnClickListener(mListener);
rootView.findViewById(R.id.snipe).setOnClickListener(mListener);
rootView.findViewById(R.id.aim).setOnClickListener(mListener);
return rootView;
}
}
Other Activity:
package com.example.android.womb_the_game;
import androidx.fragment.app.FragmentActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
public class choose_dice_column extends FragmentActivity {
private ImageButton b1;
private ImageView im1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_choose_dice_column);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
b1 = (ImageButton) findViewById(R.id.b1);
im1 = findViewById(R.id.im1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(choose_dice_column.this, Circulation.class);
i.putExtra("resid1",R.drawable.n1);
startActivity(i);
}
});
}
}
The problem is, whenever you get back to your activity, you are creating a new adapter. So add the following to your Circulation-Activity to keep the state of the adapter:
if(adapterViewPager == null)
{
adapterViewPager = new Adapter_Circulation(getSupportFragmentManager(), this);
}

When I call next fragment form current the tab selection will not change on Button click

I am trying to develop an android app in which I am going to include tab with fragment. Please find below code for Activity :
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
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.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class EnterActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(3).select();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new EnterCodeFragment(), "ENTER CODE");
adapter.addFragment(new HistoryFragment(), "HISTORY");
adapter.addFragment(new HelpFragment(), "HELP");
adapter.addFragment(new LogoutFragment(), "LOGOUT");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Below logic I used to call other fragment on button click.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
Button loginButton = (Button)v.findViewById(R.id.button);
loginButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Fragment fragment = new EnterCodeFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
// ViewPagerAdapter.get
}
});
return v;
}
When I click on button it will move to the next fragment but tab selection will not change. I think it is creating a new fragment. Any help would be appreciated.
I think you not initialize fragment properly update like above code
Button loginButton = (Button)v.findViewById(R.id.button);
loginButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
EnterCodeFragment fragment = new EnterCodeFragment(); // check this
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
// ViewPagerAdapter.get
}
});

MapFragment on a fragment

Im developing an app that displays a map on a fragment. Everything is set up, but there's small thing that is not letting me finish it.
gMapFragment.java:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class gMapFragment extends Fragment implements OnMapReadyCallback {
public gMapFragment() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(46.33328, 15.38173);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker,13));
googleMap.addMarker(new MarkerOptions().title(("HERE WE ARE!")).position(marker));
}
}
I call this fragment from button in another frament and this is the method that calls it:
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.SearchButton:
fragment = new gMapFragment();
replaceFragment(fragment);
break;
}
}
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
I get error "gMapFragment cannot be converted to fragment" Any idea how to fix this? thanks!
First, make sure that you're consistent with your Fragment imports. Use either import android.app.Fragment in all classes or import android.support.v4.app.Fragment; in all classes. Don't mix-and-match.
Then, add this to the Activity:
public void openMapFragment() {
Fragment fragment = new gMapFragment();
replaceFragment(fragment);
}
//moved to Activity from the Fragment
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Then, in the Fragment onClick() method, just call into the Activity to do the FragmentTransaction:
public void onClick(View view) {
switch (view.getId()) {
case R.id.SearchButton:
MainActivity activity = (MainActivity) getActivity();
if (activity != null) {
activity.openMapFragment();
}
break;
}
}

Android - Calling a method from MainActivity into Fragment

I'm having an issue to where I'm trying to call a method in my main activity which saves my data to a database on a button click to my fragment. The issue is that I am unsure of what to put in the brackets of the method.
Here is my main activity class
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
DatabaseHelper myDB;
EditText tNumber, tPoticullis, tChevalFrise, tMoat, tRamparts, tDrawbridge, tSallyPort, tRockWall, tRockTerrain, tLowBar;
Context context = this;
DatabaseHelper databaseHelper;
SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create database
myDB = new DatabaseHelper(this);
//Instantiate all editText objects
tNumber = (EditText) findViewById(R.id.editNumber);
tPoticullis = (EditText) findViewById(R.id.editPoticullis);
tChevalFrise = (EditText) findViewById(R.id.editChevalFrise);
tMoat = (EditText) findViewById(R.id.editMoat);
tRamparts = (EditText) findViewById(R.id.editRamparts);
tDrawbridge = (EditText) findViewById(R.id.editDrawbridge);
tSallyPort = (EditText) findViewById(R.id.editSallyPort);
tRockWall = (EditText) findViewById(R.id.editRockWall);
tRockTerrain = (EditText) findViewById(R.id.editRockTerrain);
tLowBar = (EditText) findViewById(R.id.editLowBar);
//Set the fragment initially
WelcomeFragment fragment = new WelcomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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) findViewById(R.id.nav_view);
//How to change elements in the header programatically
View headerView = navigationView.getHeaderView(0);
TextView emailText = (TextView) headerView.findViewById(R.id.description);
emailText.setText("Scouting Application");
navigationView.setNavigationItemSelectedListener(this);
} //End of onCreate
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
} //End of if statement
} //End of 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;
} //End of onCreateOptionsMenu
#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;
} //End of if statement
return super.onOptionsItemSelected(item);
} //End of onOptionsItemSelected
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_welcome) {
//Set the fragment initially
WelcomeFragment fragment = new WelcomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
// Handle the camera action
}
else if (id == R.id.nav_facebook) {
FacebookFragment fragment = new FacebookFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
else if (id == R.id.nav_members) {
//Set the fragment initially
MembersFragment fragment = new MembersFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
else if (id == R.id.nav_robot) {
}
else if (id == R.id.nav_scout) {
//Set the fragment initially
ScoutFragment fragment = new ScoutFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
else if (id == R.id.nav_match) {
//Set the fragment initially
MatchFragment fragment = new MatchFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} //End of if statement
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
} //End of onNavigationItemSelected
public void addScoutInfo(View view){
//Converts all editText values into strings
String sNumber = tNumber.getText().toString();
String sPoticullis = tPoticullis.getText().toString();
String sChevalFrise = tChevalFrise.getText().toString();
String sMoat = tMoat.getText().toString();
String sRamparts = tRamparts.getText().toString();
String sDrawbridge = tDrawbridge.getText().toString();
String sSallyPort = tSallyPort.getText().toString();
String sRockWall = tRockWall.getText().toString();
String sRockTerrain = tRockTerrain.getText().toString();
String sLowBar = tLowBar.getText().toString();
//Saves data
databaseHelper = new DatabaseHelper(context);
sqLiteDatabase = databaseHelper.getWritableDatabase();
databaseHelper.addInformation(sNumber, sPoticullis, sChevalFrise, sMoat, sRamparts, sDrawbridge, sSallyPort, sRockWall,
sRockTerrain, sLowBar, sqLiteDatabase);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
databaseHelper.close();
} //End of addScoutInfo
} //End of class
Here is my Fragment class
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* A simple {#link Fragment} subclass.
*/
public class AddScoutDataFragment extends Fragment {
Button cancelButton;
Button addDataButton;
public AddScoutDataFragment() {
// Required empty public constructor
} //End of AddScoutDataFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_add_scout_data, container, false);
view.setBackgroundColor(Color.WHITE);
//Adds data to ScoutFragment
addDataButton = (Button) view.findViewById(R.id.buttonDataAdd);
addDataButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//Saves data to database
MainActivity mainActivity = ((MainActivity)getActivity()).addScoutInfo();
//Returns to ScoutFragment
ScoutFragment fragment = new ScoutFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} //End of onClick
}); //End of setOnClickListener
//Returns to ScoutFragment without adding any data
cancelButton = (Button) view.findViewById(R.id.buttonCancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Returns to ScoutFragment
ScoutFragment fragment = new ScoutFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} //End of onClick
}); //End of setOnClickListener
// Inflates the layout for this fragment
return view;
} //End of onCreateView
} //End of class
The issue happens in the fragment class in the onCreateView method MainActivity mainActivity = ((MainActivity)getActivity()).addScoutInfo(Need to insert something here);
addScoutInfo function parameter is not used in that function, so you can just pass null or remove the parameter. That will make your code work BUT it is generally a bad idea to cast the result of getActivity() to a specific type. The fragment can be reused by other activity in future and that cast will no longer work.
Here are a few suggestions that can improve your code:
Make the fragment manage its own views,
Move the DB saving logic into the fragment,
Communicate from fragment to activity using either local Broadcast Receivers , some kind of Event bus or by passing a callback to the fragment.
In the fragment, on the onbind() method, add the listener and implement it in the Main Activity class, this way you can call this method from the fragment to the activity. More information here:
http://developer.android.com/training/basics/fragments/communicating.html
If in case you are NOT using android:onClick="addScoutInfo" method in widget in XML, you can just remove the parameters on your addScoutInfo method. Else, you must pass the view that has been triggered, say for example your btn_add_scout_info button.

how to hide frag and refresh the activity to show this

i have a button called ac and when i click on it, i want to hide my two fragment called a and b, but this is not happening, what do I need to do to make this work?
package cmsc436.lab5;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class Lab5Activity extends Activity implements button2interface, button1interface{
/** Called when the activity is first created. */
button1 a;
button2 b ;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
a= new button1();
b=new button2();
final LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setId(1);
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
//a.getActivity().findViewById(1);
fragmentTransaction.add(linearLayout.getId(), a);
fragmentTransaction.add(linearLayout.getId(), b);
fragmentTransaction.commit();
final Button ac =new Button(this);
ac.setText("c button");
linearLayout.addView(ac);
setContentView(linearLayout);
ac.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
fragmentTransaction.hide(a);
fragmentTransaction.hide(b);
}
});
}
#Override
public void buttonClick1() {
if (b.isHidden()) {
fragmentTransaction.show(b);
}
else {
fragmentTransaction.hide(b);
}
}
#Override
public void buttonClick2() {
if (a.isHidden()) {
fragmentTransaction.show(a);
}
else {
fragmentTransaction.hide(a);
}
}
}
I haven't really worked with fragments before, but it looks like you're trying to re-use a FragmentTransaction that's already been committed. You don't want a member variable for your FragmentTransaction; you should create a new one every time you need it:
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.hide(a);
fragmentTransaction.hide(b);
fragmentTransaction.commit();
}

Categories