问:
SharedPreference not updating
SharedPreference not updating (changing). Please help. I'm a starter so I cannot figure it out. Please explain, not just code. Here is the MainActivity.java,  where I need the preference and colorPicker.java, where I choose the color.

MainActivity.java:

```<code>package com.example.alexsoft.tictactoe;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    boolean turn = true;
    int color = 0;
    Button A1, B1, C1, A2, B2, C2, A3, B3, C3;
    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        A1 = (Button) findViewById(R.id.A1);
        B1 = (Button) findViewById(R.id.B1);
        C1 = (Button) findViewById(R.id.C1);
        A2 = (Button) findViewById(R.id.A2);
        B2 = (Button) findViewById(R.id.B2);
        C2 = (Button) findViewById(R.id.C2);
        A3 = (Button) findViewById(R.id.A3);
        B3 = (Button) findViewById(R.id.B3);
        C3 = (Button) findViewById(R.id.C3);
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        color = prefs.getInt("com.example.alexsoft.tictactoe", R.color.colorAccent);
        changeAspect(color);
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        color = prefs.getInt("com.example.alexsoft.tictactoe", R.color.colorAccent);
        changeAspect(color);
    }

    @Override
    public void onStop() {
        super.onStop();

        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        prefs.edit().putInt("com.example.alexsoft.tictactoe", color).apply();
    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();

        //Creating an alert dialog to logout
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Do you want to exit?");
        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        startActivity(intent);
                    }
                });

        alertDialogBuilder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                    }
                });

        //Showing the alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        menu.getItem(1).setIcon(R.mipmap.ic_cached_white_24dp);
        switch(Color.rgb(Color.red(color), Color.green(color), Color.blue(color))) {
            case R.color.colorPrimary:
                menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
            case R.color.yellow:
                menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
            case R.color.lightBlue:
                menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.resGame:
                restartBtn();
                return true;
            case R.id.setAsp:
                Intent it = new Intent(getBaseContext(), colorPicker.class);
                startActivity(it);
                return true;
            case R.id.aboutBtn:
                AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                alertDialog.setTitle("About");
                alertDialog.setMessage("Tic Tac Toe, verison 1.0, created by Alex Sandulescu");
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
                return true;
            case R.id.resStats:
                TextView xCount = (TextView) findViewById(R.id.xCount);
                TextView oCount = (TextView) findViewById(R.id.oCount);
                TextView roundsPlayed = (TextView) findViewById(R.id.roundsPlayed);
                xCount.setText("0");
                oCount.setText("0");
                roundsPlayed.setText("0");
            case R.id.cMode:
                if (item.isChecked()) {
                    //item.setChecked(false);
                    AlertDialog nYet = new AlertDialog.Builder(MainActivity.this).create();
                    nYet.setMessage("Not ready yet!");
                    nYet.setTitle("Message");
                    nYet.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    nYet.show();
                } else {
                    //item.setChecked(true);
                    AlertDialog nYet = new AlertDialog.Builder(MainActivity.this).create();
                    nYet.setMessage("Not ready yet!");
                    nYet.setTitle("Message");
                    nYet.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    nYet.show();
                }
        }
        return false;
    }

    public void btnClick(View v) {
        Button b = (Button) v;
        if (b.isEnabled()) {
            if (turn == true)
                b.setText("X");
            else
                b.setText("0");
            b.setEnabled(false);
            turn = !turn;
            checkForWinner();
        }
    }

    private void checkForWinner() {
        String winner = "";
        boolean ok = false;
        if (A1.getText().equals(B1.getText()) && A1.getText().equals(C1.getText()) && !A1.getText().equals("")) {
            ok = true;
            winner = A1.getText().toString();
            A1.setTextColor(Color.RED);
            B1.setTextColor(Color.RED);
            C1.setTextColor(Color.RED);
        } else if (A2.getText().equals(B2.getText()) && A2.getText().equals(C2.getText()) && !A2.getText().equals("")) {
            ok = true;
            winner = A2.getText().toString();
            A2.setTextColor(Color.RED);
            B2.setTextColor(Color.RED);
            C2.setTextColor(Color.RED);
        } else if (A3.getText().equals(B3.getText()) && A3.getText().equals(C3.getText()) && !A3.getText().equals("")) {
            ok = true;
            winner = A3.getText().toString();
            A3.setTextColor(Color.RED);
            B3.setTextColor(Color.RED);
            C3.setTextColor(Color.RED);
        } else if (A1.getText().equals(A2.getText()) && A1.getText().equals(A3.getText()) && !A1.getText().equals("")) {
            ok = true;
            winner = A1.getText().toString();
            A1.setTextColor(Color.RED);
            A2.setTextColor(Color.RED);
            A3.setTextColor(Color.RED);
        } else if (B1.getText().equals(B2.getText()) && B1.getText().equals(B3.getText()) && !B1.getText().equals("")) {
            ok = true;
            winner = B1.getText().toString();
            B1.setTextColor(Color.RED);
            B2.setTextColor(Color.RED);
            B3.setTextColor(Color.RED);
        } else if (C1.getText().equals(C2.getText()) && C1.getText().equals(C3.getText()) && !C1.getText().equals("")) {
            ok = true;
            winner = C1.getText().toString();
            C1.setTextColor(Color.RED);
            C2.setTextColor(Color.RED);
            C3.setTextColor(Color.RED);
        } else if (A1.getText().equals(B2.getText()) && A1.getText().equals(C3.getText()) && !A1.getText().equals("")) {
            ok = true;
            winner = A1.getText().toString();
            A1.setTextColor(Color.RED);
            B2.setTextColor(Color.RED);
            C3.setTextColor(Color.RED);

        } else if (A3.getText().equals(B2.getText()) && A3.getText().equals(C1.getText()) && !A3.getText().equals("")) {
            ok = true;
            winner = A3.getText().toString();
            A3.setTextColor(Color.RED);
            B2.setTextColor(Color.RED);
            C1.setTextColor(Color.RED);
        }
        if (ok) {
            Toast.makeText(this, winner + " won!", Toast.LENGTH_LONG).show();
            if (winner.equals("X")) {
                TextView tcount = (TextView) findViewById(R.id.xCount);
                tcount.setText(Integer.toString(Integer.parseInt(tcount.getText().toString()) + 1));
            } else {
                TextView tcount = (TextView) findViewById(R.id.oCount);
                tcount.setText(Integer.toString(Integer.parseInt(tcount.getText().toString()) + 1));
            }
            A1.setEnabled(false);
            B1.setEnabled(false);
            C1.setEnabled(false);
            A2.setEnabled(false);
            B2.setEnabled(false);
            C2.setEnabled(false);
            A3.setEnabled(false);
            B3.setEnabled(false);
            C3.setEnabled(false);
        }
    }

    public void restartBtn() {
        remakeGame();
        TextView rplayed = (TextView) findViewById(R.id.roundsPlayed);
        rplayed.setText(Integer.toString(Integer.parseInt(rplayed.getText().toString()) + 1));
    }

    private void remakeGame() {
        A1.setText("");
        B1.setText("");
        C1.setText("");
        A2.setText("");
        B2.setText("");
        C2.setText("");
        A3.setText("");
        B3.setText("");
        C3.setText("");
        //
        A1.setTextColor(Color.BLACK);
        B1.setTextColor(Color.BLACK);
        C1.setTextColor(Color.BLACK);
        A2.setTextColor(Color.BLACK);
        B2.setTextColor(Color.BLACK);
        C2.setTextColor(Color.BLACK);
        A3.setTextColor(Color.BLACK);
        B3.setTextColor(Color.BLACK);
        C3.setTextColor(Color.BLACK);
        //
        A1.setEnabled(true);
        B1.setEnabled(true);
        C1.setEnabled(true);
        A2.setEnabled(true);
        B2.setEnabled(true);
        C2.setEnabled(true);
        A3.setEnabled(true);
        B3.setEnabled(true);
        C3.setEnabled(true);
        //
        turn = true;
    }

    public void changeAspect(int color) {
        if (color != 0) {
            A1.setBackgroundColor(color);
            B1.setBackgroundColor(color);
            C1.setBackgroundColor(color);
            A2.setBackgroundColor(color);
            B2.setBackgroundColor(color);
            C2.setBackgroundColor(color);
            A3.setBackgroundColor(color);
            B3.setBackgroundColor(color);
            C3.setBackgroundColor(color);
            getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                float[] hsv = new float[3];
                Color.colorToHSV(color, hsv);
                hsv[2] *= 0.8f;
                color = Color.HSVToColor(hsv);
                window.setStatusBarColor(color);
            }
        }
    }
}
</code>```

colorPicker.java:

```<code>package com.example.alexsoft.tictactoe;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class colorPicker extends Activity {

    public int color = 0;
    String xCount, oCount, roundsPlayed;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color_picker);
    }

    public void onColorConfirm(View v) {
        ImageView img = (ImageView) v;
        ColorDrawable s = (ColorDrawable) img.getDrawable();
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        SharedPreferences.Editor ed = prefs.edit();
        ed.putInt("com.example.alexsoft.tictactoe", color).apply();
        finish();
    }

    @Override
    public void onStop() {
        super.onStop();
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        prefs.edit().putInt("com.example.alexsoft.tictactoe", color).apply();
    }
}
</code>```

答:
The problem is you are not updating the value of color anywhere in your colorPicker activity. The value of color remains 0 all the time.

SOLUTION:

Update color value before storing it into SharedPreferences.

Update your code as below:

```<code>public class colorPicker extends Activity {

    public int color = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color_picker);
    }

    public void onColorConfirm(View v) {
        ImageView img = (ImageView) v;
        ColorDrawable s = (ColorDrawable) img.getDrawable();
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        SharedPreferences.Editor ed = prefs.edit();

        // Update color value
        color = SOME_VALUE;

        // Store
        ed.putInt("com.example.alexsoft.tictactoe", color).apply();
        finish();
    }
}
</code>```

Hope this will help~

Title: SharedPreference not updating

Body:
SharedPreference not updating (changing). Please help. I'm a starter so I cannot figure it out. Please explain, not just code. Here is the MainActivity.java,  where I need the preference and colorPicker.java, where I choose the color.

MainActivity.java:

package com.example.alexsoft.tictactoe;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    boolean turn = true;
    int color = 0;
    Button A1, B1, C1, A2, B2, C2, A3, B3, C3;
    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        A1 = (Button) findViewById(R.id.A1);
        B1 = (Button) findViewById(R.id.B1);
        C1 = (Button) findViewById(R.id.C1);
        A2 = (Button) findViewById(R.id.A2);
        B2 = (Button) findViewById(R.id.B2);
        C2 = (Button) findViewById(R.id.C2);
        A3 = (Button) findViewById(R.id.A3);
        B3 = (Button) findViewById(R.id.B3);
        C3 = (Button) findViewById(R.id.C3);
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        color = prefs.getInt("com.example.alexsoft.tictactoe", R.color.colorAccent);
        changeAspect(color);
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        color = prefs.getInt("com.example.alexsoft.tictactoe", R.color.colorAccent);
        changeAspect(color);
    }

    @Override
    public void onStop() {
        super.onStop();

        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        prefs.edit().putInt("com.example.alexsoft.tictactoe", color).apply();
    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();

        //Creating an alert dialog to logout
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Do you want to exit?");
        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        startActivity(intent);
                    }
                });

        alertDialogBuilder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                    }
                });

        //Showing the alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        menu.getItem(1).setIcon(R.mipmap.ic_cached_white_24dp);
        switch(Color.rgb(Color.red(color), Color.green(color), Color.blue(color))) {
            case R.color.colorPrimary:
                menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
            case R.color.yellow:
                menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
            case R.color.lightBlue:
                menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.resGame:
                restartBtn();
                return true;
            case R.id.setAsp:
                Intent it = new Intent(getBaseContext(), colorPicker.class);
                startActivity(it);
                return true;
            case R.id.aboutBtn:
                AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                alertDialog.setTitle("About");
                alertDialog.setMessage("Tic Tac Toe, verison 1.0, created by Alex Sandulescu");
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
                return true;
            case R.id.resStats:
                TextView xCount = (TextView) findViewById(R.id.xCount);
                TextView oCount = (TextView) findViewById(R.id.oCount);
                TextView roundsPlayed = (TextView) findViewById(R.id.roundsPlayed);
                xCount.setText("0");
                oCount.setText("0");
                roundsPlayed.setText("0");
            case R.id.cMode:
                if (item.isChecked()) {
                    //item.setChecked(false);
                    AlertDialog nYet = new AlertDialog.Builder(MainActivity.this).create();
                    nYet.setMessage("Not ready yet!");
                    nYet.setTitle("Message");
                    nYet.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    nYet.show();
                } else {
                    //item.setChecked(true);
                    AlertDialog nYet = new AlertDialog.Builder(MainActivity.this).create();
                    nYet.setMessage("Not ready yet!");
                    nYet.setTitle("Message");
                    nYet.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    nYet.show();
                }
        }
        return false;
    }

    public void btnClick(View v) {
        Button b = (Button) v;
        if (b.isEnabled()) {
            if (turn == true)
                b.setText("X");
            else
                b.setText("0");
            b.setEnabled(false);
            turn = !turn;
            checkForWinner();
        }
    }

    private void checkForWinner() {
        String winner = "";
        boolean ok = false;
        if (A1.getText().equals(B1.getText()) && A1.getText().equals(C1.getText()) && !A1.getText().equals("")) {
            ok = true;
            winner = A1.getText().toString();
            A1.setTextColor(Color.RED);
            B1.setTextColor(Color.RED);
            C1.setTextColor(Color.RED);
        } else if (A2.getText().equals(B2.getText()) && A2.getText().equals(C2.getText()) && !A2.getText().equals("")) {
            ok = true;
            winner = A2.getText().toString();
            A2.setTextColor(Color.RED);
            B2.setTextColor(Color.RED);
            C2.setTextColor(Color.RED);
        } else if (A3.getText().equals(B3.getText()) && A3.getText().equals(C3.getText()) && !A3.getText().equals("")) {
            ok = true;
            winner = A3.getText().toString();
            A3.setTextColor(Color.RED);
            B3.setTextColor(Color.RED);
            C3.setTextColor(Color.RED);
        } else if (A1.getText().equals(A2.getText()) && A1.getText().equals(A3.getText()) && !A1.getText().equals("")) {
            ok = true;
            winner = A1.getText().toString();
            A1.setTextColor(Color.RED);
            A2.setTextColor(Color.RED);
            A3.setTextColor(Color.RED);
        } else if (B1.getText().equals(B2.getText()) && B1.getText().equals(B3.getText()) && !B1.getText().equals("")) {
            ok = true;
            winner = B1.getText().toString();
            B1.setTextColor(Color.RED);
            B2.setTextColor(Color.RED);
            B3.setTextColor(Color.RED);
        } else if (C1.getText().equals(C2.getText()) && C1.getText().equals(C3.getText()) && !C1.getText().equals("")) {
            ok = true;
            winner = C1.getText().toString();
            C1.setTextColor(Color.RED);
            C2.setTextColor(Color.RED);
            C3.setTextColor(Color.RED);
        } else if (A1.getText().equals(B2.getText()) && A1.getText().equals(C3.getText()) && !A1.getText().equals("")) {
            ok = true;
            winner = A1.getText().toString();
            A1.setTextColor(Color.RED);
            B2.setTextColor(Color.RED);
            C3.setTextColor(Color.RED);

        } else if (A3.getText().equals(B2.getText()) && A3.getText().equals(C1.getText()) && !A3.getText().equals("")) {
            ok = true;
            winner = A3.getText().toString();
            A3.setTextColor(Color.RED);
            B2.setTextColor(Color.RED);
            C1.setTextColor(Color.RED);
        }
        if (ok) {
            Toast.makeText(this, winner + " won!", Toast.LENGTH_LONG).show();
            if (winner.equals("X")) {
                TextView tcount = (TextView) findViewById(R.id.xCount);
                tcount.setText(Integer.toString(Integer.parseInt(tcount.getText().toString()) + 1));
            } else {
                TextView tcount = (TextView) findViewById(R.id.oCount);
                tcount.setText(Integer.toString(Integer.parseInt(tcount.getText().toString()) + 1));
            }
            A1.setEnabled(false);
            B1.setEnabled(false);
            C1.setEnabled(false);
            A2.setEnabled(false);
            B2.setEnabled(false);
            C2.setEnabled(false);
            A3.setEnabled(false);
            B3.setEnabled(false);
            C3.setEnabled(false);
        }
    }

    public void restartBtn() {
        remakeGame();
        TextView rplayed = (TextView) findViewById(R.id.roundsPlayed);
        rplayed.setText(Integer.toString(Integer.parseInt(rplayed.getText().toString()) + 1));
    }

    private void remakeGame() {
        A1.setText("");
        B1.setText("");
        C1.setText("");
        A2.setText("");
        B2.setText("");
        C2.setText("");
        A3.setText("");
        B3.setText("");
        C3.setText("");
        //
        A1.setTextColor(Color.BLACK);
        B1.setTextColor(Color.BLACK);
        C1.setTextColor(Color.BLACK);
        A2.setTextColor(Color.BLACK);
        B2.setTextColor(Color.BLACK);
        C2.setTextColor(Color.BLACK);
        A3.setTextColor(Color.BLACK);
        B3.setTextColor(Color.BLACK);
        C3.setTextColor(Color.BLACK);
        //
        A1.setEnabled(true);
        B1.setEnabled(true);
        C1.setEnabled(true);
        A2.setEnabled(true);
        B2.setEnabled(true);
        C2.setEnabled(true);
        A3.setEnabled(true);
        B3.setEnabled(true);
        C3.setEnabled(true);
        //
        turn = true;
    }

    public void changeAspect(int color) {
        if (color != 0) {
            A1.setBackgroundColor(color);
            B1.setBackgroundColor(color);
            C1.setBackgroundColor(color);
            A2.setBackgroundColor(color);
            B2.setBackgroundColor(color);
            C2.setBackgroundColor(color);
            A3.setBackgroundColor(color);
            B3.setBackgroundColor(color);
            C3.setBackgroundColor(color);
            getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                float[] hsv = new float[3];
                Color.colorToHSV(color, hsv);
                hsv[2] *= 0.8f;
                color = Color.HSVToColor(hsv);
                window.setStatusBarColor(color);
            }
        }
    }
}

colorPicker.java:

package com.example.alexsoft.tictactoe;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class colorPicker extends Activity {

    public int color = 0;
    String xCount, oCount, roundsPlayed;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color_picker);
    }

    public void onColorConfirm(View v) {
        ImageView img = (ImageView) v;
        ColorDrawable s = (ColorDrawable) img.getDrawable();
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        SharedPreferences.Editor ed = prefs.edit();
        ed.putInt("com.example.alexsoft.tictactoe", color).apply();
        finish();
    }

    @Override
    public void onStop() {
        super.onStop();
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        prefs.edit().putInt("com.example.alexsoft.tictactoe", color).apply();
    }
}

Body:
The problem is you are not updating the value of color anywhere in your colorPicker activity. The value of color remains 0 all the time.

SOLUTION:

Update color value before storing it into SharedPreferences.

Update your code as below:

public class colorPicker extends Activity {

    public int color = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color_picker);
    }

    public void onColorConfirm(View v) {
        ImageView img = (ImageView) v;
        ColorDrawable s = (ColorDrawable) img.getDrawable();
        SharedPreferences prefs = this.getSharedPreferences(
                "com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
        SharedPreferences.Editor ed = prefs.edit();

        // Update color value
        color = SOME_VALUE;

        // Store
        ed.putInt("com.example.alexsoft.tictactoe", color).apply();
        finish();
    }
}

Hope this will help~


来源: stackexchange

问:
How OrderBy afterwards HasMany and BelongsTo Relationships
I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.

```<code>Models: Review
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
    }
Models: Giochi
    public function review()
    {
            return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
    }
    public function infogiochi()
    {
            return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
    }
Models: InfoGiochi
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
    }
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();
</code>```

Here is a screenshot of my json:

How do I order content for review table IDs?

答:
You have 2 options. You use a join and order in the sql statement or you order it after retrieving the results in the collection.

Using Join

```<code>Giochi::select('giocos.*')
    ->with('Review','InfoGiochi')
    ->leftJoin('reviews', 'reviews.id', '=', 'giocos.id_gioco')
    ->orderBy('reviews.id','DESC')
    ->get();
</code>```

Sorting Collection

```<code>Giochi::with('Review','InfoGiochi')
    ->get()
    ->sortByDesc(function($giochi) {
        return $giochi->review->id;
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.

Models: Review
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
    }
Models: Giochi
    public function review()
    {
            return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
    }
    public function infogiochi()
    {
            return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
    }
Models: InfoGiochi
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
    }
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();

Here is a screenshot of my json:

How do I order content for review table IDs?

Body:
You have 2 options. You use a join and order in the sql statement or you order it after retrieving the results in the collection.

Using Join

Giochi::select('giocos.*')
    ->with('Review','InfoGiochi')
    ->leftJoin('reviews', 'reviews.id', '=', 'giocos.id_gioco')
    ->orderBy('reviews.id','DESC')
    ->get();

Sorting Collection

Giochi::with('Review','InfoGiochi')
    ->get()
    ->sortByDesc(function($giochi) {
        return $giochi->review->id;
    });


问:
SQL Create variables from 2 different tables
I have 2 different tables called observations and intervals.

observations:

id,

type,

date

1 recess 03.05.2011 17:00

2 recess 03.06.2011 12:00

intervals:

id,

observation id,

value

1 1 5

2 1 8

3 2 4

4 2 4

I want a view that will display:

observation_id

percent_positive ((count where value = 5)/(total number of observations))

1 .5

2 0

I know

```<code>Select observation_id, Count(*) from intervals where value = 5 Group by
observation_id
</code>```

will give me:

1 1

1 0

and

```<code>Select observation_id, Count(*) from intervals Group by
observation_id
</code>```

will give me:

1 2

2 2

So how do I combine these to create a view with the percent_positive variable I'm looking for?

答:
```<code>SELECT
    i.observation_id,
    SUM(IF(i.value=5,1,0)) / counts.num as 'percent_positive'
FROM intervals i
inner join (
    select observation_id, count(1) as num from intervals group by observation_id
) counts on counts.observation_id = i.observation_id
group by i.observation_id
order by i.observation_id
;
</code>```

That oughta get you close, can't actually run to test at the moment.  I'm not sure about the significance of the value 5 meaning positive, so the i.value=5 test might need to be modified to do what you want.  This will only include observation IDs with intervals that refer to them; if you want ALL observations then you'll need to join that table (select from that table and left join the others, to be precise).  Of course the percentage for those IDs will be 0 divided by 0 anyway...

Body:
I have 2 different tables called observations and intervals.

observations:

id,

type,

date

1 recess 03.05.2011 17:00

2 recess 03.06.2011 12:00

intervals:

id,

observation id,

value

1 1 5

2 1 8

3 2 4

4 2 4

I want a view that will display:

observation_id

percent_positive ((count where value = 5)/(total number of observations))

1 .5

2 0

I know

Select observation_id, Count(*) from intervals where value = 5 Group by
observation_id

will give me:

1 1

1 0

and

Select observation_id, Count(*) from intervals Group by
observation_id

will give me:

1 2

2 2

So how do I combine these to create a view with the percent_positive variable I'm looking for?

Body:
SELECT
    i.observation_id,
    SUM(IF(i.value=5,1,0)) / counts.num as 'percent_positive'
FROM intervals i
inner join (
    select observation_id, count(1) as num from intervals group by observation_id
) counts on counts.observation_id = i.observation_id
group by i.observation_id
order by i.observation_id
;

That oughta get you close, can't actually run to test at the moment.  I'm not sure about the significance of the value 5 meaning positive, so the i.value=5 test might need to be modified to do what you want.  This will only include observation IDs with intervals that refer to them; if you want ALL observations then you'll need to join that table (select from that table and left join the others, to be precise).  Of course the percentage for those IDs will be 0 divided by 0 anyway...


问:
Cannot assign to 'Boolean' because it is a constant or a read-only property
I am creating a typescript object to represent read/write permissions in my app, but I came across this quirk in assigning the variables that makes no sense to me.  Hopefully, someone can look at this and tell me what I am doing wrong.

```<code>export class Permission {
       watcher:Object =  { read:Boolean = true};
}
</code>```

The previous code results in a error which says:

[ts] Cannot assign to 'Boolean' because it is a constant or a read-only property.
const Boolean: BooleanConstructor

I'm probably just doing something stupid, so apologies in advance if this is super newbish.

答:
You are trying to assign a JSON object with { read: true }, declaring it as type Boolean is just redundant (because true and false are always Boolean) typescript infers the type, and it's an invalid JSON structure.

JSON has this format:

```<code>{
  key: value,
  key2: value2
}
</code>```

Notice there are no equal signs (=) in a JSON, only : to separate the keys and values.

Now I see the class syntax is confusing you, because it does have an equal sign, but It's only for the assignment. After the assignment you don't need to have an equals sign.

Your final class definition should look something like this:

```<code>export class Permission {
    watcher = { read: true };
}
</code>```

You would need interfaces for more complex objects, in case you want optional variables or dependencies on other objects.
For a small object typescript will understand the structure by the types.

Body:
I am creating a typescript object to represent read/write permissions in my app, but I came across this quirk in assigning the variables that makes no sense to me.  Hopefully, someone can look at this and tell me what I am doing wrong.

export class Permission {
       watcher:Object =  { read:Boolean = true};
}

The previous code results in a error which says:

[ts] Cannot assign to 'Boolean' because it is a constant or a read-only property.
const Boolean: BooleanConstructor

I'm probably just doing something stupid, so apologies in advance if this is super newbish.

Body:
You are trying to assign a JSON object with { read: true }, declaring it as type Boolean is just redundant (because true and false are always Boolean) typescript infers the type, and it's an invalid JSON structure.

JSON has this format:

{
  key: value,
  key2: value2
}

Notice there are no equal signs (=) in a JSON, only : to separate the keys and values.

Now I see the class syntax is confusing you, because it does have an equal sign, but It's only for the assignment. After the assignment you don't need to have an equals sign.

Your final class definition should look something like this:

export class Permission {
    watcher = { read: true };
}

You would need interfaces for more complex objects, in case you want optional variables or dependencies on other objects.
For a small object typescript will understand the structure by the types.


问:
Creating an objective-c file creation event stream
I'm trying to create a stream to monitor a few directories for new files but I've had no luck.

Bonus points if your solution recursively searches the directories.

答: Have you read the "Tracking File-System Changes" section of the File-System Performance Guidelines - this and the NSWorkspace class reference should tell you everything you need to know.</p>

ContentLicense: CC BY-SA 2.5


问:
Angular 1.5.x Routing Not Working
I've looked at dozens of questions here about Angular routing but haven't been able to get this working. I apologize if I overlooked anything. I've been trying to use the Angularjs official tutorial and seed repository to get a simple app off the ground. This code is hosted on a web server but for this purpose, I copied my code over to Plunker here. The code is also below - thank you for any insight you might provide.

Index.html

```<code><!DOCTYPE html>
<html ng-app>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular-route.js"></script>
    <script type="text/javascript" src="script1.js"></script>
    <script type="text/javascript" src="script2.js"></script>
    <script type="text/javascript" src="script3.js"></script>
  </head>

  <body>
    <header ng-include="'header.html'"></header>
    <div ng-view></div>
  </body>

</html>
</code>```

home.html

```<code><div ng-controller='homeCtrl'>
    <h2>{{ location }}</h2>
    <p>This is the home page content.</p>
    <a href='#faq'>FAQ</a>
</div>
</code>```

faq.html

```<code><div ng-controller='faqCtrl'>
    <h2>This is the FAQ.</h2>
    <p>{{ question }}</p>
</div>
</code>```

Script1

```<code>angular.module('testApp', [
    'ngRoute',
    'home',
    'faq'
])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.otherwise('/');
}]);
</code>```

Script2

```<code>angular.module('home', ['ngRoute'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/', {
        templateUrl : 'home.html',
        controller : 'homeCtrl'
    });
}])

.controller('homeCtrl', [function ($scope) {
    $scope.location = 'USA';
}]);
</code>```

Script3

```<code>angular.module('faq', ['ngRoute'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/faq', {
        templateUrl : 'faq.html',
        controller : 'faqCtrl'
    });
}])

.controller('faqCtrl', [function ($scope) {
    $scope.question = 'Who am I?';
}]);
</code>```

答:
You have some typos/omissions in your app:

In index.html, you are missing the app name in ng-app:

```<code><html ng-app="testApp">
</code>```

In your "home" and "faq" controllers, you need to use the correct syntax for the injections:

Use:

```<code>.controller('homeCtrl', ['$scope', function ($scope) {
</code>```

Instead of:

```<code>.controller('homeCtrl', [function ($scope) {
</code>```

Finally, in home.html and faq.html, do not use ng-controller at all. In your route definitions, you are specifying the controller to use for each route. Specifying it again inside the template will result in a second controller being instantiated.

Plnkr

Title: Angular 1.5.x Routing Not Working

Body:
I've looked at dozens of questions here about Angular routing but haven't been able to get this working. I apologize if I overlooked anything. I've been trying to use the Angularjs official tutorial and seed repository to get a simple app off the ground. This code is hosted on a web server but for this purpose, I copied my code over to Plunker here. The code is also below - thank you for any insight you might provide.

Index.html

<!DOCTYPE html>

home.html

{{ location }}

This is the home page content.

    FAQ

faq.html

This is the FAQ.

{{ question }}

Script1

angular.module('testApp', [
    'ngRoute',
    'home',
    'faq'
])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.otherwise('/');
}]);

Script2

angular.module('home', ['ngRoute'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/', {
        templateUrl : 'home.html',
        controller : 'homeCtrl'
    });
}])

.controller('homeCtrl', [function ($scope) {
    $scope.location = 'USA';
}]);

Script3

angular.module('faq', ['ngRoute'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/faq', {
        templateUrl : 'faq.html',
        controller : 'faqCtrl'
    });
}])

.controller('faqCtrl', [function ($scope) {
    $scope.question = 'Who am I?';
}]);

Body:
You have some typos/omissions in your app:

In index.html, you are missing the app name in ng-app:

<html ng-app="testApp">

In your "home" and "faq" controllers, you need to use the correct syntax for the injections:

Use:

.controller('homeCtrl', ['$scope', function ($scope) {

Instead of:

.controller('homeCtrl', [function ($scope) {

Finally, in home.html and faq.html, do not use ng-controller at all. In your route definitions, you are specifying the controller to use for each route. Specifying it again inside the template will result in a second controller being instantiated.

Plnkr


问:
How to parse JSON having different keys in each array element using POJO classes in android
I have this response coming from server. I want to parse that using pojo classes. I have created pojo classes having setter and getter methods which holds values.But the logic which I am using is not working properly.While I'm printing values it was not returning values exactly.

Response:

```<code>{
        "code":200,
        "status":"ok",
        "message":"Promotions feed.",
        "data":{
        "feed":[
        {
        "id":0,
        "businessId":0,
      "photoUrl":"https:\/\/d1e6yi6s3cx2ur.cloudfront.net\/videos\/0\/8b84c9c1-50ed-4e93-9785-797bbf2be667.png",
        "videoUrl":"https:\/\/d1e6yi6s3cx2ur.cloudfront.net\/videos\/0\/_464b2fb6-ede6-403f-b6ae-1666c9504337.mov",
        "isNew":true,
        "type":"news"
        },
        {
        "id":198,
        "specialType":"limited",
        "name":"Big Data Shoes!",
        "description":"Get them now while you can. They're dangerous!",
        "start":"2017-06-04 14:59:01Z",
        "end":"2018-01-26 19:00:00Z",
        "limitedAmount":30,
        "countInfo":{
        "views":70,
        "likes":0,
        "liked":false,
        "type":"count_info"
        },
        "type":"special"
        },
        {
        "id":"1616636",
        "partnerId":3,
        "uuid":"57dacc36-abac-4bb3-89a4-f1981130b206",
        "type":"partner_offer"
        }
     ]
   }
}
</code>```

FeedPojo.java

```<code>public class FeedPojo {

    private static String id;
    private static String businessId;
    private static String photoUrl;
    private static String videoUrl;
    public static String getId() {
        return id;
    }
    public static void setId(String id) {
        FeedPojo.id = id;
    }

    public static String getPartnerId() {
        return partnerId;
    }

    public static void setPartnerId(String partnerId) {
        FeedPojo.partnerId = partnerId;
    }
   }
</code>```

MainActivity.java

```<code>FeedPojo.setType(promoJsonObject.getString("type"));

Log.d(TAG, "TypeFeed:" + FeedPojo.getType());
Log.e(TAG, "Type:" + promoJsonObject.getString("type"));
             if (promoJsonObject.getString("type") == "news") {

                                        FeedPojo.setId(promoJsonObject.getString("id"));
                                        FeedPojo.setBusinessName(promoJsonObject.getString("businessName"));
                                        FeedPojo.setBusinessLogoUrl(promoJsonObject.getString("businessLogoUrl"));
                                        FeedPojo.setText(promoJsonObject.getString("text"));

 Log.d(TAG,"Id"+FeedPojo.getId());
                                        Log.d(TAG,"Businessname"+FeedPojo.getBusinessName());

                                    }
                                    if (FeedPojo.getType() == "special") {

                                        FeedPojo.setId(promoJsonObject.getString("id"));
                                        FeedPojo.setType(promoJsonObject.getString("type"));
                                        FeedPojo.setName(promoJsonObject.getString("name"));
                                        FeedPojo.setDescription(promoJsonObject.getString("description"));
                                        FeedPojo.setStart(promoJsonObject.getString("start"));
                                        FeedPojo.setEnd(promoJsonObject.getString("end"));
                }
</code>```

答:
We can parse like this,
FeedPojo.java

```<code>public class FeedPojo {
    int id;
    int businessId;
    int limitedAmount;
    int views;
    int likes;
    int partnerId;
    String photoUrl;
    String videoUrl;
    String type;
    String specialType;
    String name;
    String description;
    String start;
    String end;
    String countInfoType;
    String uuid;
    boolean isNew;
    boolean liked;
}
</code>```

FeedParser.java

```<code>public class FeedParser {
    public static void parse(String response) {
        try {
            JSONObject feedObject = new JSONObject(response);

            if (feedObject == null) {
                return;
            }

            JSONArray feedArray = feedObject.optJSONArray("feed");

            if (feedArray == null) {
                return;
            }

            ArrayList<FeedPojo> feedPojos = new ArrayList<>();
            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feed = feedArray.optJSONObject(i);

                if (feed == null) {
                    continue;
                }

                FeedPojo feedPojo = new FeedPojo();
                feedPojo.id = feed.optInt("id", 0);
                feedPojo.businessId = feed.optInt("businessId", 0);
                feedPojo.limitedAmount = feed.optInt("limitedAmount", 0);
                feedPojo.partnerId = feed.optInt("partnerId", 0);

                feedPojo.photoUrl = feed.optString("photoUrl", "");
                feedPojo.type = feed.optString("type", "");
                feedPojo.specialType = feed.optString("specialType", "");
                feedPojo.name = feed.optString("name", "");
                feedPojo.description = feed.optString("description", "");
                feedPojo.start = feed.optString("start", "");
                feedPojo.end = feed.optString("end", "");
                feedPojo.uuid = feed.optString("uuid", "");

                feedPojo.isNew = feed.optBoolean("isNew", false);
                feedPojo.isNew = feed.optBoolean("isNew", false);

                JSONObject countInfoObj = feed.optJSONObject("countInfo");

                if (countInfoObj == null) {

                    feedPojos.add(feedPojo);
                    continue;
                }

                feedPojo.views = countInfoObj.optInt("views", 0);
                feedPojo.likes = countInfoObj.optInt("likes", 0);
                feedPojo.liked = countInfoObj.optBoolean("liked", false);
                feedPojo.countInfoType = countInfoObj.optString("type", "");

                feedPojos.add(feedPojo);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I have this response coming from server. I want to parse that using pojo classes. I have created pojo classes having setter and getter methods which holds values.But the logic which I am using is not working properly.While I'm printing values it was not returning values exactly.

Response:

{
        "code":200,
        "status":"ok",
        "message":"Promotions feed.",
        "data":{
        "feed":[
        {
        "id":0,
        "businessId":0,
      "photoUrl":"https:\/\/d1e6yi6s3cx2ur.cloudfront.net\/videos\/0\/8b84c9c1-50ed-4e93-9785-797bbf2be667.png",
        "videoUrl":"https:\/\/d1e6yi6s3cx2ur.cloudfront.net\/videos\/0\/_464b2fb6-ede6-403f-b6ae-1666c9504337.mov",
        "isNew":true,
        "type":"news"
        },
        {
        "id":198,
        "specialType":"limited",
        "name":"Big Data Shoes!",
        "description":"Get them now while you can. They're dangerous!",
        "start":"2017-06-04 14:59:01Z",
        "end":"2018-01-26 19:00:00Z",
        "limitedAmount":30,
        "countInfo":{
        "views":70,
        "likes":0,
        "liked":false,
        "type":"count_info"
        },
        "type":"special"
        },
        {
        "id":"1616636",
        "partnerId":3,
        "uuid":"57dacc36-abac-4bb3-89a4-f1981130b206",
        "type":"partner_offer"
        }
     ]
   }
}

FeedPojo.java

public class FeedPojo {

    private static String id;
    private static String businessId;
    private static String photoUrl;
    private static String videoUrl;
    public static String getId() {
        return id;
    }
    public static void setId(String id) {
        FeedPojo.id = id;
    }

    public static String getPartnerId() {
        return partnerId;
    }

    public static void setPartnerId(String partnerId) {
        FeedPojo.partnerId = partnerId;
    }
   }

MainActivity.java

FeedPojo.setType(promoJsonObject.getString("type"));

Log.d(TAG, "TypeFeed:" + FeedPojo.getType());
Log.e(TAG, "Type:" + promoJsonObject.getString("type"));
             if (promoJsonObject.getString("type") == "news") {

                                        FeedPojo.setId(promoJsonObject.getString("id"));
                                        FeedPojo.setBusinessName(promoJsonObject.getString("businessName"));
                                        FeedPojo.setBusinessLogoUrl(promoJsonObject.getString("businessLogoUrl"));
                                        FeedPojo.setText(promoJsonObject.getString("text"));

 Log.d(TAG,"Id"+FeedPojo.getId());
                                        Log.d(TAG,"Businessname"+FeedPojo.getBusinessName());

                                    }
                                    if (FeedPojo.getType() == "special") {

                                        FeedPojo.setId(promoJsonObject.getString("id"));
                                        FeedPojo.setType(promoJsonObject.getString("type"));
                                        FeedPojo.setName(promoJsonObject.getString("name"));
                                        FeedPojo.setDescription(promoJsonObject.getString("description"));
                                        FeedPojo.setStart(promoJsonObject.getString("start"));
                                        FeedPojo.setEnd(promoJsonObject.getString("end"));
                }

Body:
We can parse like this,
FeedPojo.java

public class FeedPojo {
    int id;
    int businessId;
    int limitedAmount;
    int views;
    int likes;
    int partnerId;
    String photoUrl;
    String videoUrl;
    String type;
    String specialType;
    String name;
    String description;
    String start;
    String end;
    String countInfoType;
    String uuid;
    boolean isNew;
    boolean liked;
}

FeedParser.java

public class FeedParser {
    public static void parse(String response) {
        try {
            JSONObject feedObject = new JSONObject(response);

            if (feedObject == null) {
                return;
            }

            JSONArray feedArray = feedObject.optJSONArray("feed");

            if (feedArray == null) {
                return;
            }

            ArrayList<FeedPojo> feedPojos = new ArrayList<>();
            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feed = feedArray.optJSONObject(i);

                if (feed == null) {
                    continue;
                }

                FeedPojo feedPojo = new FeedPojo();
                feedPojo.id = feed.optInt("id", 0);
                feedPojo.businessId = feed.optInt("businessId", 0);
                feedPojo.limitedAmount = feed.optInt("limitedAmount", 0);
                feedPojo.partnerId = feed.optInt("partnerId", 0);

                feedPojo.photoUrl = feed.optString("photoUrl", "");
                feedPojo.type = feed.optString("type", "");
                feedPojo.specialType = feed.optString("specialType", "");
                feedPojo.name = feed.optString("name", "");
                feedPojo.description = feed.optString("description", "");
                feedPojo.start = feed.optString("start", "");
                feedPojo.end = feed.optString("end", "");
                feedPojo.uuid = feed.optString("uuid", "");

                feedPojo.isNew = feed.optBoolean("isNew", false);
                feedPojo.isNew = feed.optBoolean("isNew", false);

                JSONObject countInfoObj = feed.optJSONObject("countInfo");

                if (countInfoObj == null) {

                    feedPojos.add(feedPojo);
                    continue;
                }

                feedPojo.views = countInfoObj.optInt("views", 0);
                feedPojo.likes = countInfoObj.optInt("likes", 0);
                feedPojo.liked = countInfoObj.optBoolean("liked", false);
                feedPojo.countInfoType = countInfoObj.optString("type", "");

                feedPojos.add(feedPojo);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}


问:
Could not Signup for Windows Azure
I am a developer from Nepal. I tried to create a account for developing application using Windows Azure. But I could not complete my signup for my windows azure account.
Is Windows Azure account limited to some countries?
Are there any alternatives to create Windows Azure account?</p>

答: You need to apply for student subscription. Azure is free for learner with limited credit. You need either subscription key or forward you microsoft account. I might help you by transfer certain credit from my MSDN subscription.</p>

Title: Could not Signup for Windows Azure


问:
How do you store preferences on multilanguage apps?
Lets say I save a position setting by its string Top.
Upon changing app language, that string becomes meaningless since in the new language it would be Arriba for example, and those those strings aren't equal.

So I have to store the position value 1 because it would be the same across languages.

But then the summary for the preference becomes 1 instead of whatever way "Top" is translated to in that other language.

So I map the code to the position text 1 -> Top for summary displaying purposes only and leave the position code alone.

I still have to translate back and forth everywhere that setting is displayed to the user (if it ever is), along with maintaining the arrays with the codes for each preference on each language and the mapping itself.

The upside is that i can use and apply the setting to the app by its code without mapping it back from its name beforehand and the fact that the app translates the code to it's string upon displaying the preferences (using the code from "Settings Activity" for that).

So I wonder, how do you manage this so it doesn't become unmanageable or comes back to bite you down the road?

答:
Since enum are to be avoided as per documentation, this is what i did:

Defined two arrays; one for the language string and one for the code in arrays.xml

```<code><string-array name="lang">
    <item>Inglés</item>
    <item>Español</item>
</string-array>

<string-array name="langCode">
    <item>EN</item>
    <item>ES</item>
</string-array>
</code>```

In code I loaded both string-arrays into arrays and compared the code to obtain the language for key:

```<code>public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
    Preference preference = findPreference(key);
    String arrayLang[] = getResources().getStringArray(R.array.lang);
    String arrayCode[] = getResources().getStringArray(R.array.langCode);
    for (int i = 0; i < arrayCode.length; i++) {
         if (arrayCode[i].contains(key)) {
             preference.setSummary(arrayLang[i]);
         }
    }
</code>```

So now I keep langCode array in every language and only translate the names.

May not be the best way but it does the job.

Body:
Since enum are to be avoided as per documentation, this is what i did:

Defined two arrays; one for the language string and one for the code in arrays.xml

<string-array name="lang">
    <item>Inglés</item>
    <item>Español</item>
</string-array>

<string-array name="langCode">
    <item>EN</item>
    <item>ES</item>
</string-array>

In code I loaded both string-arrays into arrays and compared the code to obtain the language for key:

public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
    Preference preference = findPreference(key);
    String arrayLang[] = getResources().getStringArray(R.array.lang);
    String arrayCode[] = getResources().getStringArray(R.array.langCode);
    for (int i = 0; i < arrayCode.length; i++) {
         if (arrayCode[i].contains(key)) {
             preference.setSummary(arrayLang[i]);
         }
    }

So now I keep langCode array in every language and only translate the names.

May not be the best way but it does the job.


问:
Swift drawing code behaves differently on tvOS than iOS
The company that I work for has both an iOS and a tvOS version of an app. The app draws a script at the bottom for the user to keep up during a workout, like so:

This has worked fine for more than a year in any app targeted for iOS. However, when targeting tvOS, with the same drawing code, instead of drawing the way I would expect, the tvOS view has what I'll call "traces" left after drawing each line, as opposed to just having the one line for the current time.

The drawing code is as follows:

```<code>    func addIndicatorLine(_ context:CGContext?, rect: CGRect, start: CGPoint, color: UIColor = UIColor.white) {
    context!.translateBy(x: rect.origin.x, y: rect.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setLineWidth(1.0)

    context!.setStrokeColor(color.cgColor)
    context!.move(to: CGPoint(x: start.x, y: 0))

    context!.addLine(to: CGPoint(x: start.x, y: rect.size.height - 5))
    context!.strokePath()
    context!.scaleBy(x: 1.0, y: -1.0)
    context!.translateBy(x: -rect.origin.x, y: -rect.height)
}
</code>```

Am I missing something obvious, or is there something different I have to do for the tvOS version of the drawing code?

答:
So after a couple of days of trying to figure this out, thanks to one answer (https://stackoverflow.com/a/43898524/2820553) that pointed out a line in the docs to me, I needed to give my view a background color, otherwise drawing errors may occur:

If the view’s opaque property is also set to YES, the backgroundColor property of the view must not be nil or drawing errors may occur.

Simply setting the view's background to a clear color solved this issue. Amazing that it didn't manifest in iOS but did in tvOS. Hope this helps anyone else looking for something similar.

Body:
The company that I work for has both an iOS and a tvOS version of an app. The app draws a script at the bottom for the user to keep up during a workout, like so:

This has worked fine for more than a year in any app targeted for iOS. However, when targeting tvOS, with the same drawing code, instead of drawing the way I would expect, the tvOS view has what I'll call "traces" left after drawing each line, as opposed to just having the one line for the current time.

The drawing code is as follows:

    func addIndicatorLine(_ context:CGContext?, rect: CGRect, start: CGPoint, color: UIColor = UIColor.white) {
    context!.translateBy(x: rect.origin.x, y: rect.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setLineWidth(1.0)

    context!.setStrokeColor(color.cgColor)
    context!.move(to: CGPoint(x: start.x, y: 0))

    context!.addLine(to: CGPoint(x: start.x, y: rect.size.height - 5))
    context!.strokePath()
    context!.scaleBy(x: 1.0, y: -1.0)
    context!.translateBy(x: -rect.origin.x, y: -rect.height)
}

Am I missing something obvious, or is there something different I have to do for the tvOS version of the drawing code?


问:
Parcelable encountered IOException writing serializable object getactivity()
so I am getting this in logcat:

```<code>java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student)
</code>```

I know this means that my student class is not serializable, but it is, here is my student class:

```<code>import java.io.Serializable;

public class Student implements Comparable<Student>,  Serializable{

    private static final long serialVersionUID = 1L;
    private String firstName, lastName;
    private DSLL<Grade> gradeList;

    public Student() {
        firstName = "";
        lastName = "";
        gradeList = new DSLL<Grade>();
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public DSLL<Grade> getGradeList() {
        return gradeList;
    }

    public void setGradeList(DSLL<Grade> gradeList) {
        this.gradeList = gradeList;
    }

    public int compareTo(Student arg0) {
        return this.lastName.compareTo(arg0.getLastName());
    }

}
</code>```

and this is the code that is using the getIntent() method:

```<code>public void onItemClick(AdapterView<?> parent, View viewClicked, int pos,
                                long id) {

                            Student clickedStudent = studentList.get(pos);
                            int position = pos;
                            Intent intent = new Intent(getActivity().getApplicationContext(), ShowStudentActivity.class);
                            Log.e("CINTENT","CREATED!!!");
                            intent.putExtra("clickedStudent",clickedStudent);
                            intent.putExtra("newStudentList",newStudentList);
                            intent.putExtra("position",position);
                            Log.e("putExtra","Passed");
                            Log.e("Start activity","passed");
                            startActivity(intent);

                        }

                    });
</code>```

please help me figure out whats wrong with this.

here is the whole LogCat:

```<code>04-17 16:12:28.890: E/AndroidRuntime(22815): FATAL EXCEPTION: main
04-17 16:12:28.890: E/AndroidRuntime(22815): java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeSerializable(Parcel.java:1181)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeValue(Parcel.java:1135)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeMapInternal(Parcel.java:493)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Bundle.writeToParcel(Bundle.java:1612)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeBundle(Parcel.java:507)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.content.Intent.writeToParcel(Intent.java:6111)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1613)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1422)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.Activity.startActivityForResult(Activity.java:3191)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:848)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.support.v4.app.Fragment.startActivity(Fragment.java:878)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.example.student_lists.MainActivity$DummySectionFragment$2.onItemClick(MainActivity.java:477)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AdapterView.performItemClick(AdapterView.java:292)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView$1.run(AbsListView.java:3168)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Handler.handleCallback(Handler.java:605)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Looper.loop(Looper.java:137)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.ActivityThread.main(ActivityThread.java:4447)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.lang.reflect.Method.invokeNative(Native Method)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.lang.reflect.Method.invoke(Method.java:511)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at dalvik.system.NativeStart.main(Native Method)
04-17 16:12:28.890: E/AndroidRuntime(22815): Caused by: java.io.NotSerializableException: com.resources.student_list.DSLL$DNode
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeSerializable(Parcel.java:1176)
</code>```

答:
The problem occurs when your custom class has for property some other class e.g. "Bitmap". What I made is to change the property field from  "private Bitmap photo" to "private transient Bitmap photo". However the image is empty after I getIntent() in the receiver activity. Because of this I passed the custom class to the intent and also I've created a  byte array from the image and pass it separatly to the intent:

selectedItem is my custom object and getPlacePhoto is his method to get image. I've already set it before and now I just get it first than convert it and pass it separatly:

```<code> Bitmap image = selectedItem.getPlacePhoto();
 image.compress(Bitmap.CompressFormat.PNG, 100, stream);
 byte[] byteArray = stream.toByteArray();
 Intent intent = new Intent(YourPresentActivity.this,
 TheReceiverActivity.class);
 intent.putExtra("selectedItem", selectedItem);
 intent.putExtra("image", byteArray);
 startActivity(intent);
</code>```

`

Then in the receiver activity I get my object and the image as byte array, decode the image and set it to my object as photo property.

```<code> Intent intent = getIntent();
 selectedItem = (ListItem) intent.getSerializableExtra("selectedItem");
 byte[] byteArray = getIntent().getByteArrayExtra("image");
 Bitmap image = BitmapFactory.decodeByteArray(byteArray, 0,
 byteArray.length);
 selectedItem.setPhoto(image);
</code>```

Body:
so I am getting this in logcat:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student)

I know this means that my student class is not serializable, but it is, here is my student class:

import java.io.Serializable;

public class Student implements Comparable<Student>,  Serializable{

    private static final long serialVersionUID = 1L;
    private String firstName, lastName;
    private DSLL<Grade> gradeList;

    public Student() {
        firstName = "";
        lastName = "";
        gradeList = new DSLL<Grade>();
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public DSLL<Grade> getGradeList() {
        return gradeList;
    }

    public void setGradeList(DSLL<Grade> gradeList) {
        this.gradeList = gradeList;
    }

    public int compareTo(Student arg0) {
        return this.lastName.compareTo(arg0.getLastName());
    }

}

and this is the code that is using the getIntent() method:

public void onItemClick(AdapterView<?> parent, View viewClicked, int pos,
                                long id) {

                            Student clickedStudent = studentList.get(pos);
                            int position = pos;
                            Intent intent = new Intent(getActivity().getApplicationContext(), ShowStudentActivity.class);
                            Log.e("CINTENT","CREATED!!!");
                            intent.putExtra("clickedStudent",clickedStudent);
                            intent.putExtra("newStudentList",newStudentList);
                            intent.putExtra("position",position);
                            Log.e("putExtra","Passed");
                            Log.e("Start activity","passed");
                            startActivity(intent);

                        }

                    });

please help me figure out whats wrong with this.

here is the whole LogCat:

04-17 16:12:28.890: E/AndroidRuntime(22815): FATAL EXCEPTION: main
04-17 16:12:28.890: E/AndroidRuntime(22815): java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeSerializable(Parcel.java:1181)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeValue(Parcel.java:1135)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeMapInternal(Parcel.java:493)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Bundle.writeToParcel(Bundle.java:1612)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeBundle(Parcel.java:507)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.content.Intent.writeToParcel(Intent.java:6111)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1613)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1422)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.Activity.startActivityForResult(Activity.java:3191)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:848)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.support.v4.app.Fragment.startActivity(Fragment.java:878)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.example.student_lists.MainActivity$DummySectionFragment$2.onItemClick(MainActivity.java:477)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AdapterView.performItemClick(AdapterView.java:292)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView$1.run(AbsListView.java:3168)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Handler.handleCallback(Handler.java:605)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Looper.loop(Looper.java:137)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.ActivityThread.main(ActivityThread.java:4447)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.lang.reflect.Method.invokeNative(Native Method)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.lang.reflect.Method.invoke(Method.java:511)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at dalvik.system.NativeStart.main(Native Method)
04-17 16:12:28.890: E/AndroidRuntime(22815): Caused by: java.io.NotSerializableException: com.resources.student_list.DSLL$DNode
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeSerializable(Parcel.java:1176)

Body:
The problem occurs when your custom class has for property some other class e.g. "Bitmap". What I made is to change the property field from  "private Bitmap photo" to "private transient Bitmap photo". However the image is empty after I getIntent() in the receiver activity. Because of this I passed the custom class to the intent and also I've created a  byte array from the image and pass it separatly to the intent:

selectedItem is my custom object and getPlacePhoto is his method to get image. I've already set it before and now I just get it first than convert it and pass it separatly:

 Bitmap image = selectedItem.getPlacePhoto();
 image.compress(Bitmap.CompressFormat.PNG, 100, stream);
 byte[] byteArray = stream.toByteArray();
 Intent intent = new Intent(YourPresentActivity.this,
 TheReceiverActivity.class);
 intent.putExtra("selectedItem", selectedItem);
 intent.putExtra("image", byteArray);
 startActivity(intent);

`

Then in the receiver activity I get my object and the image as byte array, decode the image and set it to my object as photo property.

 Intent intent = getIntent();
 selectedItem = (ListItem) intent.getSerializableExtra("selectedItem");
 byte[] byteArray = getIntent().getByteArrayExtra("image");
 Bitmap image = BitmapFactory.decodeByteArray(byteArray, 0,
 byteArray.length);
 selectedItem.setPhoto(image);


问:
Qt and windows messages
I want to receive custom messages in Qt via the QAbstractNativeEventFilter. Basically I added a switch WM_USER + 1: in the implementation, but I get notifications even though I am not sending anything. I assume that Qt could be using user messages internally as well. Is there a way to know the last id QT is using so that I can use the first free?

答:
The WM_USER range of messages is owned by the code that called RegisterClass(). In this case, that would be Qt, which is using that range for its own purposes. You will have to consult the Qt documentation to see what range of messages are available for you to use. This might be the WM_APP range, but if Qt uses that as well (and doesn't provide a way for you to request a message to use), you'll have to deal with registered window messages and their shortcomings. Again, check the Qt documentation.

EDIT, since I wasn't clear enough the first time

Do NOT try to find some random WM_USER + n that you can use. The point of the link I put there is that Qt is free to use all of the WM_USER messages for whatever it wants. Ignore this and your code will break in a future version of Qt. You must consult Qt documentation to see whether Qt specifically defines a set of messages in the WM_APP range (or even in the WM_USER range, but this must be explicitly stated in the documentation) as safe to use, and if not, you have no choice but to call RegisterWindowMessage() to register a system-wide named message. Ask on the Qt mailing list if necessary. Checking the source is not going to work because the current source is not a contract for future versions of Qt.

Title: Qt and windows messages


问:
how to find column index using dataIndex Extjs 4
Well in ExtJS 3 i used the following code:

grid.getColumnModel().findColumnIndex("Tasks")

I tried finding it on the api docs, but no luck...so how is ir possible that i can find the column index of the grid by the dataIndex of the column or the header name of that column.

答:
The most standard way to get a column by dataIndex would be:

```<code>var column = grid.columnManager.getHeaderByDataIndex('Tasks')
</code>```

Note that this does return a column (contrary to the function name). This is because a grid header in ExtJS is actually both a header and a column contents.

Ext.grid.column.Column docs:

This class specifies the definition for a column inside a
  Ext.grid.Grid. It encompasses both the grid header configuration as
  well as displaying data within the grid itself.

See also: getHeaderByDataIndex docs.

Body:
The most standard way to get a column by dataIndex would be:

var column = grid.columnManager.getHeaderByDataIndex('Tasks')

Note that this does return a column (contrary to the function name). This is because a grid header in ExtJS is actually both a header and a column contents.

Ext.grid.column.Column docs:

This class specifies the definition for a column inside a
  Ext.grid.Grid. It encompasses both the grid header configuration as
  well as displaying data within the grid itself.

See also: getHeaderByDataIndex docs.


问:
Google Cloud Functions CPU Speed Setup
I was not able to find settings for GCF to setup CPU speed. In pricing calculator there is several options for GCF environment on which it running, and by default as I understand the least performant option is used (800MHz?). So, I wounder, is there any options in Cloud Console or during Functions deploy to setup CPU speed?</p>

答:
The memory size and CPU speed are connected.  The details are on the pricing page:
https://cloud.google.com/functions/pricing

So, if you allocate 1024MB of memory to your function, you'll get a 1.4GHz CPU.

Title: Google Cloud Functions CPU Speed Setup


问:
Why does Double.TryParse() return false for a string containing double.MaxValue or double.MinValue?
I have static method that takes a string for input and returns the original input string if the string represents a number.  If the string does not represent a number the the input string is processed and a transformed string is returned.  I'm writing test cases.  I'm trying to verify that an input string containing either double.MinValue or double.MaxValue is returned unchanged.  I've read through a number of forums, including StackOverflow, and have come up with the following logic:

```<code>string doubleMax = double.MaxValue.ToString();
double d;
CultureInfo cultureInfo = new CultureInfo("en-US", true);
if (Double.TryParse(doubleMax, NumberStyles.Any, cultureInfo.NumberFormat, out d))
{
    Console.WriteLine("parsed");
}
else
{
    Console.WriteLine("couldn't parse");
}
</code>```

Problem is the Double.TryParse() always returns false.  I've called TryParse() in a bunch of different ways, but the result is always the same, false.

This logic works if I use decimal.MinValue(), int.MinValue(), or float.MinValue().

Can someone tell me why my logic isn't working for double.MinValue?

答:
I got interested in this question and found that if you add E20 to ToString then it works.

```<code>double.MaxValue.ToString("E20")
</code>```

Interesting question though.

UPDATE:

I test equality between d (the parsed double) and double.MaxValue and they are equal.

```<code>var abc = Double.Parse(double.MaxValue.ToString("E20"));
abc.Dump();

double d;
CultureInfo cultureInfo = new CultureInfo("en-US", true);
if (Double.TryParse(double.MaxValue.ToString("E20"), NumberStyles.Any, cultureInfo.NumberFormat, out d)) Console.WriteLine("parsed");
else Console.WriteLine("couldn't parse");

if(d == double.MaxValue) Console.WriteLine("parsed value is equal to MaxValue");
else Console.WriteLine("parsed value is NOT equal to MaxValue");
</code>```

Body:
I have static method that takes a string for input and returns the original input string if the string represents a number.  If the string does not represent a number the the input string is processed and a transformed string is returned.  I'm writing test cases.  I'm trying to verify that an input string containing either double.MinValue or double.MaxValue is returned unchanged.  I've read through a number of forums, including StackOverflow, and have come up with the following logic:

string doubleMax = double.MaxValue.ToString();
double d;
CultureInfo cultureInfo = new CultureInfo("en-US", true);
if (Double.TryParse(doubleMax, NumberStyles.Any, cultureInfo.NumberFormat, out d))
{
    Console.WriteLine("parsed");
}
else
{
    Console.WriteLine("couldn't parse");
}

Problem is the Double.TryParse() always returns false.  I've called TryParse() in a bunch of different ways, but the result is always the same, false.

This logic works if I use decimal.MinValue(), int.MinValue(), or float.MinValue().

Can someone tell me why my logic isn't working for double.MinValue?

Body:
I got interested in this question and found that if you add E20 to ToString then it works.

double.MaxValue.ToString("E20")

Interesting question though.

UPDATE:

I test equality between d (the parsed double) and double.MaxValue and they are equal.

var abc = Double.Parse(double.MaxValue.ToString("E20"));
abc.Dump();

double d;
CultureInfo cultureInfo = new CultureInfo("en-US", true);
if (Double.TryParse(double.MaxValue.ToString("E20"), NumberStyles.Any, cultureInfo.NumberFormat, out d)) Console.WriteLine("parsed");
else Console.WriteLine("couldn't parse");

if(d == double.MaxValue) Console.WriteLine("parsed value is equal to MaxValue");
else Console.WriteLine("parsed value is NOT equal to MaxValue");


问:
Laravel 5.3 set homepage as login screen
How do I set the homepage (/) to the login screen in Laravel 5.3?

I have a routes file :

```<code>Route::get('/', function () {
    return view('welcome');
});
</code>```

I have set up the basic auth scaffolding with the command php artisan make:auth and have set up my db tables too.

But I'm struggling to understand how to set the homepage to always go to the login screen if the user is not authenticated? Surely this is just me being stupid right?

答:
In laravel 5.4 you can modify the route as
Route::get('/', 'Auth\LoginController@showLoginForm');</p>

ContentLicense: CC BY-SA 4.0

Body:
How do I set the homepage (/) to the login screen in Laravel 5.3?

I have a routes file :

Route::get('/', function () {
    return view('welcome');
});

I have set up the basic auth scaffolding with the command php artisan make:auth and have set up my db tables too.

But I'm struggling to understand how to set the homepage to always go to the login screen if the user is not authenticated? Surely this is just me being stupid right?


问:
Entity Framework 6.1.1 - How to check if property is ignored from an entity in SaveChanges method
Scenario:

I have following set of entities:

```<code>public interface IAuditable
{
    DateTime? CreatedDate { get; set; }
    string CreatedBy {get;set;}
    string LastModifiedBy {get;set;}
    DateTime? LastModifiedDate {get;set;}
}

public abstract class BaseEntity: IAuditable
{
    public int ID { get; set; }
    public DateTime? CreatedDate { get; set; }
    public string CreatedBy {get;set;}
    public string LastModifiedBy {get;set;}
    public DateTime? LastModifiedDate {get;set;}
}

public class Product: BaseEntity
{
    public string Name { get; set; }
}

public class Order : BaseEntity
{
    public int ProductID { get; set; }
    public int Qty { get; set; }
}
</code>```

and following DbContext:

```<code>public class AuditDbContext : DbContext
    {
        public AuditDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public DbSet<Product> Products { get; set; }
        public DbSet<Order> Orders { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Products>()
            .Ignore(t => t.CreatedDate);

            modelBuilder.Entity<Order>()
            .Ignore(t => t.LastModifiedBy);
            modelBuilder.Entity<Order>()
            .Ignore(t => t.LastModifiedDate);
        }

        public override int SaveChanges()
        {
            SetAuditableProperties();
            return base.SaveChanges();
        }

        private void SetAuditableProperties()
        {
            foreach (var auditableEntity in ChangeTracker.Entries<IAuditable>())
            {
                if (auditableEntity.State == EntityState.Added ||
                    auditableEntity.State == EntityState.Modified)
                {
                    string userName = "ABC";
                    DateTime dateTimeNow = DateTime.Now;

                    auditableEntity.Entity.LastModifiedDate = dateTimeNow;
                    auditableEntity.Entity.LastModifiedBy = userName;

                    if (auditableEntity.State == EntityState.Added)
                    {
                        auditableEntity.Entity.CreatedDate = dateTimeNow;
                        auditableEntity.Entity.CreatedBy = userName;
                    }
                    else
                    {
                        auditableEntity.Property(p => p.CreatedDate).IsModified = false; //TODO: Set this property if mapped otherwise dont execute this line
                        auditableEntity.Property(p => p.CreatedBy).IsModified = false; //TODO: Set this property if mapped otherwise dont execute this line
                    }
                }
            }
        }
    }
</code>```

Observe I'm Ignoring some properties form entities in OnModelCreating and setting Auditable properties inside SaveChanges method by overriding it. Now, when I try to create new entity it works as expected but when I try to update an existing entity it throws exception.

Problem:

Let's say I try to update Product entity it throws following exceptions:

"Member 'IsModified' cannot be called for property 'CreatedDate' on entity of type 'Products' because the property is not part of the Entity Data Model".

Same is true for 'Order' entity but for 'LastModifiedBy' and 'LastModifiedDate' properties.

How can I check if a property is ignored from entity inside 'SetAuditableProperties' method? So that I can set 'IsModified' accordingly.

P.S. I can find out [NotMapped] properties but when I use the ModelBuilder to ignore a column, I cannot detect these.

答:
I'm unaware of any way to query the model builder for this outside of the scope of setting the configuration - but there is a little easier of a way to perform this task using attributes

On your properties to be ignored attribute them with [NotMapped], then you would perform this for each property you want to check before updating in your audit method:

```<code>foreach (var auditableEntity in ChangeTracker.Entries<IAuditable>())
{
    var ignore = Attribute.IsDefined(auditableEntity.Entity.GetType().GetProperty("CreatedDate"), typeof(NotMappedAttribute))
    if (!ignore) {
        auditableEntity.Entity.CreatedDate = dateTimeNow;
    }
}
</code>```

Body:
Scenario:

I have following set of entities:

public interface IAuditable
{
    DateTime? CreatedDate { get; set; }
    string CreatedBy {get;set;}
    string LastModifiedBy {get;set;}
    DateTime? LastModifiedDate {get;set;}
}

public abstract class BaseEntity: IAuditable
{
    public int ID { get; set; }
    public DateTime? CreatedDate { get; set; }
    public string CreatedBy {get;set;}
    public string LastModifiedBy {get;set;}
    public DateTime? LastModifiedDate {get;set;}
}

public class Product: BaseEntity
{
    public string Name { get; set; }
}

public class Order : BaseEntity
{
    public int ProductID { get; set; }
    public int Qty { get; set; }
}

and following DbContext:

public class AuditDbContext : DbContext
    {
        public AuditDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public DbSet<Product> Products { get; set; }
        public DbSet<Order> Orders { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Products>()
            .Ignore(t => t.CreatedDate);

            modelBuilder.Entity<Order>()
            .Ignore(t => t.LastModifiedBy);
            modelBuilder.Entity<Order>()
            .Ignore(t => t.LastModifiedDate);
        }

        public override int SaveChanges()
        {
            SetAuditableProperties();
            return base.SaveChanges();
        }

        private void SetAuditableProperties()
        {
            foreach (var auditableEntity in ChangeTracker.Entries<IAuditable>())
            {
                if (auditableEntity.State == EntityState.Added ||
                    auditableEntity.State == EntityState.Modified)
                {
                    string userName = "ABC";
                    DateTime dateTimeNow = DateTime.Now;

                    auditableEntity.Entity.LastModifiedDate = dateTimeNow;
                    auditableEntity.Entity.LastModifiedBy = userName;

                    if (auditableEntity.State == EntityState.Added)
                    {
                        auditableEntity.Entity.CreatedDate = dateTimeNow;
                        auditableEntity.Entity.CreatedBy = userName;
                    }
                    else
                    {
                        auditableEntity.Property(p => p.CreatedDate).IsModified = false; //TODO: Set this property if mapped otherwise dont execute this line
                        auditableEntity.Property(p => p.CreatedBy).IsModified = false; //TODO: Set this property if mapped otherwise dont execute this line
                    }
                }
            }
        }
    }

Observe I'm Ignoring some properties form entities in OnModelCreating and setting Auditable properties inside SaveChanges method by overriding it. Now, when I try to create new entity it works as expected but when I try to update an existing entity it throws exception.

Problem:

Let's say I try to update Product entity it throws following exceptions:

"Member 'IsModified' cannot be called for property 'CreatedDate' on entity of type 'Products' because the property is not part of the Entity Data Model".

Same is true for 'Order' entity but for 'LastModifiedBy' and 'LastModifiedDate' properties.

How can I check if a property is ignored from entity inside 'SetAuditableProperties' method? So that I can set 'IsModified' accordingly.

P.S. I can find out [NotMapped] properties but when I use the ModelBuilder to ignore a column, I cannot detect these.

Body:
I'm unaware of any way to query the model builder for this outside of the scope of setting the configuration - but there is a little easier of a way to perform this task using attributes

On your properties to be ignored attribute them with [NotMapped], then you would perform this for each property you want to check before updating in your audit method:

foreach (var auditableEntity in ChangeTracker.Entries<IAuditable>())
{
    var ignore = Attribute.IsDefined(auditableEntity.Entity.GetType().GetProperty("CreatedDate"), typeof(NotMappedAttribute))
    if (!ignore) {
        auditableEntity.Entity.CreatedDate = dateTimeNow;
    }
}