Access the local site created by GatsbyJS on phone in development stage
In cmd, just run the following command to start the gatsby site:gatsby develop -H 0.0.0.0If it is successful, it will provide a link start with your ip address instead of localhost. Enter this link on your phone to access this site.
Cannot load the image after deploy a GatsbyJS website to Github Pages
After deploy the GatsbyJS website to Github Pages, the images stored in /public folder cannot be loaded by CSS url() method.This problem occurs when I use the Inline CSS style to set the background picture of a div.<div style={{ backgroundImage: `url(${photoPath})` }}></div>It is because the website contain prefix after deployment. So the image path should also contain the prefix.To solve this problem, use the Gatsby withPrefix() method to include the prefix automatically.<div style={{ backgroundImage: `url(${withPrefix(photoPath)})` }}></div>
Get the item list from localstorage or sessionstorage in JavaScript
To retrieve the value from localstorageor sessionstorage, we need to provide the key. But, it is difficult to retrieve a list of value from localstorage or sessionstoragewithout the keys. This method introduce how to retrieve a list of value from localstorageor sessionstoragewithout knowing the keys.Assume there are a list of localstorageitems:The following code segment will get the key of these items, get the values and store the result in key-value pair.(function () {
let result = [];
let storageKey = Object.keys(localStorage);
for (let i = 0; i < storageKey.length; i++) {
let tempResult = {};
tempResult[storageKey[i]] = localStorage.getItem(storageKey[i]);
result.push(tempResult);
}
console.log(result);
})();Result:[
{
"eKey": "e"
},
{
"cKey": "c"
},
{
"dKey": "d"
},
{
"bKey": "b"
},
{
"aKey": "a"
}
]
Filter array element based on dynamic search key and value in JavaScript
Given: an array of objects with two keys - "type" and "content", a search key and valueResult: an array contains the objects match the search key and valueCode segment:function filterArray(searchKey, searchValue) {
return arr.filter(function (value, index, array) {
return array[index][searchKey] === searchValue;
});
}
Example:var arr = [{
type: "red",
content: "tomato"
},
{
type: "yellow",
content: "maize"
},
{
type: "yellow",
content: "noodles"
},
{
type: "red",
content: "apple"
},
{
type: "green",
content: "vegetables"
}
];
function filterArray(searchKey, searchValue) {
return arr.filter(function (value, index, array) {
return array[index][searchKey] === searchValue;
});
}
console.log(filterArray("type", "red"));
Result:[
{
"type": "red",
"content": "tomato"
},
{
"type": "red",
"content": "apple"
}
]
Find records within specific month and year by Laravel query builder
Sometimes, we may want to find out the records within specific month and year. This method introduce how to
use Laravel's query builder to implement this requirement.In database, the date is stored in the date data type. Th following are some examples of date stored in the date format.DateYearMonth2019-02-052019022020-12-24202012If we want to get the day and the full name of the month, we will use the following code segment:$date_list = DB::table('date_table')
->select(DB::raw('table_date, DATE_FORMAT(table_date, "%Y") as date_year, DATE_FORMAT(table_date, "%M") as date_month'))
->get();DATE_FORMAT is used to format the date according to the second parameter. In this example, %Y and %M is used to format the output. ParameterMeaning%MGet the full name of the month%YGet the year in 4-digit formatThe following is the output:table_datedate_yeardate_month2019-02-052019February2020-12-242020December
Implementation of Dark theme to Android application
Nowadays, dark theme becomes more popular in Android application. This tutorial introduce how to implement dark theme to your android application including AppCompatActivity and Fragment and save the current theme state for your application. This tutorial will focus on the main point of implementing dark theme. You can check the full source code from GitHub and watch the demo video.Source CodeDemoTo implement a dark theme application, there are three requirements:When the user changes the theme from dark to light or from light to dark, it will not recreate the activity. For example, if there is a text field that will change the text according to user input, this text field should not be reset to default value i.e. the activity has not recreated.When the user reopen the application, the theme should remain the same. For example, if the user has change the theme to dark. When he/she opens the application next time, the theme should change to dark.The
change of theme should apply to the whole application.So, there are three steps for implementation.Notify the change of themeWe use AppCompatDelegate.setDefaultNightMode() to set the default theme for this application. It accepts a integer as parameter. We will pass either AppCompatDelegate.MODE_NIGHT_NO or AppCompatDelegate.MODE_NIGHT_YES to this function. // light theme
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
// dark theme
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);AppCompatDelegate.MODE_NIGHT_NO means the user will use light theme and AppCompatDelegate.MODE_NIGHT_YES means the user will use dark theme. All the activities and fragments in the application can notify the change of theme. But, it will call the onCreate method of class extends AppCompatActivity and the onCreateView method of class extends Fragment. So, for the activities in AndroidManifest.xml, add the code android:configChanges="uiMode" to prevent the recreation of activities and fragments.<activity android:name="cky.project.darkthemetest.MainActivity2"
android:configChanges="uiMode" />Change the color of elements according to the current themeIt is necessary to check the current theme and change the color of elements. To check the current theme, we need two integers - getResources().getConfiguration().uiMode and Configuration.UI_MODE_NIGHT_MASK. We need to get the bitwise AND result of this two integers. int nightModeFlags = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;If the result equals Configuration.UI_MODE_NIGHT_NO, it means the current theme is light theme. If the result equals to Configuration.UI_MODE_NIGHT_YES, it means the current theme is dark theme.The following is the code segment for checking the current theme. It can be used to update the color of elements.int nightModeFlags = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if (nightModeFlags == Configuration.UI_MODE_NIGHT_NO) {
// change to light mode
changeTheme(themeHelper.DAY);
} else {
// change to dark mode
changeTheme(themeHelper.NIGHT);
}
Save the current themeWe use SharedPreference to save the current theme. If the value of SharedPreference equals to AppCompatDelegate.MODE_NIGHT_NO, it means the current theme is light theme. If the value of SharedPreference equals to AppCompatDelegate.MODE_NIGHT_YES, it means the current theme is dark theme.The following is the example of how to use the SharedPreference to save the current theme and notify the change of theme.int currentMode = themeHelper.getCurrentMode();
if (currentMode == -1) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
changeTheme(themeHelper.DAY);
themeHelper.saveCurrentMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
AppCompatDelegate.setDefaultNightMode(currentMode);
changeTheme(currentMode);
}
public int getCurrentMode() {
return sharedPreferences.getInt(modeName, -1);
}
public void saveCurrentMode(int mode) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(modeName, mode);
editor.commit();
}
Wampserver: 2 of 3 services running
Sometimes, wampserver will show the message 2 of 3 services running and the icon color is orange, instead of green. It means there are one of the services - PHP, MySQL or MariaDB is not working normally. This tutorial introduce how to find out the stopped service and solve this problem.Right click the wampserver icon, select Tools -> Create Wampserver Configuration ReportWait until the report generation process has finishedRight click the wampserver icon, select Tools -> Wampserver Configuration ReportThis report shows that The service 'wampmariadb64' is NOT started. It means the MariaDB services has not startedClick the wampserver icon, select MariaDB -> MariaDB logThe error log shows that Can't start server: Bind on TCP/IP port. Got error: 10048: (//). It means there are some service is using the port.Press ctrl+alt+delete to open the Task Manager. Find out the services with name mysqlID.exe and stop this servicesRestart the wampserver. Three services are running normally.
Merge multiple database rows with comma by Laravel query builder
Sometimes, we may want to join multiple rows from single column and separate it with delimiter such as comma. This method introduce how to use Laravel's query builder to implement this requirement.Suppose there is a database table tag with column tags and three rows:tagsdatabasesqlrealtimeIf we want to join the rows of tags column, we will use the following code segment of query builder:$test = DB::table('tag')
->select(DB::raw('GROUP_CONCAT(tags SEPARATOR ", ") as join_tags'))
->get();The result is:join_tagsdatabase, sql, resltime
Save and retrieve the current timestamp in firebase real-time database
Sometimes, we need to save the current timestamp to Firebase Real-time database. The following shows how to get the current timestamp, save it to database and translate the timestamp to readable date.Get the current timestampWe can use the Firebase ServerValue.TIMESTAMP to get the current timestamp.Save to Firebase real-time databaseJust save the timestamp like other real-time database child.DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("timestamp", ServerValue.TIMESTAMP);
ref.updateChildren(map);
Translate the timestamp to readable dateThe timestamp retrieved from the real-time database is in String format. So, we need to translate the timestamp to Long format.long timestamp = Long.parseLong(snapshot.getValue().toString());Then, translate the timestamp to readable date like Jun 15, 2018 6:00:00 AM. DateFormat dateFormat = getDateTimeInstance();
Date date = (new Date(timestamp));
return dateFormat.format(date);
Get the full size photo from Android Camera Application
In android application, MediaStore.ACTION_IMAGE_CAPTURE allows the application to open the camera, take and save the photos. But, the photo is blurred because it saves the thumbnail of the photo, instead of the full size photo. To solve this problem, we should provide a path for the application to save the photo.First, the following permission should be mentioned in AndroidManifest.xml<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
Then, create a image file to save the captured image:File outputFolder = new File(Environment.getExternalStorageDirectory() + "/fakeFile");
if (!outputFolder.exists()) {
outputFolder.mkdir();
}
File imageFilePath = new File(outputFolder.getAbsolutePath() + "/" + "image.jpeg");Next, invoke the camera intent:Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFilePath));
startActivityForResult(cameraIntent, 1);Finally, receive the result:@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
// Do anything
}
}