Menus

Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Thursday 1 February 2024

How to get relation value in index in yii2 and Filter


How to get relation value in index in yii2


Certainly! When using Yii2, the convention is to create a separate search model for handling search and filtering logic. Here's a basic example of a PostSearch model with filtering capabilities for the author.name attribute:

Assuming you have a Post model with a hasOne relation to Author:

  1. Create a PostSearch model:

// models/PostSearch.php

namespace app\models;

use yii\base\Model;

use yii\data\ActiveDataProvider;

class PostSearch extends Post

{

    public $authorName;

    public function rules()

    {

        return [

            [['id', 'author_id'], 'integer'],

            [['title', 'content', 'authorName'], 'safe'],

        ];

    }


    public function search($params)

    {

        $query = Post::find()->joinWith('author');

        $dataProvider = new ActiveDataProvider([

            'query' => $query,

            'sort' => [

                'attributes' => [

                    'id',

                    'title',

                    'content',

                    'authorName' => [

                        'asc' => ['author.name' => SORT_ASC],

                        'desc' => ['author.name' => SORT_DESC],

                    ],

                ],

            ],

        ]);

        $dataProvider->sort->attributes['authorName'] = [

            'asc' => ['author.name' => SORT_ASC],

            'desc' => ['author.name' => SORT_DESC],

        ];

        $this->load($params);

        if (!$this->validate()) {

            return $dataProvider;

        }

        $query->andFilterWhere(['like', 'author.name', $this->authorName]);

        // Your other filtering logic goes here


        return $dataProvider;

    }

}


In your views/post/index.php, you can now use the GridView widget with the search model:

// views/post/index.php

use yii\grid\GridView;

// Other view code

<?= GridView::widget([

    'dataProvider' => $dataProvider,

    'filterModel' => $searchModel,

    'columns' => [

        // Your other columns


        [

            'attribute'=>'authorName'

            'value'=> 'author.name',

            'label' => 'Author Name',

        ],

        // Other columns

    ],

]); ?>


  1. In your Post model, ensure you have defined the relation to Author:
// models/Post.php

namespace app\models;

use yii\db\ActiveRecord;

class Post extends ActiveRecord
{
    // Your other attributes and methods here

    // Define the relation to Author

    public function getAuthor()
    {
        return $this->hasOne(Author::class, ['id' => 'author_id']);
    }

}


In your PostController, use the PostSearch model in the actionIndex method:

// controllers/PostController.php

namespace app\controllers;

use Yii;

use yii\web\Controller;

use app\models\PostSearch;

class PostController extends Controller

{

    public function actionIndex()

    {

        $searchModel = new PostSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }

}


 

Saturday 23 April 2022

Largest of three numbers in C

 #include <stdio.h>

int main()

{

 int x,y,z;

 clrscr();

 printf("Enter three numbers :");

 scanf("%d,%d,%d",&x,&y,&z);


 if(x>y)

 {

   if(x>z)

     printf("Largest value : %d ",x);

   else

     printf("Largest value : %d ",z);

 }

 else

 {

   if(y>z)

     printf("Largest value : %d",y);

   else

     printf("Largest value : %d",z);

 }


 getch();

}

Wednesday 24 February 2021

Android code for Displaying a video with VideoView



By the help of MediaController and VideoView classes, we can play the video files in android.

 - Dsiplaying loacal videos


- Create an application that displays a video clip, which is stored locally 

in our applications “res” directory


- Create a row directory

      Paste video file to raw directory


-  Add VideoView to your UI


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<VideoView
android:id="@+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.lb.videoplay;

import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

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

VideoView videoView = (VideoView) findViewById(R.id.videoView);

//Attach a media controller to video view
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
mediaController.setAnchorView(videoView);

//Specify the location of media file
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.favicon);

videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();



}
}





Android playing video from url with video view






previous tutorial we are discuss about

how to play video on videoview from local file


First set to internet permission


  your manifest must include the permissions:

<uses-permission android:name="android.permission.INTERNET" />


Then and to video url


Check this code


package com.lb.videoplay;

import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

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

VideoView videoView = (VideoView) findViewById(R.id.videoView);

//Attach a media controller to video view
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
mediaController.setAnchorView(videoView);

//add your video URL
Uri uri = Uri.parse("Add URL here..");


videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();



}
}



videoView can't open this video Online video


Create file res/xml/network_security_config.xml


<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>



New in the AndroidManifest.xml file under application:



android:networkSecurityConfig="@xml/network_security_config"











Friday 14 August 2020

How to place a YouTube Video in Your android app

 

Hello Friends

    Welcome back to android tutorials in this post we are going to earn about How to place a YouTube Video in Your android app.




Start new project in android studio.

Specify application name

To play Your YouTube video you need to the internet permission for the application

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Place YouTube video in Your app You need to add YouTube API. Download and add library in Your project.
    YouTube Android API (Click to Download)
    Extract File
    Now open libs folder
    Copy jar files
    Now open android studio 
        Open project view
        Open app folder
        Paste that jar file inside lib folder and right click then click Add As Library

      
To play YouTube video then create YouTube API Key.
    Get the API key to submit application package name and SHA1 certificate fingerprint on google developer console.
        Create new project
        Go to credentials option and create API key
        Copy this API key and to add java class in your android project

Go to Activity, then add Custom View select YouTube Player View and to add a Button text as Play

Then following these code

Config.Java

public class Config {

private static final String YOUTUBE_API_KEY = "Paste Your key....";

public static String getYoutubeApiKey() {
return YOUTUBE_API_KEY;
}

}


MainActivity.Java

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends YouTubeBaseActivity {


YouTubePlayerView aYouTubePlayerView;
Button btnPlay;
YouTubePlayer.OnInitializedListener mOnInitializedListener;

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

btnPlay = (Button) findViewById(R.id.btnPlay);
aYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplay);

mOnInitializedListener = new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

//Load video list
/* List<String> videoList = new ArrayList<>();
videoList.add("saIqHKolTHc");
videoList.add("ov8YX9tNyio");
youTubePlayer.loadVideos(videoList); */

//play list
//youTubePlayer.loadPlaylist("PLIFW--Hzc0hbgKs_ZIzMWnElNkHkpsmGP");

//play video
youTubePlayer.loadVideo("saIqHKolTHc");
}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

}
};

btnPlay.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
aYouTubePlayerView.initialize(Config.getYoutubeApiKey(),mOnInitializedListener);
}
});

}
}



Thanks You


  





Monday 25 May 2020

Android edit text to show the dd-mm-yyyy date format






Add this code your onTextChanged event.


        EditText date;

        date = (EditText)findViewById(R.id.edtDateofbirth);
        date.addTextChangedListener(new TextWatcher() {
            private String current = "";
            private String ddmmyyyy = "DDMMYYYY";
            private Calendar cal = Calendar.getInstance();


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.toString().equals(current)) {
                    String clean = s.toString().replaceAll("[^\\d.]", "");
                    String cleanC = current.replaceAll("[^\\d.]", "");

                    int cl = clean.length();
                    int sel = cl;
                    for (int i = 2; i <= cl && i < 6; i += 2) {
                        sel++;
                    }
                    //Fix for pressing delete next to a forward slash
                    if (clean.equals(cleanC)) sel--;

                    if (clean.length() < 8){
                        clean = clean + ddmmyyyy.substring(clean.length());
                    }else{
                        //This part makes sure that when we finish entering numbers
                        //the date is correct, fixing it otherwise
                        int day  = Integer.parseInt(clean.substring(0,2));
                        int mon  = Integer.parseInt(clean.substring(2,4));
                        int year = Integer.parseInt(clean.substring(4,8));

                        if(mon > 12) mon = 12;
                        cal.set(Calendar.MONTH, mon-1);

                        year = (year<1900)?1900:(year>2100)?2100:year;
                        cal.set(Calendar.YEAR, year);
                        // ^ first set year for the line below to work correctly
                        //with leap years - otherwise, date e.g. 29/02/2012
                        //would be automatically corrected to 28/02/2012

                        day = (day > cal.getActualMaximum(Calendar.DATE))? cal.getActualMaximum(Calendar.DATE):day;
                        clean = String.format("%02d%02d%02d",day, mon, year);
                    }

                    clean = String.format("%s/%s/%s", clean.substring(0, 2),
                            clean.substring(2, 4),
                            clean.substring(4, 8));

                    sel = sel < 0 ? 0 : sel;
                    current = clean;
                    date.setText(current);
                    date.setSelection(sel < current.length() ? sel : current.length());



                }
            }


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void afterTextChanged(Editable s) {}
        });







Tuesday 29 October 2019

Download File From Server in Android


How to Download an image in ANDROID programatically?

How to Download an pdf in ANDROID programatically?



Open new project and add these code.
This an simple example for downloading files from server in android programatically.

The java code to download the file.
MainActivity.java

package com.example.root.download;

import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static Button btnDownload;

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

        btnDownload = (Button) findViewById(R.id.btnDownload);
        btnDownload.setOnClickListener(new View.OnClickListener() {

        @Override
         public void onClick(View view) {

                //ok calll downloading
                new Downloading().execute();

                Toast.makeText(MainActivity.this,"Downloading             completed",Toast.LENGTH_LONG).show();
            }
        });

    }


    //add downloading
    private class Downloading extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {

            try {
             
               //This is the file we are going to download.
               //Please add your server file location .
                URL url = new URL("http://www.mission2win.in/pdf/pdf22.pdf");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                //Connect
                urlConnection.connect();

                //set path where to save the file
                File SDCardRoot = Environment.getExternalStorageDirectory();
                //create a new file to save
                File file = new File(SDCardRoot,"pdf22.pdf");

                FileOutputStream fileOutput = new FileOutputStream(file);

                //stream used for reading the data from the internet
                InputStream inputStream = urlConnection.getInputStream();


                //create a buffer
                byte[] buffer = new byte[124];
                int bufferLength = 0;


                while( (bufferLength = inputStream.read(buffer)) > 0){
                    fileOutput.write(buffer,0,bufferLength);
                }

                //close the output stream when complete
                fileOutput.close();

            }
            catch (final MalformedURLException e){
                showError("Error : MalformURLException " + e);
                e.printStackTrace();
            }
            catch (final IOException e){
                showError("Error : IOException " + e);
                e.printStackTrace();
            }
            catch (final Exception e){
                showError("Error : Please check your internet connection " + e);
            }

            return null;
        }

        void showError(final String err){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,err,Toast.LENGTH_LONG).show();
                }
            });
        }

    }
}


This is the contents of xml file.
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.root.download.MainActivity">

    <Button
        android:id="@+id/btnDownload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download File"
        />

</RelativeLayout>


Add Internet and Write to External Directory permissions to AndroidManifest.xml
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.root.download">

    <!-- Permission required for Downloading Files -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Permission required for Checking Internet Connection -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- Permission required for Reading Writing SD Card/Memory -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 Now run the app on your Android device.






open failed: EACCES (Permission denied)

Verify permission and add this code to give a permission

 public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }


Other wise add several permission to Manifest file.

<!-- Permission required for Downloading Files -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Permission required for Checking Internet Connection -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Permission required for Reading Writing SD Card/Memory -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />






Android download a file from remote server With progressbar 


Create a new xml file inside res/layout folder and name it progressdialog.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    >

    <TextView
        android:id="@+id/heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0F0"
        android:text="Heading"
        android:textStyle="bold|italic"
        android:layout_marginTop="5dp"

        />

    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:progress="0"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="10dp"
        style="?android:attr/progressBarStyleHorizontal"
        android:maxHeight="10dip"
        android:minHeight="10dip"
        />

</LinearLayout>


Colored code add to Main_Activity.java

package com.example.root.download;

import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static Button btnDownload;

    ProgressBar progressBar;
    Dialog dialog;
    int downloadedSize =0;
    int totalSize=0;
    TextView heading;

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


        btnDownload = (Button) findViewById(R.id.btnDownload);

        btnDownload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {


                showProgress();
                //ok calll downloading
                new Downloading().execute();

                Toast.makeText(MainActivity.this,"Downloading completed",Toast.LENGTH_LONG).show();

            }
        });


    }


    //add downloading
    private class Downloading extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {

            try {

                URL url = new URL("http://www.mission2win.in/pdf/pdf22.pdf");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                //Connect
                urlConnection.connect();

                //set path where to save the file
                File SDCardRoot = Environment.getExternalStorageDirectory();
                //create a new file to save
                File file = new File(SDCardRoot,"pdf22.pdf");

                FileOutputStream fileOutput = new FileOutputStream(file);

                //stream used for reading the data from the internet
                InputStream inputStream = urlConnection.getInputStream();

                //This is total size of the downloading file
                totalSize = urlConnection.getContentLength();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setMax(totalSize);
                    }
                });


                //create a buffer
                byte[] buffer = new byte[124];
                int bufferLength = 0;


                while( (bufferLength = inputStream.read(buffer)) > 0){
                    fileOutput.write(buffer,0,bufferLength);
                    downloadedSize += bufferLength;
                    //Update progress bar
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setProgress(downloadedSize);
                        }
                    });
                }

                //close the output stream when complete
                fileOutput.close();

                //close dialog
                dialog.dismiss();

            }
            catch (final MalformedURLException e){
                showError("Error : MalformURLException " + e);
                e.printStackTrace();
            }
            catch (final IOException e){
                showError("Error : IOException " + e);
                e.printStackTrace();
            }
            catch (final Exception e){
                showError("Error : Please check your internet connection " + e);
            }



            return null;
        }

        void showError(final String err){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,err,Toast.LENGTH_LONG).show();
                }
            });
        }


    }



    void showProgress(){
        dialog = new Dialog(MainActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.progressdialog); //this is my created xml file
        dialog.setTitle("Download Progress");

        heading = (TextView) dialog.findViewById(R.id.heading);
        heading.setText("Download starting ...");
        dialog.show();

        progressBar = (ProgressBar)dialog.findViewById(R.id.progressbar);
        progressBar.setProgress(0);

    }


}