Tuesday, November 29, 2022

How to change title of Activity in Android ?

When you are using the fragments and activities together in an application, it takes the title for the fragments automatically as the names of the fragments. But for the activities, it takes the app name itself as the title of the activity, So how to change the title of the activity.

 There are two ways to change the title of the activity. 

1. You can do it programmatically through activity by setting the title as below:

public class QuestionActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
setTitle("Questions ?");

}
}

Before:                                       After: 




2. You can do it through androidmanifest.xml by setting the label there.  Open Androidmanifest.xml, in the activity you can add the label as the string or from the string file below to display the title:


<activity
android:name=".QuestionActivity"
android:label="@string/Questions"
android:exported="false" />

Here is the title shown:




That's it. Happy coding


Wednesday, November 23, 2022

"No Application Encryption Key Has Been Specified" Error in Laravel Application

 While creating a new laravel application from the begining, you only need the below things:

  • A terminal
  • PHP-7.0 installed
  • composer installed and available in your path
  • npm installed aad available in your path.

After all the above installed in your computer , You can create a new Laravel project from the command prompt:

composer create-project laravel/laravel  Myapplication

Now you can run:

php artisan serve

This should give you a URL to view, so click on this and open it in your browser. This should show the default Laravel screen or Page. But some time you get a Error in the browser as " No application Encryption Key has been specified" 



This will happen if the application key is empty in .env file or the key is corrupted.
In such case you need to follow the below steps to solve this issue:

1. Generate application key by running the below command in your command prompt:
    php artisan key:generate




2. Now you can see. .env file your app key is set to a key if its empty. or its updated.

3. Now you can run php artisan serve



 4. And go to the browser and check the link, You will be able to see the default laravel page showing



Even if you see the error, you need to clear the cache with the command 
php artisan config:cache

And after this, run php artsan serve and you will be able to see the laravel default page. Hope this helps.

Tuesday, November 22, 2022

Playing a YouTube video in the Android application

We  want to play Youtube video by streaming it directly from YouTube without downloading. Also, while playing videos, I want provide menu options. I don't want to play video using default intent. How can we do this?

There are multiple ways to play the youtube video in your android application. One of the easiest way is to start the activity View by parsing the URI. Eg as below:

    startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("youtube URL")));

that's 
"startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.youtube.com/watch?v=4TmBlhfJVnc")));



if this should happen on click of a button, you can add this inside onclick of the button:

btnvideo.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

    startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.youtube.com/watch?v=4TmBlhfJVnc")));
Log.i("Video", "Video Playing...."); } });

Now if  the video names are shown as the list of items. 
And on click of the list item, we need to fetch the URL from mysql database and 
pass it to the URL Parse.


BhagvadgeetaViewModel slideshowViewModel =
new ViewModelProvider(this).get(BhagvadgeetaViewModel.class);


binding = FragmentSlideshowBinding.inflate(inflater, container, false);
View root = binding.getRoot();

final TextView textView = binding.textSlideshow;
slideshowViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
ProgressBar progressBar = binding.progress;
ListView listview =binding.list;
final String[] videoName = new String[1];
progressBar.setVisibility(View.VISIBLE);

slideshowViewModel.getVideoList().observe(getViewLifecycleOwner(), videoList->{
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_2, android.R.id.text1, videoList);
listview.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
});

listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView textView1 = view.findViewById(android.R.id.text1);
String selectedItemname = (String) textView1.getText();
slideshowViewModel.getVideoPath(selectedItemname).observe(getViewLifecycleOwner(), S-> {
String videoPath = S;

Log.i("Video", "Video Playing....: "+videoPath);
// Toast.makeText(getActivity(),"Selected Path: "+videoPath,Toast.LENGTH_SHORT).show();
if(videoPath !=null) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(videoPath)));
}

});

}
});

return root;
}




And in the viewmodel, you need to write the code to get the video path:
You need to have a api which returns the youtube url by sending the youtube video name.
I have that in getpath.php file in my server.


Here we go:

LiveData<String> getVideoPath(String videoName){
mVideoPath = new MutableLiveData<>();
mVideoPath.setValue(loadVideoPath(videoName));
if(mVideoPath == null){
mVideoPath.setValue(loadVideoPath(videoName));
}
return mVideoPath;
}
private String loadVideoPath(String videoName) {
Handler myHandlerVideoPath = new Handler();

myHandlerVideoPath.post(new Runnable() {
@Override
public void run() {
String[] field = new String[1];
field[0] = "name";
String[] data = new String[1];
data[0] = videoName;
PutData putData = new PutData(SERVER+"getPath.php", "POST", field, data);
if (putData.startPut()) {
if (putData.onComplete()) {

String result = putData.getResult();
if(result.equals("All fields are required")){
//Toast.makeText(getActivity(), result,Toast.LENGTH_SHORT).show();
mText.setValue(result);
}
else {
videoPath = result ;

}
mVideoPath.setValue(videoPath);


}

}
}

});
return videoPath;
}


Sunday, September 11, 2022

How to decide MahaShivaratri date

Maha Shivaratri is an annual Hindu festival commemorating the god Shiva. The name also alludes to the night when Shiva performs the divine dance known as Tandava. 

On the day before the new moon in each month of the luni-solar Hindu calendar, there is a Shivaratri, or "night of Shiva." But once a year, this night is referred to as "Maha Shivaratri" or "the Great Night of Shiva" and occurs in late winter or early spring (February or March). According to the South Indian Hindu calendar, this day is in the month of Magha.

It is a significant Hindu festival, and this festival is solemn and commemorates "overcoming darkness and ignorance" in life and the world. It is observed by remembering Shiva and chanting prayers, fasting, and meditating on ethics and virtues such as honesty, charity, forgiveness, and Shiva's discovery. Dedicated devotees stay awake all night. They call it as "Jagarani", Others go on pilgrimage to Jyotirlingas or to Shiva temples. 

The South Indian calendar observes Maha Shivaratri on Chaturdashi Tithi during Krishna Paksha in the month of Magha, while other parts of India observe it on the 13/14 night of Krishna Paksha in the month of Phalguna of the Hindu calendar, with the Gregorian date remaining the same.

Date: 14th day of māgha māsa (amānta)  Krishna Paksha 
Significance: self study, remembering Shiva, overcoming darkness and ignorance
Observances: Fasting, yoga, jagran all night 
Observed by: Hindus




Saturday, September 3, 2022

How to create your own Android Library and publish it

We'll build and publish our own Android Library in this tutorial. You can use the library in all of your upcoming projects by releasing it. Additionally, other people can utilize the library for their projects.
Therefore, let's begin: 

Creating The Android Library

Open Android Studio and create a new project. Give the name "HttpConnection" to the project.

Click on Finish and your project will be ready.
Now create a new Module in your project

Name Your Library as httpConnectionlib and click finish.


 Your module httpConnection has been added.  Now we need to add code to our library. Create a new Class in the module and name that class. Add the required file to the library.
I have added two classes, FetchData and PutData.

So now, our library is finished, it's time to publish it.

JitPack will be used to publish the library because it makes the procedure great deal simpler. 
GitHub repository is all you require.

Publishing the Android Library
Now we are going to create a new GitHub  public repository and push our code:



Now you can set up your Android Studio to push the code to this repository. You can do it as per my previous blog:  
How to Use Git in Android Studio

Now in your GitHub repository, you should be able to see your code:



Now you need to click on the release button to release this code for usage




Publish the release. Open a new tab and go to jitpack.io.
Insert your repository address and click on Lookup. Your releases will be listed. Now click on Get it.

click on the get it button there and you will get the instructions on how to use it:

Now your Android Library has been published and is ready to be used.
Using the Android Library
Now you can use this android library in any of your projects.
In your project’s build. Gradle add the following line
maven { url ‘https://jitpack.io’ }

And you can add a dependency library here
implementation 'com.GitHub.karjol:httpconnection:0.1.0'


And now you can use the library in your activity.

Example for PutData

private void getSubjectList(String featureSelected, String semSelected) {
if(!featureSelected.equals("") && !semSelected.equals("")) {
progressBar.setVisibility(View.VISIBLE);
Handler handler1 = new Handler();
handler1.post(new Runnable() {
@Override
public void run() {
String[] field = new String[2];
field[0] = "feature";
field[1] = "sem";
String[] data = new String[2];
data[0] = featureSelected;
data[1] = semSelected;
PutData putData = new PutData("https://grcamp.in/qbank/subject.php", "POST", field, data);
if (putData.startPut()) {
if (putData.onComplete()) {
progressBar.setVisibility(View.GONE);
String result = putData.getResult();
if(result.equals("All fields are required")){
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();

}
else {
try {
JSONArray jsonarry = new JSONArray(result);
//JSONArray subjects = jsonObj.getJSONArray("subname");
for (int i = 0; i < jsonarry.length(); i++) {
JSONObject jsonobject = jsonarry.getJSONObject(i);
list.add(jsonobject.getString("subname"));
}

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

}

}
}
}
});
}
else {
Toast.makeText(getApplicationContext(),"All fields required", Toast.LENGTH_SHORT).show();
}
}

Example for fetch Data:

buttonFetch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
//Starting Read data from URL
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
FetchData fetchData = new FetchData("https://grcamp.in/qbank/Fetchstudents.php");
if (fetchData.startFetch()) {
if (fetchData.onComplete()) {
String result = fetchData.getResult();
progressBar.setVisibility(View.GONE);
textView.setText(result);
Log.i("FetchData", result);
}
}
}
});
//End Read data from URL
}
});

If there is any question or confusion regarding this. 
Feel free to ask your questions in the comments below.

Thursday, August 25, 2022

How to Use Git in Android Studio

In this blog, you will learn how to use Git in Android Studio. Firstly, you will learn the basic concept of Git and then create a new project using Git. Next, you will learn how to clone and fork a repository. Next up, you will see how to push your changes online using Github.  Also you can learn:
  • Integrating Git into the project
  • Setting up remote connections
  • Staging and committing changes
  • Pushing the changes to remote
  • Fetching the changes from remote
  • Working with branches
  • Showing log history

Note: This article uses Android Studio on a Windows OS machine for all references to paths, options, names, and configurations. Although it might alter significantly on other operating systems like Mac or Linux, the concept will remain the same.

Integrate Git into the project
Test whether Git is configured
In Android Studio, go to Android Studio > File > Settings > Version Control > Git. Click Test to ensure that Git is configured properly in Android Studio.

Enable version control integration
Suppose you’ve just created an Android project. In Android Studio, go to VCS > Enable Version Control Integration. This option won’t be visible if it’s integrated with any version control before.


Select Git version control system. On a successful enable VCS, a default local master branch will be created.

Add .gitignore to exclude files from Git
When you create a new Android project with Android Studio, two .gitignore files are automatically added (one in the project root folder, and the app folder). Files like generated code, binary files (executables, APKs), local configuration files should not be added to Git. Those files should be excluded from version control. Here’s my initial .gitignore file content:
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
File extensions that you want to keep outside the git track can be added. 
Stage and Commit Changes
The project is ready to use with Git version control. To stage and commit your changes, go to Git> Commit.
You will get a dialog to examine all files that will be added, enter commit messages and commit. You can deselect any files that you don’t want to belong to this commit.
When you click commit, a popup shows that you haven’t configured your username and email yet. You should always configure them because they will be attached to your commit message.
All done — now the whole project has been added to Git.
Set Up Remote Connections

To add the project to the remote repository, go to  Git > Manage Remotes :



Click on + and add the remote repo URL . Your local project is now linked to your remote Github repository. You can utilize Bitbucket, Gitlab, or any repository in addition to Github.

Push the Changes to Remote

To push your local changes to the remote repository, go to Git > Push.

The “Push Commits” popup will display which commit will be pushed to the remote-tracking branch. You can go ahead and make the push.
Fetch the Changes From Remote
To download the latest changes from remote, go to Git > Pull.

Work With Branches
Git's branching approach is referred to as its "killer feature" by some, and it undoubtedly distinguishes Git from other VCS systems. I'll demonstrate how to use branches in Android Studio in this part.
Create a new branch

Go to Git > Branches

“Git Branches” appears. It shows all the local branches and remote branches as well as the “New branch” option. If you click on New branch, you can create a new branch.
You can have a lot of options with the existing branch

  • Checkout: checkout master branch.
  • Checkout As: checkout new branch from master
  • Checkout and Rebase onto Current: checkout master and rebase feature branch onto it.
  • Compare with Current: commits that exist in master but don’t exist in feature and vice versa.
  • Show Diff with Working Tree: show the difference between the master and the current working tree.
  • Rebase Current onto Selected: rebase master on feature.
  • Merge into Current: merge master into feature.
  • Rename: rename the master branch.
  • Delete: delete the master branch.

You can choose the right option based on your needs. 
Show Log History
Go to Git > Show History.

It shows the log