Home Blog Page 42

Android Copy Text to Clipboard Programmatically – JAVA/KOTLIN

0
Android Copy Text to Clipboard Programmatically
copy to clipboard android

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial will learn how to copy a text programmatically into clipboard in android apps, Source Code below for both JAVA & KOTLIN developer.

Copy text to clipboard android programmatically

Below is complete source code to learn how to copy and paste on android programmatically (copy to clipboard android).

To Implement the same, we will use android clipboard manager

clipboard manager in android

Basically, android clipboard manager is a interface to a clipboard services, use to easily save any text in clipData and to retrieve the text global in a mobile device.

The ClipboardManager is best, easily to use & understand: it contains some methods by which we can get & set the current clipboard data as primary copyed text.

Snippet Code For Java

  ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

  ClipData clipData = ClipData.newPlainText("label","The Text you want to copy in clipboard");  // Example: In real-time, Value from textview

  clipboardManager.setPrimaryClip(clipData);

Snippet Code For Kotlin

  val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager

  val clipData = ClipData.newPlainText("label", txtview2cpy!!.text.toString())

  clipboardManager.setPrimaryClip(clipData)

Clipboard manager android example with source code

Note: Below code is just an example, Use it to implement in real-time projects. ALL THE BEST.

Code Explaination in brief

Below I have 2 views (TextView & a Button). In TextView I have a text that I want to copy into android clipboard as PainText data, Then I have a button that simply copy the text from textview and get saved into clipdata (so that I can paste the copied text somewhere else easily).

activity_main.xml – UI Design

<?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">

    <TextView
        android:id="@+id/txtview2cpy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textAlignment="center"
        android:text="On Click, This TextView Text get Copyed in clipboard programmatically...!!"
        android:textSize="22dp"
        app:layout_constraintBottom_toTopOf="@+id/bCopyText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/bCopyText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Copy"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt – For Kotlin Developer

package example.on.androidtextcopy

import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
import android.os.Bundle
import example.on.androidtextcopy.R
import android.content.ClipData
import android.content.ClipboardManager
import android.view.View
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    var txtview2cpy: TextView? = null
    var bCopyText: Button? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        txtview2cpy = findViewById<View>(R.id.txtview2cpy) as TextView
        bCopyText = findViewById<View>(R.id.bCopyText) as Button
        val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        bCopyText!!.setOnClickListener {
            val clipData = ClipData.newPlainText("label", txtview2cpy!!.text.toString())
            clipboardManager.setPrimaryClip(clipData)
            Toast.makeText(this@MainActivity, "Text Copyed", Toast.LENGTH_SHORT).show()
        }
    }
}

MainActivity.javacopy to clipboard android programmatically

package example.on.androidtextcopy;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView txtview2cpy;
    Button bCopyText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtview2cpy = (TextView) findViewById(R.id.txtview2cpy);
        bCopyText = (Button) findViewById(R.id.bCopyText);
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        bCopyText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipData clipData = ClipData.newPlainText("label",txtview2cpy.getText().toString());
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(MainActivity.this,"Text Copyed",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

How to Check if string is empty/Null in flutter

0
how to Check if string is empty in dart
how to Check if string is empty in dart

Hi Guy’s Welcome to Proto Coders Point, In this Flutter dart article let’s learn how to validate a String Variable to check if the given String is empty or null.

Suppose, You are building an application where you ask user to enter some data & you don’t accept empty or null value.

At situation, we need to check if string is empty or null, Let’s Start:

Function to check of String is null or empty

Will create a function/method that will validate our string, Let’s name the function as stringValidator()

bool stringvalidator(String? value) {
  if (value == null) {
    return false;
  }

  if (value.isEmpty) {
    return false;
  }

  return true;
}

Let’s make the above function shorter by using ternary operation in dart.

bool stringvalidator(String? value) {
   return value?.isNotEmpty ?? false;
}

The above function, return true if String variable contain atleast one character, else return false if string is empty or null.

Complete Code – To check if string variable is empty or null in dart Flutter

bool stringvalidator(String? value) {
   return value?.isNotEmpty ?? false;
}

void main() {
  print(stringvalidator(''));   // false
  print(stringvalidator('Rajat Palankar'));    // true
  print(stringvalidator(null));   // false
}

Listview Selected Item Next Page with Next and Previous Button

0
flutter listview pass data
flutter listview pass data

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial article will learn how to build listview with list of items in it, & onTap selected item will be displayed on next screen, In the mean while will learn how to pass selected data to next screen.

I has already wrote a complete article on “Flutter Listview onTap Selected Item – send data to new screen” and have a complete step by step video tutorial on youtube ( Check below Video at bottom on this article ).

Flutter Listview OnTap Pass Selected Data to Next Page, with Next & Previous Button to switch items

Video Tutorial


Flutter Listview onTap pass data to next page & has next & previous button on page 2

So when user select an item from listview.builder, the selected item data is been passed to page 2 and data is been shown, but if the user wants to read next data item from the list then he has to go back to first page and select the next data item from listview, which is not fully userfriendly.

In this flutter tutorial article, will add new Feature i.e:

In page no 2, There will be 2 buttons (previous & next) by using which user can change or swap the item from listview by being in page 2 itself. There is not need for user to go back to page 1 to select next item from list.


Complete Source Code – Flutter Listview With Example

Step by Step

We need to create 2 Screen and a dataModel class

(Screen 1) main.dart: Will generate list of data and show in flutter listview.

(Screen 2) FruitDetail.dart: User selected item data will be shown here.

(DataModel) FruitDataModel: Holds Information or a data.

Create above 3 files, for better understanding refer my file project structure.

1. FruitDataModel.dart

A Data Model are class of entities that holds information or a data.

In our app, DataModel has 3 String datatype.

Eg: Name of Fruit.
ImageUrl of Fruit.
Description of Fruit.

Code DataModel

class FruitDataModel{
  final String name,ImageUrl,desc;

  FruitDataModel(this.name, this.ImageUrl, this.desc);
}

DataModel will have a constructor to assign the value to variables strings.


2. FruitDetail.dart

In fruitDetail page, will display details of selected Item from the listview of flutter app.

FruitDetail has a constructor that accept 2 parameter from page 1(main.dart) while navigating.

  1. Index of user selected item from list.
  2. FruitDataModel The whole List of data.

It also has 2 buttons (Prev & Next) by which user can change contents of the page.

Code – FruitDetial.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:listview_on_tap/FruitDataModel.dart';
import 'dart:convert';

class FruitDetail extends StatefulWidget {
  final List<FruitDataModel> fruitDataModel;
  int index;
  FruitDetail({Key? key, required this.index, required this.fruitDataModel}) : super(key: key);

  @override
  State<FruitDetail> createState() => _FruitDetailState();
}

class _FruitDetailState extends State<FruitDetail> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.fruitDataModel[widget.index].name),),
      body: Column(
        children: [
          Image.network(widget.fruitDataModel[widget.index].ImageUrl),
          SizedBox(
            height: 10,
          ),
          Text(widget.fruitDataModel[widget.index].desc,style: TextStyle(fontWeight: FontWeight.bold,fontSize: 20),),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              FloatingActionButton(
                heroTag: "f1",
                onPressed: (){
                  setState(() {
                    if(widget.index!=0){
                      widget.index --;
                    }
                  });
                },
                child:Icon(Icons.arrow_back_ios) ,
              ),
              FloatingActionButton(
                heroTag: "f2",
                onPressed: (){
                  setState(() {
                    if(widget.index != widget.fruitDataModel.length-1){
                      widget.index ++;
                    }
                  });
                },
                child:Icon(Icons.arrow_forward_ios),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

3. main.dart

main.dart is the first page/screen, Here we will generate list of data and then pass the list to show the data in listview.builder.

Then when user onTap on any item from listview, we are using Navigator to navigate the user from main.dart to fruitDetail.dart page.

With PageNavigator we are passing 2 parameter to page 2 (fruitDetail.dart)

  • Index of user selected item from list.
  • FruitDataModel The whole List of data.

Code main.dart

import 'package:flutter/material.dart';
import 'package:listview_on_tap/FruitDataModel.dart';
import 'package:listview_on_tap/FruitDetail.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  static List<String> fruitname =['Apple','Banana','Mango','Orange','pineapple'];

  static List<String> url = ['https://www.applesfromny.com/wp-content/uploads/2020/05/Jonagold_NYAS-Apples2.png',
    'https://cdn.mos.cms.futurecdn.net/42E9as7NaTaAi4A6JcuFwG-1200-80.jpg',
    'https://upload.wikimedia.org/wikipedia/commons/thumb/9/90/Hapus_Mango.jpg/220px-Hapus_Mango.jpg',
    'https://5.imimg.com/data5/VN/YP/MY-33296037/orange-600x600-500x500.jpg',
    'https://5.imimg.com/data5/GJ/MD/MY-35442270/fresh-pineapple-500x500.jpg'];

  final List<FruitDataModel> Fruitdata = List.generate(fruitname.length, (index) => FruitDataModel('${fruitname[index]}', '${url[index]}','${fruitname[index]} Description...'));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Pass Data from ListView to next Screen'),),
        body: ListView.builder(
            itemCount: Fruitdata.length,
            itemBuilder: (context,index){
              return Card(
                child: ListTile(
                  title: Text(Fruitdata[index].name),
                  leading: SizedBox(
                    width: 50,
                    height: 50,
                    child: Image.network(Fruitdata[index].ImageUrl),
                  ),
                  onTap: (){
                    Navigator.of(context).push(MaterialPageRoute(builder: (context)=>FruitDetail(index: index,fruitDataModel: Fruitdata,)));
                  },
                ),
              );
            }
        )
    );
  }
}

The Below Video is only to learn how to pass data selected from listview item to next page.

Multiple heroes that share the same tag within a subtree – FloatingActionButton

0

Hi Guys Welcome to Proto Coders Point. This article is on a quick solution to an error i.e "There are multiple heroes that share the same tag within a subtree" in flutter.

Long time ago while developing a flutter application for my client, I encountered an error been show when I used 2 or more FloatingActionButton on same page.

How to Solve Multiple Heroes error in flutter

My FloatingActionButton Previous Snippet Code

floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          FloatingActionButton(
            onPressed: (){},
            child:Icon(Icons.arrow_back_ios) ,
          ),
          FloatingActionButton(onPressed: (){},
            child:Icon(Icons.arrow_forward_ios),
          ),
        ],
      ),
I/flutter (21786): In this case, multiple heroes had the following tag: default FloatingActionButton tag

Here the Error simple means that, If you are adding more then 1 FloatingActionButton widget in one page or screen, then you have to add heroTag to each FloatingActionButton widget.

My FloatingActionButton after adding heroTag

floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          FloatingActionButton(
            heroTag: "f1",   // add a unique tag
            onPressed: (){},
            child:Icon(Icons.arrow_back_ios) ,
          ),
          FloatingActionButton(
            heroTag: "f2",   // add a unique tag
            onPressed: (){},
            child:Icon(Icons.arrow_forward_ios),
          ),

        ],
      ),

Just by adding unique heroTag to FloatingActionButton the error will get solved 100%.

How to programmatically take a screenshot in android

0
Programmatically take screenshot
Programmatically take screenshot

Hi Guys, Welcome to Proto Coders Point. In this Android Article will learn how to implement taking screenshot in your android application, Now every mobile device has a inbuilt feature by which users can easily capture screenshots.

Suppose you want to implement programmatically take screenshot in your android application as a special feature of your app then this article will help you.

Take Screenshot in android programmatically

Final Output of below code implementation

Implementation Step by Step

Step 1: Open or Create new Android Project

Create a new android project in android studio or open any existing android project where you want to implement screenshot taking feature.


Step 2: Add storage read & Write permission

As we are going to take screenshot and store the capture image in storage, we need to add permission to access storage, Therefore open AndroidManifest.xml file

Android > app > Manifest > AndroidManifest.xml

Within Manifest tag add below 3 storage permission

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.on.take_screenshot">    
    
    //add this 3 permission
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />



</manifest>

Then next you need to enable requestLegacyExternalStorage inside <application.> as show below:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.on.take_screenshot">    
    
    //add this 3 permission
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

     <application
        android:requestLegacyExternalStorage="true"     //add this line
        android:allowBackup="true"
        .......
        .......
        .......
       >


</manifest>

Step 3: Layout design

Now, Let’s create a layout view or page of which our program will take screenshot programmatically.

activity_main.xml

Copy the below code in activty_main.xml file as UI design.

<?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:gravity="center"
    android:id="@+id/parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:src="@mipmap/ic_launcher_round"
        android:layout_marginBottom="15dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="To Capture Hit below Button"
        android:textColor="#302F2F"
        android:textSize="20dp"
        android:textStyle="bold|italic" />

    <Button
        android:id="@+id/takeshot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#11BFD6"
        android:text="Take Shot" />

</LinearLayout>

Step 4: Giving Life to UI, Working on MainActivity.java

Refer below MainActivity.java code , Comment are been added for better understanding while code go through.

package example.on.take_screenshot;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    Button take;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] permissionstorage = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        take = findViewById(R.id.takeshot);
        checkpermissions(this); // check or ask for storage permission
        take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //pass layout view to method to perform capture screenshot and save it.
                takeScreenshot(getWindow().getDecorView().getRootView());
            }
        });
    }

    protected File takeScreenshot(View view) {
        Date date = new Date();
        try {
            String dirpath;
            // Initialising the directory of storage
            dirpath= MainActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() ;
            File file = new File(dirpath);
            if (!file.exists()) {
                boolean mkdir = file.mkdir();
            }
            // File name : keeping file name unique using data time.
            String path = dirpath + "/"+ date.getTime() + ".jpeg";
            view.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
            view.setDrawingCacheEnabled(false);
            File imageurl = new File(path);
            FileOutputStream outputStream = new FileOutputStream(imageurl);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
            outputStream.flush();
            outputStream.close();
            Log.d(TAG, "takeScreenshot Path: "+imageurl);
            Toast.makeText(MainActivity.this,""+imageurl,Toast.LENGTH_LONG).show();
            return imageurl;

        } catch (FileNotFoundException io) {
            io.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // check weather storage permission is given or not
    public static void checkpermissions(Activity activity) {
        int permissions = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        // If storage permission is not given then request for External Storage Permission
        if (permissions != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, permissionstorage, REQUEST_EXTERNAL_STORAGE);
        }
    }

}

Result

Android FileNotFoundException: open failed EPERM Operation not permitted

0
eperm operation not permitted
eperm operation not permitted

Hi Guys, Welcome to Proto Coders Point. So once i was trying to implement programmatically taking screenshot in android ap development and I faced a problem while saving the captured screenshot to gallery, & this is the error i got FileNotFoundException: open failed: EPERM (Operation not permitted), After lot’s of trial & error, finally got the solution to solve EPERM issue in android while saving file in android.

 Let’s start to solve operation not permitted issue in android

How To Solve FileNotFoundException open failed: EPERM (Operation not permitted) Error

Here is a very simple soltion to easily solve FileNotFoundException open Failed: EPERM: You have to has a permission where you are allowing you android appliation to access External Storage, add it.

To add requestLegacyExternalStorage, just go to AndroidManifest.xml

Project > app > manifest > AndroidManifest.xml

Open it, then inside application tag add

 android:requestLegacyExternalStorage=”true” 

For Reference image:

make legacy extenal storage to true

Now, just Uninstall app and reinstall app it again & you will see your eror got successfully solved.