问:
App crashes with OnClickListener in Fragment
I have an app with 3 tabs and one of them has a todo-function. Everything works fine when I want to add a new note. Now I wanted to implement a delete function for the notes and since I can't access the button from the .xml file I tried it with public class Tab2 extends Fragment implements View.OnClickListener and public void onClick(View v) but now my App crashes completly when I start it. What do I do wrong?
Here the Fragment:

```<code>public class Tab2 extends Fragment implements View.OnClickListener {

ImageButton btn_ok;
EditText edit_task;
private TaskDbHelper mHelper;
public ListView mTaskListView;
private ArrayAdapter<String> mAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab2, container, false);

    setHasOptionsMenu(true);
    mHelper = new TaskDbHelper(getActivity());
    mTaskListView = view.findViewById(R.id.list_todo);
    updateUI();

    Button b = view.findViewById(R.id.btn_delete);
    b.setOnClickListener(this);

    return view;
}

public void updateUI() {
    ArrayList<String> taskList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(TaskContract.TaskEntry.TABLE, new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
            null, null, null, null, null, null);
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(idx));
    }

    if (mAdapter == null) {
        mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.item_todo, R.id.task_title, taskList);
        mTaskListView.setAdapter(mAdapter);
    } else {
        mAdapter.clear();
        mAdapter.addAll(taskList);
        mAdapter.notifyDataSetChanged();
    }

    cursor.close();
    db.close();
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.main_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_add_task:
            final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
            View mView = getLayoutInflater().inflate(R.layout.dialog_add_task, null);
            btn_ok = mView.findViewById(R.id.btn_ok5);
            edit_task = mView.findViewById(R.id.edit_task);
            mBuilder.setView(mView);
            final AlertDialog dialog = mBuilder.create();
            dialog.show();

            btn_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String task = String.valueOf(edit_task.getText());
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                    db.insertWithOnConflict(TaskContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                    db.close();

                    updateUI();

                    dialog.cancel();
                }
            });

            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_delete:
            View parent = (View) v.getParent();
            TextView taskTextView = parent.findViewById(R.id.task_title);
            String task = String.valueOf(taskTextView.getText());
            SQLiteDatabase db = mHelper.getWritableDatabase();
            db.delete(TaskContract.TaskEntry.TABLE, TaskContract.TaskEntry.COL_TASK_TITLE + " = ?", new String[]{task});
            db.close();

            updateUI();

            break;
    }
} }
</code>```

Logcat:

```<code>    12-06 19:35:58.710 20306-20306/com.example.rike1.final_logbuch E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.rike1.final_logbuch, PID: 20306
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                at com.example.rike1.final_logbuch.Tab2.onCreateView(Tab2.java:49)
                                                                                at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2199)
                                                                                at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)
                                                                                at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1236)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
                                                                                at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                                                                                at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1485)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1485)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:729)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2436)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1482)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1741)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1366)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6768)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:926)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:735)
12-06 19:35:58.710 20306-20306/com.example.rike1.final_logbuch E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:912)
                                                                                at android.os.Handler.handleCallback(Handler.java:761)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:156)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
</code>```

XML item_todo where the Button is I want to access:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical">
    <TextView
        android:id="@+id/task_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="Hello"
        android:textSize="20sp" />
    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="Done"
        android:backgroundTint="@color/colorAccent"/>
</RelativeLayout>
</code>```

tab2 XML:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    <ListView
        android:id="@+id/list_todo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ListView>
</RelativeLayout>
</code>```

答:
You need to add the item click listener in ListView and use that. You can't just find the ListViews items because there would be multiple of them.

```<code>mTaskListView.setOnItemClickListener(this); // And remember to implement the interface
</code>```

https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html

Then you can move your code from method onClick to onItemClick

```<code>@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    TextView taskTextView = view.findViewById(R.id.task_title);
    String task = String.valueOf(taskTextView.getText());
    SQLiteDatabase db = mHelper.getWritableDatabase();
    // and so on...
}
</code>```

and ofcourse you need to remove the lines which are causing the null pointer exception:

```<code>Button b = view.findViewById(R.id.btn_delete);
b.setOnClickListener(this);
</code>```

Body:
I have an app with 3 tabs and one of them has a todo-function. Everything works fine when I want to add a new note. Now I wanted to implement a delete function for the notes and since I can't access the button from the .xml file I tried it with public class Tab2 extends Fragment implements View.OnClickListener and public void onClick(View v) but now my App crashes completly when I start it. What do I do wrong?
Here the Fragment:

public class Tab2 extends Fragment implements View.OnClickListener {

ImageButton btn_ok;
EditText edit_task;
private TaskDbHelper mHelper;
public ListView mTaskListView;
private ArrayAdapter<String> mAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab2, container, false);

    setHasOptionsMenu(true);
    mHelper = new TaskDbHelper(getActivity());
    mTaskListView = view.findViewById(R.id.list_todo);
    updateUI();

    Button b = view.findViewById(R.id.btn_delete);
    b.setOnClickListener(this);

    return view;
}

public void updateUI() {
    ArrayList<String> taskList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(TaskContract.TaskEntry.TABLE, new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
            null, null, null, null, null, null);
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(idx));
    }

    if (mAdapter == null) {
        mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.item_todo, R.id.task_title, taskList);
        mTaskListView.setAdapter(mAdapter);
    } else {
        mAdapter.clear();
        mAdapter.addAll(taskList);
        mAdapter.notifyDataSetChanged();
    }

    cursor.close();
    db.close();
}

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.main_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_add_task:
            final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
            View mView = getLayoutInflater().inflate(R.layout.dialog_add_task, null);
            btn_ok = mView.findViewById(R.id.btn_ok5);
            edit_task = mView.findViewById(R.id.edit_task);
            mBuilder.setView(mView);
            final AlertDialog dialog = mBuilder.create();
            dialog.show();

            btn_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String task = String.valueOf(edit_task.getText());
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                    db.insertWithOnConflict(TaskContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                    db.close();

                    updateUI();

                    dialog.cancel();
                }
            });

            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_delete:
            View parent = (View) v.getParent();
            TextView taskTextView = parent.findViewById(R.id.task_title);
            String task = String.valueOf(taskTextView.getText());
            SQLiteDatabase db = mHelper.getWritableDatabase();
            db.delete(TaskContract.TaskEntry.TABLE, TaskContract.TaskEntry.COL_TASK_TITLE + " = ?", new String[]{task});
            db.close();

            updateUI();

            break;
    }
} }

Logcat:

    12-06 19:35:58.710 20306-20306/com.example.rike1.final_logbuch E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.rike1.final_logbuch, PID: 20306
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                at com.example.rike1.final_logbuch.Tab2.onCreateView(Tab2.java:49)
                                                                                at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2199)
                                                                                at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)
                                                                                at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1236)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1084)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
                                                                                at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                                                                                at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                                                                                at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1485)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1485)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:775)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6139)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:729)
                                                                                at android.view.View.measure(View.java:19917)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2436)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1482)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1741)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1366)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6768)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:926)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:735)
12-06 19:35:58.710 20306-20306/com.example.rike1.final_logbuch E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:667)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:912)
                                                                                at android.os.Handler.handleCallback(Handler.java:761)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:156)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

XML item_todo where the Button is I want to access:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical">
    <TextView
        android:id="@+id/task_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="Hello"
        android:textSize="20sp" />
    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="Done"
        android:backgroundTint="@color/colorAccent"/>
</RelativeLayout>

tab2 XML:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    <ListView
        android:id="@+id/list_todo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ListView>
</RelativeLayout>

Body:
You need to add the item click listener in ListView and use that. You can't just find the ListViews items because there would be multiple of them.

mTaskListView.setOnItemClickListener(this); // And remember to implement the interface

https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html

Then you can move your code from method onClick to onItemClick

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    TextView taskTextView = view.findViewById(R.id.task_title);
    String task = String.valueOf(taskTextView.getText());
    SQLiteDatabase db = mHelper.getWritableDatabase();
    // and so on...
}

and ofcourse you need to remove the lines which are causing the null pointer exception:

Button b = view.findViewById(R.id.btn_delete);
b.setOnClickListener(this);


来源: stackexchange

问:
Pascal Pseudocode
I'm learning Pascal Pseudocode in school and my teacher sent me this exercise:

Write an algorithm, in pseudocode, that, when read the name and the ages for N students, counts how many of them have more than 18 years old. Should print the name of those students.

I've writen the code until printing the counting of those students, but how should I do to print their names. Can you guys give me a tip?

PS: I didn't learned anything of arrays or records.

```<code>BEGIN
  WRITE ('Insert the number of students in the class.');
  READ (n);
  i := 1;
  WHILE i<=n DO
  BEGIN
    WRITE ('Insert the student's name');
    READ (name);
    WRITE ('Insert the student's age');
    READ (age);
    IF age > 18 THEN
      count := count + 1;
    i := i + 1;
  END;
  WRITE ('There are ',count,' students with more than 18 years.');
</code>```

I cannot proceed from here.

答:
You had several errors, you read the variables with READ instead of with READLN and I assume that the variables you have already declared. On the other hand the if it is convenient to have closure (with END)
Finally, remember to "stop" the console so that the message can be displayed    </p>

```<code>program count_age;
   USES CRT;
   VAR i,age,count,n:INTEGER;
   VAR name:STRING;
BEGIN
  count :=0;
  WRITE ('Insert the number of students in the class. ');
  READLN (n);
  i := 1;
  WHILE i<=n DO
  BEGIN
    WRITE ('Insert the students name ');
    READLN (name);
    WRITE ('Insert the students age ');
    READLN (age);
    IF age > 18 THEN BEGIN
      count := count + 1;
    END;
    i := i + 1;
  WRITE ('There are ',count,' students with more than 18 years.');
  readkey;
END.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pascal Pseudocode

Body:
I'm learning Pascal Pseudocode in school and my teacher sent me this exercise:

Write an algorithm, in pseudocode, that, when read the name and the ages for N students, counts how many of them have more than 18 years old. Should print the name of those students.

I've writen the code until printing the counting of those students, but how should I do to print their names. Can you guys give me a tip?

PS: I didn't learned anything of arrays or records.

BEGIN
  WRITE ('Insert the number of students in the class.');
  READ (n);
  i := 1;
  WHILE i<=n DO
  BEGIN
    WRITE ('Insert the student's name');
    READ (name);
    WRITE ('Insert the student's age');
    READ (age);
    IF age > 18 THEN
      count := count + 1;
    i := i + 1;
  END;
  WRITE ('There are ',count,' students with more than 18 years.');

I cannot proceed from here.

Body:
You had several errors, you read the variables with READ instead of with READLN and I assume that the variables you have already declared. On the other hand the if it is convenient to have closure (with END)
Finally, remember to "stop" the console so that the message can be displayed

program count_age;
   USES CRT;
   VAR i,age,count,n:INTEGER;
   VAR name:STRING;
BEGIN
  count :=0;
  WRITE ('Insert the number of students in the class. ');
  READLN (n);
  i := 1;
  WHILE i<=n DO
  BEGIN
    WRITE ('Insert the students name ');
    READLN (name);
    WRITE ('Insert the students age ');
    READLN (age);
    IF age > 18 THEN BEGIN
      count := count + 1;
    END;
    i := i + 1;
  WRITE ('There are ',count,' students with more than 18 years.');
  readkey;
END.


问:
UI tab control visibility changes between debug and deployed version
I have a WPF Mvvm-Light application that uses tab controls to display different views to the user.

PROBLEM:

THe problem I have is that when the program first loads the tab control displays empty.  But when debugging locally this problem never occurs.  This application has been in development for over a year without this issue and all of a sudden it started happening.  see below image

HACK FIX:

If the user resizes their window, the content in the tab control refreshes and appears and the problem never reoccurs while they have the application open.  But this issue occurs 100% of the time on first program load and first tab load (which happens at the same time)

DETAILS:

here is how I define my views that get inserted into the tab control

```<code> <DataTemplate DataType="{x:Type FtcViewModel:DashboardNavViewModel}">
   <FtcView:DashboardNav  />
 </DataTemplate>
</code>```

and here is my tab control:

```<code><TabControl  Grid.Column="1" Grid.Row="3"
                     SelectedItem="{Binding CurrentViewModel}"
                     ItemsSource="{Binding OpenViewModelCollection}"
                     Style="{StaticResource TabControlStyle}"
                     ItemContainerStyle="{StaticResource TabItemStyle}" >
        </TabControl>
</code>```

then in my view model for the main window i assign a collection to the tab control and by default set  the dashbaord as the first tab to open like this (tried to only include relevant code, obiously there is more in the viewModel file):

```<code>Public Property OpenViewModelCollection As ObservableCollection(Of ViewModelHelper)
    Get
        Return Me._OpenViewModelCollection
    End Get
    Set(value As ObservableCollection(Of ViewModelHelper))
        If _OpenViewModelCollection Is value Then
            Return
        End If
        _OpenViewModelCollection = value
        RaisePropertyChanged(OpenViewModelCollectionPropertyName)
    End Set
End Property

Public Property CurrentViewModel As ViewModelHelper
            Get
                Return Me._CurrentViewModel
            End Get
            Set(value As ViewModelHelper)
                If _CurrentViewModel Is value Then
                    Return
                End If
                ''if change of viewmodel is not from OpenTabViewModelCommandExecute method
                If FlagOpening = False AndAlso value IsNot Nothing Then

                    If _CurrentViewModel IsNot Nothing Then
                        _CurrentViewModel.HandleNavigation(True)
                    End If

                    ''Mark NavService target VM
                    _NavService.TargetViewModelKey = value.vmKey

                    ''evaluate if naviagtion has been canceled
                    If _NavService.bCanNavigate = False Then
                        _NavService.bCanNavigate = True
                        Exit Property
                    End If
                End If
                ''if navigation not canceled, finish assigning new view model
                _CurrentViewModel = value
                RaisePropertyChanged(CurrentViewModelPropertyName)
                If _CurrentViewModel IsNot Nothing Then
                    _CurrentViewModel.RefreshModel()
                End If
            End Set
        End Property
...

'' THIS CODE IS FROM THE CONSTRUCTOR OF THE VIEW MODEL CLASS
OpenViewModelCollection.Add(_Locator.DashboardHome_VM)
CurrentViewModel = OpenViewModelCollection(0)
</code>```

QUESTION

can someone help me figure out why this is happening or suggest a way to refresh the UI after the first application load.

thanks in advance

UPDATE 1 - Oct 4, 2017

I have been able to reproduce this problem on my development machine.  When the UI is blank you can see that the XAML diagnostics tools don't show up. THe image below shows the same app being debugged, but the one without the XAML tools box is the one with the missing ui elements.

The following content is not being rendered inside my custom tab control style:

```<code><ScrollViewer VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Auto" >
    <ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</ScrollViewer>
</code>```

EDIT 2 Oct 11 2017

I have set breakpoints in both the xaml and code in the ViewModel.  I can confirm that the ViewModel data is correctly initialized and assigned to the observable objects.  I also inserted "test" textblocks in my tabItemTemplate to confirm which part is not showing.  Right now I have a terrible hack of resizing the window from code on application startup, while that works, I still would like to figure out what is going on.

答:
This is quite hacky but you could try something like this:

```<code>Public Sub YourFormName.OnLoad ()
    Dim CorrectFormSize As Intager = YourFormName.Size
    YourFormName.Size = New Size(300, 300)
    System.Threading.Thread.Sleep(1000)
    YourFormName.Size = New Size(CorrectFormSize)
End Sub
</code>```

Bear in mind that this will just automate the resize process that you described.

If you want to save a few lines because you application is going to be full screen once loaded then you can skip a few lines and do this instead:

```<code>Public Sub YourFormName.OnLoad()
    YourFormName.Size = New Size(300, 300)
    System.Threading.Thread.Sleep(1000)
    YourFormName.WindowState = System.Windows.Forms.FormWindowState.Maximized
End Sub
</code>```

Body:
I have a WPF Mvvm-Light application that uses tab controls to display different views to the user.

PROBLEM:

THe problem I have is that when the program first loads the tab control displays empty.  But when debugging locally this problem never occurs.  This application has been in development for over a year without this issue and all of a sudden it started happening.  see below image

HACK FIX:

If the user resizes their window, the content in the tab control refreshes and appears and the problem never reoccurs while they have the application open.  But this issue occurs 100% of the time on first program load and first tab load (which happens at the same time)

DETAILS:

here is how I define my views that get inserted into the tab control

 <DataTemplate DataType="{x:Type FtcViewModel:DashboardNavViewModel}">
   <FtcView:DashboardNav  />
 </DataTemplate>

and here is my tab control:

<TabControl  Grid.Column="1" Grid.Row="3"
                     SelectedItem="{Binding CurrentViewModel}"
                     ItemsSource="{Binding OpenViewModelCollection}"
                     Style="{StaticResource TabControlStyle}"
                     ItemContainerStyle="{StaticResource TabItemStyle}" >
        </TabControl>

then in my view model for the main window i assign a collection to the tab control and by default set  the dashbaord as the first tab to open like this (tried to only include relevant code, obiously there is more in the viewModel file):

Public Property OpenViewModelCollection As ObservableCollection(Of ViewModelHelper)
    Get
        Return Me._OpenViewModelCollection
    End Get
    Set(value As ObservableCollection(Of ViewModelHelper))
        If _OpenViewModelCollection Is value Then
            Return
        End If
        _OpenViewModelCollection = value
        RaisePropertyChanged(OpenViewModelCollectionPropertyName)
    End Set
End Property

Public Property CurrentViewModel As ViewModelHelper
            Get
                Return Me._CurrentViewModel
            End Get
            Set(value As ViewModelHelper)
                If _CurrentViewModel Is value Then
                    Return
                End If
                ''if change of viewmodel is not from OpenTabViewModelCommandExecute method
                If FlagOpening = False AndAlso value IsNot Nothing Then

                    If _CurrentViewModel IsNot Nothing Then
                        _CurrentViewModel.HandleNavigation(True)
                    End If

                    ''Mark NavService target VM
                    _NavService.TargetViewModelKey = value.vmKey

                    ''evaluate if naviagtion has been canceled
                    If _NavService.bCanNavigate = False Then
                        _NavService.bCanNavigate = True
                        Exit Property
                    End If
                End If
                ''if navigation not canceled, finish assigning new view model
                _CurrentViewModel = value
                RaisePropertyChanged(CurrentViewModelPropertyName)
                If _CurrentViewModel IsNot Nothing Then
                    _CurrentViewModel.RefreshModel()
                End If
            End Set
        End Property
...

'' THIS CODE IS FROM THE CONSTRUCTOR OF THE VIEW MODEL CLASS
OpenViewModelCollection.Add(_Locator.DashboardHome_VM)
CurrentViewModel = OpenViewModelCollection(0)

QUESTION

can someone help me figure out why this is happening or suggest a way to refresh the UI after the first application load.

thanks in advance

UPDATE 1 - Oct 4, 2017

I have been able to reproduce this problem on my development machine.  When the UI is blank you can see that the XAML diagnostics tools don't show up. THe image below shows the same app being debugged, but the one without the XAML tools box is the one with the missing ui elements.

The following content is not being rendered inside my custom tab control style:

<ScrollViewer VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Auto" >
    <ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</ScrollViewer>

EDIT 2 Oct 11 2017

I have set breakpoints in both the xaml and code in the ViewModel.  I can confirm that the ViewModel data is correctly initialized and assigned to the observable objects.  I also inserted "test" textblocks in my tabItemTemplate to confirm which part is not showing.  Right now I have a terrible hack of resizing the window from code on application startup, while that works, I still would like to figure out what is going on.

Body:
This is quite hacky but you could try something like this:

Public Sub YourFormName.OnLoad ()
    Dim CorrectFormSize As Intager = YourFormName.Size
    YourFormName.Size = New Size(300, 300)
    System.Threading.Thread.Sleep(1000)
    YourFormName.Size = New Size(CorrectFormSize)
End Sub

Bear in mind that this will just automate the resize process that you described.

If you want to save a few lines because you application is going to be full screen once loaded then you can skip a few lines and do this instead:

Public Sub YourFormName.OnLoad()
    YourFormName.Size = New Size(300, 300)
    System.Threading.Thread.Sleep(1000)
    YourFormName.WindowState = System.Windows.Forms.FormWindowState.Maximized
End Sub