Home Blog Page 71

Android studio logcat not showing anything | 100% working solution found

0
logcat not showing

Hi Guys, Welcome to Proto Coders Point, So a few days back I got a query from one of my subscribers on my youtube channel that his android studio logcat is not showing anything,

Then Today I was working on my project and I was testing the app on my 2 devices as shown in the video Below

Here I have made use of 2 android devices that MI A2 and Redmi Note 7 Pro,

Then what was happening is MI A2 log data is getting displayed in android studio, but Redmi Note 7 Pro logcat not showing android studio. Even I faced the same issue i.e. android studio logcat not showing.

So Then I tried to find the solution for the Empty logcat, I visited StackOverflow and many other websites to find the Solution, I almost spend 4 hours solving it.


Android studio logcat not showing anything

So here are some Solution  you can try

Solution 1: Restarting your Android Studio

In your IDE Go to File > Invalidate Caches and Restart > Invalidate and Restart. This Solution will clear all the caches of Android studio IDE and restart it automatically, By the method, there are 80% change that Logcat will start work as before.

Refer screenshot below


Solution 2: Restart your mobile Devices

Just restart your mobile device and then check if logcat is showing or no.


Solution 3: Android Debug Bridge (ADB) use libusb backend

Android Studio > Preferences > Debugger > Android Debug Bridge (ADB) enable “Use libusb backend”

and then restart your android studio with Invalidate cache & Restart


Solution 4: Increasing Logger Bugger Sizes ( This Worked with me )

In your mobile device go to –>Settings –> Developer Options –> search for Logger buffer Sizes ( change it to 1M or Bigger size ) and then your android studio IDE will show data in Logcat.

Refer Screenshot

debug logger buffer size

logger sizes per log buffer

How to get mac address of android phone programmatically

0
How to get mac address of android phone programmatically

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will check out How to get mac address of android phone programmatically – find mac address android devices.

So let’s begin

Find MAC Address of android Device Programmatically

Step 1 : Create a new Android Project

Step 2 : Add required Permission

Then, to get MAC Address of any android device you need to add some permission like ACCESS WIFI STATE, INTERNET, ACCESS NETWORK STATE.
To add them:

In your Android Manifest.xml file add below uses permission, just before <application> tag begin

<uses-permission>

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

Step 3: Create a method GetMacAddress

Now, create a method that help you in getting mac address of your android mobile device.

public String getMacAddress(){
        try{
            List<NetworkInterface> networkInterfaceList = Collections.list(NetworkInterface.getNetworkInterfaces());

            String stringMac = "";

            for(NetworkInterface networkInterface : networkInterfaceList)
            {
                if(networkInterface.getName().equalsIgnoreCase("wlon0"));
                {
                    for(int i = 0 ;i <networkInterface.getHardwareAddress().length; i++){
                        String stringMacByte = Integer.toHexString(networkInterface.getHardwareAddress()[i]& 0xFF);

                        if(stringMacByte.length() == 1)
                        {
                            stringMacByte = "0" +stringMacByte;
                        }

                        stringMac = stringMac + stringMacByte.toUpperCase() + ":";
                    }
                    break;
                }

            }
            return stringMac;
        }catch (SocketException e)
        {
            e.printStackTrace();
        }

        return  "0";
    }

Step 4: Call the above method

By calling above getMacAddress() you will get mac address of android device.

String mobile_mac_addres = getMacAddress();  //call the method that return mac address 

Log.d("MyMacIS",mobile_mac_address);   // print the mac address on logcat screen

Here, we are calling getMacAddress() method and storing the MAC ADDRESS in a String Varaible.

How to get mac address of android phone programmatically – Complete Source Code

MainActivity.java

package com.example.getmacaddress;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    String mobile_mac_address;
    TextView macaddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        macaddress = (TextView)findViewById(R.id.macaddress);

        mobile_mac_address = getMacAddress();

        Log.d("MyMacIS",mobile_mac_address);

        macaddress.setText(mobile_mac_address);

    }

    public String getMacAddress(){
        try{
            List<NetworkInterface> networkInterfaceList = Collections.list(NetworkInterface.getNetworkInterfaces());

            String stringMac = "";

            for(NetworkInterface networkInterface : networkInterfaceList)
            {
                if(networkInterface.getName().equalsIgnoreCase("wlon0"));
                {
                    for(int i = 0 ;i <networkInterface.getHardwareAddress().length; i++){
                        String stringMacByte = Integer.toHexString(networkInterface.getHardwareAddress()[i]& 0xFF);

                        if(stringMacByte.length() == 1)
                        {
                            stringMacByte = "0" +stringMacByte;
                        }

                        stringMac = stringMac + stringMacByte.toUpperCase() + ":";
                    }
                    break;
                }

            }
            return stringMac;
        }catch (SocketException e)
        {
            e.printStackTrace();
        }

        return  "0";
    }


}

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

    <TextView
        android:id="@+id/macaddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

Flutter Calender Widget Example – Table Calender Widget

0
Flutter calendar widget example
Flutter calendar widget example

Hi Guys Welcome to Proto Coders Point, In this article we will learn how to add calender in your flutter application.

Calender Widget in Flutter App

Using Calender you can organize the day, week and month, you can also check religious or any social event in flutter calender widget, It keeps a data of event or festival event that comes on a particular date or ant special event on calender.

In this tutorial article, we will check out how to use table_calender widget to display calender widget in flutter application.

So as you know that flutter team, keeps on work to build best UI widget so that developer work becames much easier, So our Flutter team has provided a best simple calender by name Table_Calender that makes easy to display a calender in our flutter app.

The table calender widget in flutter is a powerful widget which comes with many feature, customizable feature and even such a gesture and animation etc.

Feature of table calender widget

  • Easy to use API.
  • UI can be controlled using Custom Builder calender
  • Beautiful animation feature.
  • Gesture Detector
  • Has Multiple calender formats like year, month, week.
  • It has vertical auto sizing.

So, Let’s begin adding calender in flutter app

Step 1: Create a new Flutter Project

OffCourse, you need to open an existing flutter where you want to add calender or create a new flutter project,

Start your favorite IDE, In my case i make use of Android studio to build flutter apps.

New -> New Flutter Project -> Give a project title for example “Flutter Calender Example”.

Step 2 : Adding Dependencies

In your flutter project structure, you will file a file by name ‘pubspec.yaml’ open it, you need to add the dependencies ‘table_calender’ .

As shown in below screenshot

table calender widget

for the latest version of this package, kindly visit official site : https://pub.dev/packages/table_calendar/install

Step 3: Importing the calender dart file

Then now, once you have added the dependencies then you need to import the library/packge of calender where you want to use/display calender.

import 'package:table_calendar/table_calendar.dart';

Step 4: Code Process Explaination

1 : First we need to create a object for CalenderController that controls all the evven/action happening in calender & you need to initialize it in initState().

class _HomeCalendarPageState extends State<HomeCalendarPage> {
  CalendarController _controller;   //controller creation

  @override
  void initState() {
    super.initState();
    _controller = CalendarController();  //initializing it 
  }Flutt

 2 : Now you need to use calenderWidget i.e TableCalender as a child of Scafford Widget.

Scaffold(  
    body: SingleChildScrollView(  
      child: Column(  
        children: <Widget>[  
          TableCalendar()   // snippet code   // you need to customize it as per your UI // check below for full source code
        ],  
      ),  
    ),

above code is just a snipet code, you need to customize it as per you UI needs.

Flutter Calender Widget – Table Calender – Full Source Code

main.dart

Copy paste below code in main.dart file of your flutter project

import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomeCalendarPage(),
    );
  }
}

class HomeCalendarPage extends StatefulWidget {
  @override
  _HomeCalendarPageState createState() => _HomeCalendarPageState();
}

class _HomeCalendarPageState extends State<HomeCalendarPage> {
  CalendarController _controller;

  @override
  void initState() {
    super.initState();
    _controller = CalendarController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Calendar Example'),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TableCalendar(
              initialCalendarFormat: CalendarFormat.month,
              calendarStyle: CalendarStyle(
                  todayColor: Colors.blue,
                  selectedColor: Theme.of(context).primaryColor,
                  todayStyle: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 22.0,
                      color: Colors.white)
              ),
              headerStyle: HeaderStyle(
                centerHeaderTitle: true,
                formatButtonDecoration: BoxDecoration(
                  color: Colors.brown,
                  borderRadius: BorderRadius.circular(22.0),
                ),
                formatButtonTextStyle: TextStyle(color: Colors.white),
                formatButtonShowsNext: false,
              ),
              startingDayOfWeek: StartingDayOfWeek.monday,
              onDaySelected: (date, events,e) {
                print(date.toUtc());
              },

              builders: CalendarBuilders(
                selectedDayBuilder: (context, date, events) => Container(
                    margin: const EdgeInsets.all(5.0),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor,
                        borderRadius: BorderRadius.circular(8.0)),
                    child: Text(
                      date.day.toString(),
                      style: TextStyle(color: Colors.white),
                    )),
                todayDayBuilder: (context, date, events) => Container(
                    margin: const EdgeInsets.all(5.0),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.circular(8.0)),
                    child: Text(
                      date.day.toString(),
                      style: TextStyle(color: Colors.white),
                    )),
              ),
              calendarController: _controller,
            )
          ],
        ),
      ),
    );
  }
}

Output

 

 

Flutter Dynamic theme change using getX | Dark & Light mode

0
change flutter theme dynamically using getx library
change flutter theme dynamically using getx library

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will create a app where user can select his desired theme either dark theme in flutter or light theme in flutter.

VIDEO TUTORIAL

Flutter Dynamic theme change using getX

Step 1 : Create a new Flutter project

Start your favorite IDE, In my case i am making user of ANDROID STUDIO to build Flutter project, you may use as per your choice.

Create a new Flutter project
IDE -> Files -> New > New Flutter Project -> give name -> give package name and finish

Step 2: Add GetX & Get Storage dependencies

Then, once your flutter project is been created, you need to add 2 required dependencies i.e. GetX  & Get Storage in pubspec.yaml

adding depencencies in flutter getx get storage
adding depencencies in flutter getx get storage

Step 3 : Adding images in Flutter project

create a package/folder in your flutter project structure, Right click on project -> New -> Directory (give name) and add image files in that folder.

After creating the directory you need to specify the path of the directory you have created in pubspec.yaml file so that your flutter project can access the images.

You can see in below screenshot, i have created folder by name images which has 2 images in it, and then in pubspec.yaml file i have gave the image path in flutter.

flutter image, assets path

Step 4: The Code

If you face problem in understand below code, learn basic of Getx and Get Storage (link is below)

void main() async{
  await GetStorage.init();  // before building the app  you need to initialize GetStorage  // so that we have access to use app data
  runApp(MyApp());
}

Then, Create a instance of GetStorage class

final appdata = GetStorage();  // instance of GetStorage

Now, using instance create a key-value pair

appdata.writeIfNull('darkmode', false);

as you see above, ‘darkmode’ is a key and false is value stored in it.

bool isDarkMode = appdata.read('darkmode');  //  get data from get storage and store in a boolean variable

This isDarkMode will store either true or false, If true then it means, user have previously turned on dark mode before closing the app.

and depending on isDarkMode, we will set the theme of the app either dark mode or light mode.

A Switch Widget to turn on/off dark mode dynamically in flutter

Switch(
                    value: isDarkMode ,
                    onChanged: (value) => appdata.write('darkmode', value),
      )

Complete Flutter code main.dart

This complete code will be posted on github repository, you may download it from there (link below)

import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:get/get.dart';

void main() async{
  await GetStorage.init();  // before building the app  you need to initialize GetStorage
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  final appdata = GetStorage();  // instance of GetStorage

  @override
  Widget build(BuildContext context) {

    appdata.writeIfNull('darkmode', false);
    return SimpleBuilder(
      builder: (_)
      {
        bool isDarkMode = appdata.read('darkmode');
        return GetMaterialApp(
          theme: isDarkMode ? ThemeData.dark() : ThemeData.light(),
          home: Scaffold(
            appBar: AppBar(title: Text("Getx Dynamic theme change"),),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(isDarkMode ? 'images/night.png' :'images/day.png' ,width: 100,height: 100,),
                  Switch(
                    value: isDarkMode ,
                    onChanged: (value) => appdata.write('darkmode', value),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

To make it easy i am making user of Getx & Get Storage package https://pub.dev/packages/get_storage/

Watch this video to learn basic of Get Storage and Getx Basic : https://www.youtube.com/watch?v=L7Zs4yuStsw&t=1s

Keep user logged in into the app :

https://youtu.be/ViXfhl4dA3w

clone project on github https://github.com/RajatPalankar8/flutter_dynamic_theme_change.git

Comment below for any queries

😀 Follow and support me:

🐦 Twitter: https://twitter.com/rajatpalankar
💬 Facebook: https://www.facebook.com/protocoderspoint/
💸 Instagram: https://www.instagram.com/protocoderspoint/

Be sure to ask for help in the comments if you need any. Suggestions for future Flutter tutorials are also very welcome! 🙂 For mobile application development keep learning freely from proto coders point Visit: https://protocoderspoint.com/

Flutter map string dynamic example – Map in Flutter

0
Flutter map string dynamic example
Flutter map string dynamic example

Hi Guys, Welcome to Proto Coders Point, In this Article we will learn about map in dart programming language.

Dart Map

In Dart or any other programming language, A Map Object is a key-value pair to store string or any dynamic data.
Here, In dart map, A key & value can be of any datatype, It  means that we can store any data type because a map in dart language is a dynamic collection of data/information.

In Flutter Dart, A map can be declared in 2 ways : –

  • Using Map Literals.
  • Using Map Constructor.

Declaring a map using Map Literals

To declare a map in dart you need to enclose the key-value pair in a curly bracket “{}”

Syntax
var identifier = { ‘key1′:’value1’ , ‘key2′:’value2’ , ‘key3′:’value3’,  …….. };

Example

var usrMap = {"name": "Proto Coders Point ", 'Website': 'https://protocoderspoint.com/'}; 
   
print(usrMap);

output

map literal example

To get/print particular key value then you can do it like this print ( usrMap[‘name’] ) this will print the value = Proto Coders Point.

Declartion of Map using Map Construtor

Using map constructor, A Map can be declared in 2 steps:

  • Declare Map using it constructor
  • Initilalize the map

Syntax

var identifier = new Map();

then, to initialize to maps with some key-value

identifier[key] = value

Example

void main() { 
  
var logincred = new Map();
  
  logincred['username']='admin';
  logincred['password']='admin@12334#';
  
  print(logincred);

}

output

map constructor example

Properties of Map in dart

So, to us map you need to import dart.core package

  1. Keys : This will return all the key in map object.
  2. Values : Wiil return all the value in map object.
  3. length : Return the number of key-value pair length/size.
  4. isEmpty : Will return true if Map object is empty.
  5. IsNotEmpty : Will return true if map value is not empty.

Function of Map dart

There are some comman task performed with Map in dart:

  1. addAll() : Used to add all key-value of some other Map Object.
  2. clean() : Remove all data from pair.
  3. remove() : Remove Specific date of key.
  4. foreach : used to iterate and read alll map entires.

addAdd() :  Example

void main() { 
  
 var usrMap = {"name": "Proto Coders Point ", 'Website': 'https://protocoderspoint.com/'}; 
  
  
  var map2 = {'email': 'protocoders.come'};
  
  usrMap.addAll(map2);
  
  print(usrMap);


}

output

map add All

remove() : Example

Removes Specific data of key – values from map data, it accept a key which is  needed to be removed.

void main() { 
  
Map m  = { 'id': 01 ,'name': 'Rajat'};

  print("Before removing : ${m}");
  
  dynamic res = m.remove('name'); // here name is the key.
  
  print("removed data is : ${res}");
  
  
  print("After removing ${m}");

}

output

map remove function

foreach : Example

By using foreach function in Map you can easily iterate and read all the maps entries.

Syntax :  Map.forEach(void f(K key , V value));

void main() { 
  
var userdata = { 'name': 'Proto Coders Point', 'Website': 'https://protocoderspoint.com/'};
  
  userdata.forEach((k,v){
    print('  ${k} ${v}');
  });

}

output

Recommended Article

Dart data types – variable in dart

Flutter array array in flutter

Dropdown in flutter

List in dart – convert list to set or vice versa