Tuesday, April 25, 2023

Android - Read and Write to internal or external storage

 public static final String favFile = "favlist.txt";


private void getOrCreateFavFile() {

        File fFile = new File(getFilesDir(), favFile);

        if (!fFile.isFile()){

            if(!isWriteTextFileToInternalStorage(favFile,"")) {

                Toast.makeText(this, R.string.ERROR_FILE_CREATE, Toast.LENGTH_LONG).show();

                finish();

            } else

            {

                Toast.makeText(this, "File created", Toast.LENGTH_LONG).show();

            }

        } else {

            //favList = getListFromTextFile(favFile);

            favList = getTextFileData(favFile);

        }

    }

private boolean isWriteTextFileToExternalStorage(String FILENAME, String CONTENT_TXT) {

        try {

            File myFile = new File("/sdcard/" + FILENAME);

            myFile.createNewFile();

            FileOutputStream fOut = new FileOutputStream(myFile);

            OutputStreamWriter myOutWriter =

                    new OutputStreamWriter(fOut);

            myOutWriter.append(CONTENT_TXT);

            myOutWriter.close();

            fOut.close();

            Toast.makeText(getBaseContext(),

                    "Done writing SD 'favFile.txt'",

                    Toast.LENGTH_SHORT).show();

            return true;

        } catch (Exception e) {

            Toast.makeText(getBaseContext(), e.getMessage(),

                    Toast.LENGTH_SHORT).show();

        }

        return false;

    }



private boolean isWriteTextFileToInternalStorage(String FILENAME, String CONTENT_TXT) {

        FileOutputStream fos = null;

        Boolean lResult=false;


        try {

            fos = openFileOutput(FILENAME, MODE_PRIVATE);

            fos.write(CONTENT_TXT.getBytes());

            // Toast.makeText(this,"Save to " + getFilesDir() + "/" + FILENAME, Toast.LENGTH_LONG).show();

            lResult = true;


        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (fos != null) {

                try {

                    fos.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        return lResult;

    }


public  List<Song>  getTextFileData(String fileName) {

        List<Song> songs = new ArrayList<>();

        StringBuilder text = new StringBuilder();

        try {

            FileInputStream fIS = getApplicationContext().openFileInput(fileName);

            InputStreamReader isr = new InputStreamReader(fIS, StandardCharsets.UTF_8);

            BufferedReader br = new BufferedReader(isr);


            String line;


            while ((line = br.readLine()) != null) {

                text.append(line).append('\n');

                String Filepath = new File(new URI(line).getPath()).getCanonicalPath();

                songs.add(SongProvider.retrieveSongByPath(this,Filepath));

            }

            br.close();

        } catch (IOException | URISyntaxException e) {

            Log.e("Error!", "Error occured while reading text file from Internal Storage!");


        }

        return songs;

    }


private List<Song> getListFromTextFile(String FILENAME){

        List<Song> songs = new ArrayList<>();


        FileInputStream fis = null;

        try {

            fis = openFileInput(FILENAME);

            InputStreamReader isr = new InputStreamReader(fis);

            BufferedReader br = new BufferedReader(isr);

            StringBuilder sb = new StringBuilder();

            String textLine = br.readLine();

            while (textLine != null) {

                sb.append(textLine).append("\n"); // all text

                //Uri songUri = Uri.parse(textLine);

                String Filepath = new File(new URI(textLine).getPath()).getCanonicalPath();

                songs.add(SongProvider.retrieveSongByPath(this,Filepath));

            }

           // Toast.makeText(this,sb.toString(), Toast.LENGTH_LONG).show();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (URISyntaxException e) {

            e.printStackTrace();

        } finally {

            if (fis != null) {

                try {

                    fis.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        return songs;

    }



private void SaveListToTextFile() {

        if (isWriteTextFileToInternalStorage(favFile,false,"")) {

            for(int i=0; i<favList.size();i++) {

                final Song favSong = favList.get(i);

                if (!isWriteTextFileToInternalStorage(favFile,true,favSong.path + "\n")) {

                    //Toast.makeText(this,favSong.path, Toast.LENGTH_LONG).show();

                    return;

                }

            }

        }

        if(favList.size()>0) {

            String data =  getTextFileData(favFile);

            songLyrics.setText(data);

        }

    }



public String getTextFileData(String fileName) {

        StringBuilder text = new StringBuilder();

        try {

            FileInputStream fIS = getApplicationContext().openFileInput(fileName);

            InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");

            BufferedReader br = new BufferedReader(isr);


            String line;


            while ((line = br.readLine()) != null) {

                text.append(line + '\n');

            }

            br.close();

        } catch (IOException e) {

            Log.e("Error!", "Error occured while reading text file from Internal Storage!");


        }


        return text.toString();

    }



private boolean isWriteTextFileToInternalStorage(String FILENAME, Boolean isAppend, String CONTENT_TXT ) {

        FileOutputStream fos = null;

        Boolean lResult=false;


        try {

            if(isAppend) {

                fos = openFileOutput(FILENAME, MODE_APPEND);

            } else  {

                fos = openFileOutput(FILENAME, MODE_PRIVATE);

            }

            fos.write(CONTENT_TXT.getBytes());

           // Toast.makeText(this,"Save to " + getFilesDir() + "/" + FILENAME, Toast.LENGTH_LONG).show();

            lResult = true;


        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (fos != null) {

                try {

                    fos.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        return lResult;

    }



    /* DOWNLOAD PROCEDURES

    Async Task to read textfile from url and save to internal storage... */

    private class GetTextFileFromServer extends AsyncTask<String, Void, Void> {

        String lineTextHolder,allTextHolder = null, finalContents = "";


        @Override

        protected void onPreExecute() {

            super.onPreExecute();

        }

        @Override

        protected Void doInBackground(String... params) {

            String TextFileURL = params[0]; // Get Path from params

            finalContents = "";

            try {

                URL url = new URL(TextFileURL);

                BufferedReader bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));

                while ((lineTextHolder = bufferReader.readLine()) != null) {

                     allTextHolder += lineTextHolder + "\n";

                }

                bufferReader.close();


            } catch (MalformedURLException malformedURLException) {

                // TODO Auto-generated catch block

                malformedURLException.printStackTrace();


            } catch (IOException iOException) {

                // TODO Auto-generated catch block

                iOException.printStackTrace();

            } finally {

                finalContents = allTextHolder;

            }

            return null;

        }

        @Override

        protected void onPostExecute(Void result) {

            super.onPostExecute(result);

            writeFileExternalStorage(finalContents);

            songLyrics.setText(finalContents);

        }

    }


    private String getOreadTextFile(File FILE_NAME) {

        if(FILE_NAME.isFile()){

            StringBuilder finalContents = new StringBuilder();

            try {

                BufferedReader br = new BufferedReader(new FileReader(FILE_NAME));

                String lineTextHolder;

                int currentLine = 0;

                while ((lineTextHolder = br.readLine()) != null){

                    currentLine++;

                    String s;

                    if(isOdd(currentLine)) {

                        s = "<font color='##000000'>" + lineTextHolder + "</font>" + "<br>";

                    } else {

                        s = "<font color='#1B5E20'>" + lineTextHolder + "</font>" + "<br>";

                    }

                    finalContents.append(s);

                }

                for(int i=0; i<6;i++) {

                    finalContents.append('\n');

                }

                br.close();

            } catch (IOException e) {

                e.printStackTrace();

                finalContents = new StringBuilder();

            }

            return finalContents.toString();

        }

        return "";

    }


    public void writeFileExternalStorage(String finalContents) {

        FileOutputStream outputStream = null;

        try {

            currentTextFilePath.createNewFile();

            //second argument of FileOutputStream constructor indicates whether to append or create new file if one exists

            outputStream = new FileOutputStream(currentTextFilePath, true);

            outputStream.write(finalContents.getBytes());

            outputStream.flush();

            outputStream.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }



private String GetAssetTextFile(String FILE_NAME){

        BufferedReader reader;

        StringBuilder finalContents = new StringBuilder();

        try{

            final InputStream file = getAssets().open(FILE_NAME);

            reader = new BufferedReader(new InputStreamReader(file));

            String lineTextHolder = reader.readLine();

            int currentLine = 0;

            while(lineTextHolder != null){

                currentLine++;

                String s;

                if(isOdd(currentLine)) {

                    s = "<font color='##000000'>" + lineTextHolder + "</font>" + "<br>";

                } else {

                    s = "<font color='#1B5E20'>" + lineTextHolder + "</font>" + "<br>";

                }


                finalContents.append(s).append("\n");;


                lineTextHolder = reader.readLine();

            }

        } catch(IOException ioe){

            ioe.printStackTrace();

            finalContents = new StringBuilder();

        }

        if(finalContents.toString().isEmpty()) finalContents.append("lyrics not found.");

        return finalContents.toString();

    }



 private void showLyrics(){

        imageDisk.setVisibility(INVISIBLE);

        Linear_Resize.setVisibility(VISIBLE);

        scrollView.setBackgroundColor(Color.WHITE);

        songLyrics.setVisibility(VISIBLE);

        songLyrics.setTextColor(Color.BLACK);


        String sl = getOreadTextFile(currentTextFilePath);

        if(sl.isEmpty()){

            sl = GetAssetTextFile( "SongAndLyrics/" + currentTitle + ".txt");

        }

        songLyrics.setText(Html.fromHtml(sl));

    }


    boolean isOdd( int val ) { return (val & 0x01) != 0; }


    private void hideLyrics(){

        imageDisk.setVisibility(VISIBLE);

        songLyrics.setVisibility(INVISIBLE);

        scrollView.setBackgroundColor(Color.TRANSPARENT);

        Linear_Resize.setVisibility(INVISIBLE);

    }


Monday, April 24, 2023

Android - Get String Contents from URL

    public static  ArrayList<String>  getTextFromWeb(String urlString)

    {

        ArrayList<String> contents=new ArrayList<String>();


        try

        {

            URL feedUrl = new URL(urlString);

            HttpURLConnection conn=(HttpURLConnection) feedUrl.openConnection();

            //conn.setConnectTimeout(60000); // timing out in a minute


            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));


            //t=(TextView)findViewById(R.id.TextView1);

            String str;

            while ((str = in.readLine()) != null) {

                contents.add(str);

            }

            in.close();


            return contents; // return whatever you need

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }


        return null;

    }

Tuesday, April 18, 2023

Android Storage Permission

package com.dexcoding.myapplication;


import android.Manifest;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.os.Bundle;

import android.view.Window;

import android.view.WindowManager;


import androidx.core.app.ActivityCompat;

import androidx.core.content.ContextCompat;



@SuppressLint("CustomSplashScreen")

public class SplashActivity extends Activity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Hide title and nav bar, must be done before setContentView.

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        getWindow()

                .setFlags(

                        WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


        setContentView(R.layout.activity_splash);

    }


    private void gotoNextActivity(){

        Intent intent = new Intent(SplashActivity.this, MainActivity.class);

        startActivity(intent);

        finish();

    }


    public void checkStoragePermission() {

        int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);

        if (result == PackageManager.PERMISSION_GRANTED) {

            gotoNextActivity();

        } else

        {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        }

    }



    // Events ************************************************************************

    @Override

    protected void onResume() {

        checkStoragePermission();

        super.onResume();

    }

}

Simple way to use postDelayed() correctly in Android Studio


final Handler handler = new Handler();

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Write whatever to want to do after delay specified (1 sec)
        Log.d("Handler", "Running Handler");
    }
}, 1000);

How to find the Android version of a project in Android Studio?

//https://stackoverflow.com/questions/19465049/changing-api-level-android-studio


Changing API level Android Studio


When you want to update your minSdkVersion in an existing Android project...


Update build.gradle (Module: YourProject) under Gradle Script and

make sure that it is NOT build.gradle (Project: YourProject.app).


An example of build.gradle:


apply plugin: 'com.android.application'


android {

    compileSdkVersion 28

    buildToolsVersion "28.0.2"


    defaultConfig {

        applicationId "com.stackoverflow.answer"

        minSdkVersion 21

        targetSdkVersion 28

        versionCode 1

        versionName "1.0"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

    }

}


dependencies {

    androidTestCompile 'junit:junit:4.12'

    compile fileTree(dir: 'libs', include: ['*.jar'])

}


Rebuild project

After updating the build.gradle's minSdkVersion, you have to click on the button to sync gradle file ("Sync Project with Gradle files"). That will clear the marker.


Updating manifest.xml, for e.g. deleting any references to SDK levels in the manifest file, is NOT necessary anymore in Android Studio.

Thursday, November 3, 2022

Meta tags for a blogger (SEO)

 <!--- meta tags for my blog-->


<!---- Title Tag Optimization------>

<b:if cond='data:blog.pageType == &quot;item&quot;'>

<title><data:blog.pageName/> | <data:blog.title/></title>

<b:else/>

<title>Your Blog Title</title> 

</b:if>

<!---- End Of Title Tag Optimization------>


 <meta content='Your Blog Description' name='description'/>

 <meta content='Keyword-1,Keyword-2,Keyword-3' name='keywords'/>

 <meta content='index, follow' name='robots'/>

 <meta content='Author Name' name='Author'/>

 <meta content='Author Email Address' name='Email'/>

 <meta content='Language Name' name='language'/>

 <meta content='Country Name' name='country'/>

 <meta content='blogger' name='generator'/>


<!--- End of meta tags for my blog-->


Thursday, October 27, 2022

How To Rename/Change Package Name In Android Studio

How To Rename/Change Package Name In Android Studio

Steps by Step

Step 1: First make sure you are viewing the project in Android view. For that follow the below image to change from project to Android view in Android Studio:

Step 2: Now click on setting gear icon and deselect Compact Empty Middle Package

Step 3: Now you will see each package folder is broken into parts]\

Step 4: Now right click on the first package folder, refactor and rename. Now a warning will be displayed but you go ahead and click Rename Package. After that enter your domain name for the package name.

Step 5: Now in the bottom of Android Studio it will display ‘Find Refactoring Preview’. Here click on ‘Do Refactor’

Step 6: Now it has change the package domain name of the App. Now go ahead, change the domain extension and App folder name according to your requirement:

Step 6: Now it has change the package domain name of the App. Now go ahead, change the domain extension and App folder name according to your requirement: