java - microsoft - visual studio installer
La función en fragmento hace que el emulador se cuelgue (2)
Se produce un error cuando onCreateView
una función dentro onCreateView
en menu1_Fragment.java
. Lo siento de antemano porque también colocaré mis registros para que mi publicación sea un poco grande, así que le diré el diseño. Lo siento por las muchas preguntas.
El código funciona perfectamente si simplemente no pongo la función setClick()
dentro de mi fragmento. nota rápida que la función básicamente hace que mi imagen en menu1_layout.xml
un botón de 3 vías, también conocido como iniciar detener el restablecimiento, donde cuando lo restableces, aparece un brindis del tiempo exacto que tienes
1) menu1_Fragment.java
public class menu1_Fragment extends Fragment {
Chronometer mChronometer;
int loop = 0;
double startTime;
double millis;
View rootview;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
setClick();
return rootview;
}
Button button;
public void setClick() {
mChronometer = (Chronometer) getActivity().findViewById(R.id.aChronometer);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
button = (Button) getActivity().findViewById(R.id.stopWatch);
button.setOnClickListener(mStartListener);
}
View.OnClickListener mStartListener = new View.OnClickListener() {
public void onClick(View v) {
if (loop == 0) {
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
startTime = System.currentTimeMillis();
loop++;
} else if (loop == 1) {
mChronometer.stop();
millis = System.currentTimeMillis()-startTime;
loop++;
} else if (loop == 2) {
mChronometer.setBase(SystemClock.elapsedRealtime());
Context context = getActivity().getApplicationContext();
CharSequence text = "Your Time is: " + (millis/1000);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
loop = 0;
}
}
};
}
2) REGISTROS
10-28 16:52:26.552 2912-2912/app.z0nen.menu D/AndroidRuntime: Shutting down VM
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: FATAL EXCEPTION: main
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Process: app.z0nen.menu, PID: 2912
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{app.z0nen.menu/app.z0nen.slidemenu.MyActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ''void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'' on a null object reference
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ''void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'' on a null object reference
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.setClick(menu1_Fragment.java:39)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.onCreateView(menu1_Fragment.java:26)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Fragment.performCreateView(Fragment.java:2220)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.BackStackRecord.run(BackStackRecord.java:793)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentController.execPendingActions(FragmentController.java:325)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Activity.performStart(Activity.java:6252)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-28 16:52:28.662 2912-2912/? I/Process: Sending signal. PID: 2912 SIG: 9
3) MyActivity.Java
public class MyActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new menu1_Fragment();
break;
case 1:
objFragment = new menu2_Fragment();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.my, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
4) Menu1_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_horizontal">
<Chronometer
android:id="@+id/aChronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:textColor="#111111"
android:layout_marginTop="27dp"
android:layout_below="@+id/stopWatch"
android:layout_centerHorizontal="true" />
<Button
android:id="@+id/stopWatch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/stopwatch2"
android:layout_marginTop="38dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Cambio
button = (Button) getActivity().findViewById(R.id.stopWatch);
a esto:
button = (Button) findViewById(R.id.stopWatch);
Su botón está dentro del diseño de su fragmento, no de la actividad.
EDITAR:
Haga que su button
miembro variable, para que pueda acceder a él desde los métodos onCreateView
& setClick
:
private Button mButton;
Y tenemos que guardar una referencia de su button
en el método onCreateView
para esto: (rootview es el diseño inflado de su fragmento)
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
mButton = rootview.findViewById(R.id.stopWatch);
setClick();
return rootview;
}
y en el método setClick ponga esto en su lugar:
mButton.setOnClickListener(mStartListener);
No puede usar getActivity()
desde onCreateView()
ya que la actividad del fragmento aún no se ha creado. Debe utilizar no use getActivity()
hasta que onActivityCreated()
se llame, o mejor aún, use la vista de rootview
que infló para hacer sus llamadas a findViewByID()
.
Además, está inicializando su botón tres veces. Deberías deshacerte de dos de ellos :)