Sunday, September 29, 2019

upload images code

main java


package com.google.top.my;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    Button chooseImg, uploadImg;
    ImageView imgView;
    int PICK_IMAGE_REQUEST = 111;
    Uri filePath;
    ProgressDialog pd;

    //creating reference to firebase storage    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://wallpaper-app-1b2cd.appspot.com");    //change the url according to your firebase app

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

        chooseImg = (Button)findViewById(R.id.chooseImg);
        uploadImg = (Button)findViewById(R.id.uploadImg);
        imgView = (ImageView)findViewById(R.id.imgView);

        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");


        chooseImg.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });

        uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                if(filePath != null) {
                    pd.show();
                    String imageID = UUID.randomUUID().toString();
                    StorageReference childRef = storageRef.child(imageID);

                    //uploading the image                    UploadTask uploadTask = childRef.putFile(filePath);

                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                           @Override                             public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            pd.dismiss();
                            Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
                        }
                    });

                     uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override                        public void onFailure(@NonNull Exception e) {
                            pd.dismiss();
                            Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                else {
                    Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

                       @Override                  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                 super.onActivityResult(requestCode, resultCode, data);

                   if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                      filePath = data.getData();

                      try {
                //getting image from gallery                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);

                //Setting image to ImageView                         imgView.setImageBitmap(bitmap);
                        } catch (Exception e) {
                         e.printStackTrace();
                   }
        }
    }
}






<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"    android:orientation="vertical"    tools:context=".MainActivity">


    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Choose Image"        android:id="@+id/chooseImg"/>

    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Upload Image"        android:id="@+id/uploadImg"/>

    <ImageView        android:layout_width="match_parent"        android:layout_height="300dp"        android:id="@+id/imgView"/>


</LinearLayout>




appp


implementation 'com.google.firebase:firebase-storage:16.0.4'implementation 'com.google.firebase:firebase-auth:16.0.5'
apply plugin: 'com.google.gms.google-services'




classpath 'com.google.gms:google-services:4.2.0'

Friday, September 20, 2019

video player

main activity .java



package com.google.earnshayro.myplyer;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    private EditText videoPathEditor = null;

    private Button browseVideoFileButton = null;

    private Button playVideoButton = null;

    private Button stopVideoButton = null;

    private Button pauseVideoButton = null;

    private Button continueVideoButton = null;

    private Button replayVideoButton = null;

    private VideoView playVideoView = null;

    private ProgressBar videoProgressBar = null;

    // Request code for user select video file.    private static final int REQUEST_CODE_SELECT_VIDEO_FILE = 1;

    // Request code for require android READ_EXTERNAL_PERMISSION.    private static final int REQUEST_CODE_READ_EXTERNAL_PERMISSION = 2;

    // Used when update video progress thread send message to progress bar handler.    private static final int UPDATE_VIDEO_PROGRESS_BAR = 3;

    // Save local video file uri.    private Uri videoFileUri = null;

    // Wait update video progress thread sent message, then update video play progress.    private Handler videoProgressHandler = null;

    // Save current video play position.    private int currVideoPosition = 0;

    // Save whether the video is paused or not.    private boolean isVideoPaused = false;

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

        // Init this example used video components.        initVideoControls();

        // When user input video file url in the video file path edittext input text box.        videoPathEditor.setOnKeyListener(new View.OnKeyListener() {
            @Override            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                int action = keyEvent.getAction();
                if(action == KeyEvent.ACTION_UP) {
                    String text = videoPathEditor.getText().toString();
                    if (text.length() > 0) {
                        // If user input video file url, enable play button.                        playVideoButton.setEnabled(true);
                        pauseVideoButton.setEnabled(false);
                        replayVideoButton.setEnabled(false);
                    } else {
                        // If user input nothing, disable all buttons.                        playVideoButton.setEnabled(false);
                        pauseVideoButton.setEnabled(false);
                        replayVideoButton.setEnabled(false);
                    }
                }
                return false;
            }
        });

        // If user click browse video file button.        browseVideoFileButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                // Check whether user has granted read external storage permission to this activity.                int readExternalStoragePermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);

                // If not grant then require read external storage permission.                if(readExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
                {
                    String requirePermission[] = {Manifest.permission.READ_EXTERNAL_STORAGE};
                    ActivityCompat.requestPermissions(MainActivity.this, requirePermission, REQUEST_CODE_READ_EXTERNAL_PERMISSION);
                }else {
                    selectVideoFile();
                }
            }
        });

        // Click this button to play user browsed or input video file.        playVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                String videoFilePath = videoPathEditor.getText().toString();

                if(!TextUtils.isEmpty(videoFilePath))
                {
                    if(!videoFilePath.trim().toLowerCase().startsWith("http")) {
                        // Play local video file.                        playVideoView.setVideoURI(videoFileUri);
                    }else                    {
                        // Convert the web video url to a Uri object.                        Uri webVideoFileUri = Uri.parse(videoFilePath.trim());

                        // Play web video file use the Uri object.                        playVideoView.setVideoURI(webVideoFileUri);
                    }

                    playVideoView.setVisibility(View.VISIBLE);

                    videoProgressBar.setVisibility(ProgressBar.VISIBLE);

                    currVideoPosition = 0;

                    playVideoView.start();

                    playVideoButton.setEnabled(false);

                    stopVideoButton.setEnabled(true);

                    pauseVideoButton.setEnabled(true);

                    continueVideoButton.setEnabled(false);

                    replayVideoButton.setEnabled(true);
                }

            }
        });

        // Click this button to stop playing video file.        stopVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                // Stop video playing.                playVideoView.stopPlayback();

                // Seek to the beginning of the video file.                playVideoView.seekTo(0);

                playVideoButton.setEnabled(true);

                stopVideoButton.setEnabled(false);

                pauseVideoButton.setEnabled(false);

                continueVideoButton.setEnabled(false);

                replayVideoButton.setEnabled(false);
            }
        });

        // Click this button to pause playing video file.        pauseVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                // Pause video play.                playVideoView.pause();

                isVideoPaused = true;

                // Record current video play position.                currVideoPosition = playVideoView.getCurrentPosition();

                playVideoButton.setEnabled(false);

                stopVideoButton.setEnabled(true);

                pauseVideoButton.setEnabled(false);

                continueVideoButton.setEnabled(true);

                replayVideoButton.setEnabled(true);
            }
        });

        // Click this button to continue play paused video.        continueVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                playVideoView.seekTo(currVideoPosition);

                playVideoButton.setEnabled(false);

                pauseVideoButton.setEnabled(true);

                stopVideoButton.setEnabled(true);

                continueVideoButton.setEnabled(false);

                replayVideoButton.setEnabled(true);
            }
        });

        // Click this button to replay video file.        replayVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                // Replay video.                playVideoView.resume();

                // Set current video play position to 0.                currVideoPosition = 0;

                playVideoButton.setEnabled(false);

                pauseVideoButton.setEnabled(true);

                stopVideoButton.setEnabled(true);

                continueVideoButton.setEnabled(false);

                replayVideoButton.setEnabled(true);
            }
        });
    }

    /*      Initialise play video example controls.    * */    private void initVideoControls()
    {
        if(videoPathEditor==null)
        {
            videoPathEditor = (EditText) findViewById(R.id.play_video_file_path_editor);
        }

        if(browseVideoFileButton==null)
        {
            browseVideoFileButton = (Button)findViewById(R.id.browse_video_file_button);
        }

        if(playVideoButton==null)
        {
            playVideoButton = (Button)findViewById(R.id.play_video_start_button);
        }

        if(stopVideoButton==null)
        {
            stopVideoButton = (Button)findViewById(R.id.play_video_stop_button);
        }

        if(pauseVideoButton==null)
        {
            pauseVideoButton = (Button)findViewById(R.id.play_video_pause_button);
        }

        if(continueVideoButton==null)
        {
            continueVideoButton = (Button)findViewById(R.id.play_video_continue_button);
        }

        if(replayVideoButton==null)
        {
            replayVideoButton = (Button)findViewById(R.id.play_video_replay_button);
        }

        if(playVideoView==null)
        {
            playVideoView = (VideoView)findViewById(R.id.play_video_view);
        }

        if(videoProgressBar==null)
        {
            videoProgressBar = (ProgressBar) findViewById(R.id.play_video_progressbar);
        }

        if(videoProgressHandler==null)
        {
            // This handler wait and receive update progress bar message from child thread.            videoProgressHandler = new Handler(){
                @Override                public void handleMessage(Message msg) {
                    // When receive update progressbar message.                    if(msg.what == UPDATE_VIDEO_PROGRESS_BAR)
                    {
                        // Get current video play position.                        int currVideoPosition = playVideoView.getCurrentPosition();

                        // Get total video length.                        int videoDuration = playVideoView.getDuration();

                        // Calculate the percentage.                        int progressPercent = currVideoPosition * 100 / videoDuration;

                        // 10 times percentage value to make effect clear.                        videoProgressBar.setProgress(progressPercent);
                    }
                }
            };

            // This thread send update video progress message to video progress Handler every 2 seconds.            Thread updateProgressThread = new Thread()
            {
                @Override                public void run() {

                    try {
                        while (true) {
                            // Create update video progressbar message.                            Message msg = new Message();
                            msg.what = UPDATE_VIDEO_PROGRESS_BAR;

                            // Send the message to video progressbar update handler.                            videoProgressHandler.sendMessage(msg);

                            // Sleep 2 seconds.                            Thread.sleep(2000);
                        }
                    }catch (InterruptedException ex)
                    {
                        ex.printStackTrace();
                    }
                }
            };
            // Start the thread.            updateProgressThread.start();
        }

        setContinueVideoAfterSeekComplete();
    }

    /* This method start get content activity to let user select video file from local directory.*/    private void selectVideoFile()
    {
        // Create an intent with action ACTION_GET_CONTENT.        Intent selectVideoIntent = new Intent(Intent.ACTION_GET_CONTENT);

        // Show video in the content browser.        // Set selectVideoIntent.setType("*/*") to select all data        // Intent for this action must set content type, otherwise you will encounter below exception : android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT }        selectVideoIntent.setType("video/*");

        // Start android get content activity ( this is a android os built-in activity.) .        startActivityForResult(selectVideoIntent, REQUEST_CODE_SELECT_VIDEO_FILE);
    }

    /* This method will be invoked when startActivityForResult method complete in selectVideoFile() method.     *  It is used to process activity result that is started by startActivityForResult method.     * */    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // Identify activity by request code.        if(requestCode == REQUEST_CODE_SELECT_VIDEO_FILE)
        {
            // If the request is success.            if(resultCode==RESULT_OK)
            {
                // To make example simple and clear, we only choose video file from local file,                // this is easy to get video file real local path.                // If you want to get video file real local path from a video content provider                // Please read another article.                videoFileUri = data.getData();

                String videoFileName = videoFileUri.getLastPathSegment();

                videoPathEditor.setText("You select video file is " + videoFileName);

                playVideoButton.setEnabled(true);

                pauseVideoButton.setEnabled(false);

                replayVideoButton.setEnabled(false);
            }
        }
    }

    /* Run this method after user choose grant read external storage permission or not. */    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==REQUEST_CODE_READ_EXTERNAL_PERMISSION)
        {
            if(grantResults.length > 0)
            {
                int grantResult = grantResults[0];
                if(grantResult == PackageManager.PERMISSION_GRANTED)
                {
                    // If user grant the permission then open browser let user select audio file.                    selectVideoFile();
                }else                {
                    Toast.makeText(getApplicationContext(), "You denied read external storage permission.", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /* This method is used to play video after seek complete, otherwise video playing will not be accurate.*/    private void setContinueVideoAfterSeekComplete()
    {
        playVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                    @Override                    public void onSeekComplete(MediaPlayer mediaPlayer) {
                        if(isVideoPaused)
                        {
                            playVideoView.start();
                            isVideoPaused = false;
                        }
                    }
                });
            }
        });
    }
}





activity main.xml





<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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">

    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical">

        <EditText            android:id="@+id/play_video_file_path_editor"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:hint="enter" />

        <Button            android:id="@+id/browse_video_file_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Video list"/>

        <Button            android:id="@+id/play_video_start_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Play Video"            android:enabled="false"/>

        <Button            android:id="@+id/play_video_stop_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Stop"            android:enabled="false"/>

        <Button            android:id="@+id/play_video_pause_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Pause"            android:enabled="false"/>

        <Button            android:id="@+id/play_video_continue_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Continue"            android:enabled="false"/>

        <Button            android:id="@+id/play_video_replay_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Replay"            android:enabled="false"/>

        <ProgressBar            android:id="@+id/play_video_progressbar"            style="@android:style/Widget.ProgressBar.Horizontal"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:max="100"            android:visibility="invisible"/>

        <VideoView            android:id="@+id/play_video_view"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:visibility="invisible"/>


    </LinearLayout>

</RelativeLayout>







main fest



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




Wednesday, July 20, 2016

Load Spinner with string-array from resources xml


To define string-array in resources xml, edit values/strings.xml to add items of string-array.
<resources>
<string name="app_name">AndroidSpinner</string>
<string-array name="weekday">
<item>Sunday</item>
<item>Monday</item>
<item>Tuesday</item>
<item>Wednesday</item>
<item>Thursday</item>
<item>Friday</item>
<item>Saturday</item>
</string-array>
</resources>


Edit layout/activity_main.xml to add Spinner with entries to load from string-array.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="com.example.androidspinner.MainActivity">

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android-coding.blogspot.com"
android:textSize="28dp"
android:textStyle="bold" />
<Spinner
android:id="@+id/myspinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/weekday"/>
</LinearLayout>


MainActivity.java
package com.example.androidspinner;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

Spinner mySpinner = (Spinner)findViewById(R.id.myspinner);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = (String)adapterView.getItemAtPosition(i);
Toast.makeText(MainActivity.this, item, Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});
}
}

Friday, March 4, 2016

Get the number of processor cores available to the VM

The method Runtime.availableProcessors() returns the number of processor cores available to the VM, at least 1. Traditionally this returned the number currently online, but many mobile devices are able to take unused cores offline to save power, so releases newer than Android 4.2 (Jelly Bean) return the maximum number of cores that could be made available if there were no power or heat constraints.


package example.com.androidprocessors;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

int availableProcessors = Runtime.getRuntime().availableProcessors();
Toast.makeText(MainActivity.this,
"Available Processors: " + availableProcessors,
Toast.LENGTH_LONG).show();
}
}

Saturday, January 16, 2016

Android Textual Layout (Android Dev Summit 2015)



Recent versions of Android have significant advances in typographic sophistication, including automatic hyphenation, balanced and optimized paragraph layout, OpenType features, support for dozens of scripts around the world, and more. Raph Levien, software engineer and tech lead of Android Text on the Android UI Toolkit team, covers these capabilities and how apps can make best use of them.

View presentation slides here: https://speakerdeck.com/raphlinus/android-textual-layout


Monday, November 23, 2015

What’s New in Android Studio 1.5

Android Studio 1.5 is focused on delivering more stability, with most of the enhancements being made under the hood. It adds new lint checks, the ability to use short names when code-completing custom views, and the memory profiler can now help you detect some of the most commonly known causes of leaked activities.

Android Studio 1.5 is now available to download from the stable release channel.

Find out more from Android Developers Blog: http://goo.gl/oIbJHO

Monday, November 9, 2015

What is Cardboard

What is Cardboard and Virtual Reality. This video introduces Cardboard for developers and how to use a phone and a simple box of Cardboard to tap into a new type of immersion with virtual reality.

Watch more episodes of Cardboard here:
https://goo.gl/IAoGGs



Cardboard: How Cardboard Works