am_dot_com

DDM 20210107

Jan 7th, 2021 (edited)
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.94 KB | None | 0 0
  1. public String saveBitmapToImageFile(
  2.             Bitmap pBitmap,
  3.             String pFilename
  4.     ){
  5.         try{
  6.             FileOutputStream fos = new FileOutputStream(
  7.                     pFilename
  8.             );
  9.  
  10.             if (fos!=null){
  11.                 /*
  12.                 Write a compressed version of the bitmap to the specified outputstream.
  13.                 If this returns true,
  14.                 the bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream().
  15.                 Note: not all Formats support all bitmap configs directly,
  16.                 so it is possible that the returned bitmap from BitmapFactory could be in a different bitdepth,
  17.                 and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels).
  18.                  */
  19.                 Boolean bAbleToRepresentBitmapAsRequested = pBitmap.compress(
  20.                         Bitmap.CompressFormat.PNG,
  21.                         100,
  22.                         fos
  23.                 );
  24.                 if (bAbleToRepresentBitmapAsRequested){
  25.                     return pFilename;
  26.                 }
  27.             }//if
  28.         }//try
  29.         //if an Exception does occur it is probably "FileNotFoundException"
  30.         catch (Exception e){
  31.             //probably: java.io.FileNotFoundException: test.png (Read-only file system)
  32.             Log.e("BOINK!", e.toString());
  33.         }//catch
  34.         return ""; //could not save file
  35.     }//saveBitmapToImageFile
  36.  
  37. //---
  38.  
  39. <?xml version="1.0" encoding="utf-8"?>
  40. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  41.     xmlns:app="http://schemas.android.com/apk/res-auto"
  42.     xmlns:tools="http://schemas.android.com/tools"
  43.     android:layout_width="match_parent"
  44.     android:layout_height="match_parent"
  45.     tools:context=".MainActivity">
  46.  
  47.     <ImageView
  48.         app:layout_constraintTop_toTopOf="parent"
  49.         android:id="@+id/idIvCapturedImage"
  50.         android:layout_width="match_parent"
  51.         android:layout_height="wrap_content"/>
  52.  
  53.     <!-- Text captured: -->
  54.     <TextView
  55.         android:gravity="center_horizontal"
  56.         android:text="@string/strTvAbout"
  57.         android:id="@+id/idTvAbout"
  58.         app:layout_constraintTop_toBottomOf="@id/idIvCapturedImage"
  59.         android:layout_width="match_parent"
  60.         android:layout_height="wrap_content"></TextView>
  61.  
  62.     <!-- the exact text that was shared from an external app will
  63.     show here -->
  64.     <TextView
  65.         android:id="@+id/idTvCapturedText"
  66.         app:layout_constraintLeft_toLeftOf="parent"
  67.         app:layout_constraintTop_toBottomOf="@id/idTvAbout"
  68.         android:layout_width="wrap_content"
  69.         android:layout_height="wrap_content"/>
  70.  
  71.     <ListView
  72.         android:id="@+id/idLvRecords"
  73.         app:layout_constraintTop_toBottomOf="@id/idTvCapturedText"
  74.         android:layout_width="match_parent"
  75.         android:layout_height="wrap_content"></ListView>
  76.  
  77. </androidx.constraintlayout.widget.ConstraintLayout>
  78.  
  79. //
  80.  
  81. package com.joythis.android.textcapturer;
  82.  
  83. import androidx.appcompat.app.AppCompatActivity;
  84.  
  85. import android.content.Context;
  86. import android.content.Intent;
  87. import android.os.Bundle;
  88. import android.util.Log;
  89. import android.view.View;
  90. import android.widget.ArrayAdapter;
  91. import android.widget.ImageView;
  92. import android.widget.ListView;
  93. import android.widget.TextView;
  94. import android.widget.Toast;
  95.  
  96. import java.io.File;
  97. import java.io.FileInputStream;
  98. import java.io.FileOutputStream;
  99. import java.io.InputStreamReader;
  100. import java.io.OutputStreamWriter;
  101. import java.nio.charset.StandardCharsets;
  102. import java.util.ArrayList;
  103. import java.util.Calendar;
  104. import java.util.HashMap;
  105. import java.util.Map;
  106.  
  107. public class MainActivity extends AppCompatActivity {
  108.     Context mContext;
  109.     TextView mTvAbout, mTvCapturedText;
  110.     ImageView mIvCapturedImage;
  111.  
  112.     ArrayList<String> mAlRecords;
  113.     ArrayAdapter<String> mAd;
  114.     ListView mLvRecords;
  115.  
  116.     public final static String MY_TSV_DB = "SHARES.DB";
  117.  
  118.     @Override
  119.     protected void onCreate(Bundle savedInstanceState) {
  120.         super.onCreate(savedInstanceState);
  121.         setContentView(R.layout.activity_main);
  122.  
  123.         init();
  124.     }//onCreate
  125.  
  126.     boolean qualityControl(
  127.         Object[] pCheckThese
  128.     ){
  129.         boolean bRet = true;
  130.         for (Object o : pCheckThese){
  131.             bRet = bRet && (o!=null);
  132.         }//for
  133.  
  134.         return bRet;
  135.     }//qualityControl
  136.  
  137.     Map<Object, Boolean> altQualityControl(
  138.         Object[] pCheckThese
  139.     ){
  140.         Map<Object, Boolean> aRet= new HashMap<>();
  141.         for (Object o : pCheckThese){
  142.             boolean bOk = o!=null;
  143.             aRet.put(o, bOk);
  144.         }//for
  145.         return aRet;
  146.     }//altQualityControl
  147.  
  148.     void init(){
  149.         mContext = this;
  150.         mTvAbout = findViewById(R.id.idTvAbout);
  151.         mTvCapturedText = findViewById(R.id.idTvCapturedText);
  152.         mIvCapturedImage = findViewById(R.id.idIvCapturedImage);
  153.  
  154.         mLvRecords = findViewById(R.id.idLvRecords);
  155.         mAlRecords = new ArrayList<>();
  156.         mAd = new ArrayAdapter<>(
  157.             mContext,
  158.             android.R.layout.simple_list_item_1,
  159.             mAlRecords //memory address for the data
  160.         );
  161.         mLvRecords.setAdapter(mAd);
  162.  
  163.         Object[] aRelevant = {mTvAbout, mTvCapturedText};
  164.         boolean bCanProceed = qualityControl(aRelevant);
  165.  
  166.         if (!bCanProceed){
  167.             Toast t = Toast.makeText(
  168.                 this,
  169.                 getString(R.string.strThereIsNullObject),
  170.                 Toast.LENGTH_LONG
  171.             );
  172.             return;
  173.         }//if
  174.  
  175.         mTvAbout.setText(
  176.             whereIsThePrivateInternalStorage()
  177.                 +"\nText Captured:"
  178.         );
  179.  
  180.         /*
  181.         TODO: avoid reprocessing the Intent on reexecutions of onCreate
  182.          */
  183.         checkIfCalledForSharingAndDisplayingSharedData();
  184.  
  185.         refresh();
  186.     }//init
  187.  
  188.     void checkIfCalledForSharingAndDisplayingSharedData(){
  189.         Intent intentHowWasICalled = getIntent();
  190.  
  191.         if (intentHowWasICalled!=null){
  192.             String strAction =
  193.                 intentHowWasICalled.getAction();
  194.  
  195.             //share
  196.             boolean bIWantToAnswer =
  197.             strAction.equals(Intent.ACTION_SEND);
  198.  
  199.             boolean bIWantToAnswer2 =
  200.             strAction.compareTo(Intent.ACTION_SEND)==0;
  201.  
  202.             boolean bIWantToAnswer3 =
  203.             strAction.compareToIgnoreCase(Intent.ACTION_SEND)==0;
  204.  
  205.             if (bIWantToAnswer){
  206.                 //it was a share!
  207.  
  208.                 String strType =
  209.                     intentHowWasICalled.getType();
  210.  
  211.                 Toast.makeText(
  212.                     mContext,
  213.                     strType,
  214.                     Toast.LENGTH_LONG
  215.                 ).show(); //"image/png" "image/jpeg"
  216.  
  217.                 boolean bIsText =
  218.                     strType.startsWith("text/");
  219.  
  220.                 boolean bIsImage =
  221.                     strType.startsWith("image/");
  222.  
  223.                 if (bIsText){
  224.                     String strTextThatWasShared =
  225.                     intentHowWasICalled.getStringExtra(
  226.                         Intent.EXTRA_TEXT
  227.                     );
  228.  
  229.                     insert(strTextThatWasShared); //record the received text
  230.                     refresh(); //shows the text
  231.  
  232.                     mTvCapturedText.setVisibility(View.GONE); //hides the TextView
  233.  
  234.                     //enough for principle demonstration
  235.                     mTvCapturedText.setText(
  236.                         strTextThatWasShared
  237.                     );
  238.                 }//if text was shared
  239.                 else
  240.                 if (bIsImage){
  241.                     //TODO?
  242.                 }
  243.             }//if the Activity was called from an ACTION_SEND Intent (e.g. Share from another app)
  244.         }//if got an Intent object with all the necessary data
  245.     }//checkIfCalledForSharingAndDisplaySharedText
  246.  
  247.     void refresh(){
  248.         /*
  249.         String strNewContent = readFile(MY_TSV_DB);
  250.         mTvCapturedText.setText(strNewContent);
  251.          */
  252.         //mAlRecords = new ArrayList<>(); //NO GO! would break the Adapter
  253.         mAlRecords.clear();
  254.  
  255.         //mAlRecords.addAll(readFile(MY_TSV_DB)); //original order
  256.         ArrayList<String> alTemp = readFile(MY_TSV_DB);
  257.         for (int idx=0; idx<alTemp.size(); idx++){
  258.             String strContent = alTemp.get(idx);
  259.             mAlRecords.add(0, strContent);
  260.         }//for
  261.  
  262.         mAd.notifyDataSetChanged();
  263.     }//refresh
  264.  
  265.     /*String*/ArrayList<String> readFile(
  266.         String pFileName
  267.     ){
  268.         String strContent =
  269.         readFromPrivateInternalStorage(pFileName);
  270.  
  271.         /*
  272.         somewhat useless while the app is not rewritten using
  273.         a true "Record" class data type
  274.         and a collection of Records is kept (for example in ArrayList<Record>)
  275.          */
  276.         ArrayList<String> aRet = new ArrayList<>();
  277.         String[] aRecords =
  278.             strContent.split("\n");
  279.         for(String record : aRecords){
  280.             String strAfterReplacement =
  281.             record.replace(
  282.                 "<br>", "\n"
  283.             );
  284.             aRet.add(strAfterReplacement);
  285.         }//for
  286.         return aRet;
  287.  
  288.         //return strContent;
  289.     }//readFile
  290.  
  291.     /*
  292.     will record with a TSV structure of our imagination
  293.     the data in a file, in the private internal storage of the app
  294.  
  295.     <when> \t <text> \n
  296.      */
  297.     void insert(String pStrWhatToInsert){
  298.         Calendar cal = Calendar.getInstance();
  299.         String strYMD = String.format(
  300.             "%d-%d-%d",
  301.             cal.get(Calendar.YEAR),
  302.             (cal.get(Calendar.MONTH)+1),
  303.             cal.get(Calendar.DAY_OF_MONTH)
  304.         );
  305.  
  306.         //replace the TSV reserved-symbols for innocuos alternatives
  307.         // \n -> "<br>" ; \t -> " "
  308.         String strAfterReplacement =
  309.             pStrWhatToInsert.replace(
  310.                 "\n",
  311.             "<br>"
  312.             );
  313.  
  314.         strAfterReplacement =
  315.             pStrWhatToInsert.replace(
  316.                 "\t",
  317.                 " "
  318.             );
  319.  
  320.         String strRecord = String.format(
  321.             "%s\t%s\n",
  322.             strYMD,
  323.             strAfterReplacement
  324.         );
  325.  
  326.         Boolean bOK =
  327.             writeToPrivateInternalStorage(
  328.                 MY_TSV_DB,
  329.                 //pStrWhatToInsert+"\n",
  330.                 strRecord,
  331.                 MODE_APPEND
  332.             );
  333.  
  334.         if (bOK){
  335.             Toast t = Toast.makeText(
  336.                 mContext,
  337.                 "New record added to TSV DB",
  338.                 Toast.LENGTH_LONG
  339.             );
  340.             t.show();
  341.         }//if
  342.     }//insert
  343.  
  344.     /*
  345.     to read and write in the Private Internal Storage
  346.     we need tools for dumping and recovering text from
  347.     that exclusive non-volatile file-system area
  348.      */
  349.  
  350.     String whereIsThePrivateInternalStorage(){
  351.         File pis = this.getFilesDir();
  352.         return pis.getAbsolutePath();
  353.     }//whereIsThePrivateInternalStorage
  354.  
  355.     Boolean writeToPrivateInternalStorage(
  356.         String pFileName,
  357.         String pFileContent,
  358.         int pWriteMode //PRIVATE (destructive) / APPEND (cumulative)
  359.     ){
  360.         try {
  361.             FileOutputStream fos = openFileOutput(
  362.                 pFileName,
  363.                 //MODE_APPEND
  364.                 pWriteMode
  365.             );
  366.  
  367.             if (fos!=null){
  368.                 OutputStreamWriter osw = new OutputStreamWriter(
  369.                     fos,
  370.                     StandardCharsets.UTF_8
  371.                 );
  372.                 if (osw!=null){
  373.                     osw.write(pFileContent);
  374.                     osw.close();
  375.                     fos.close();
  376.                     return true;
  377.                 }//if
  378.             }//if
  379.         }//try
  380.         catch (Exception e){
  381.             Log.e(
  382.                 getClass().getName(),
  383.                 e.toString()
  384.             );
  385.         }//catch
  386.         return false;
  387.     }//writeToPrivateInternalStorage
  388.  
  389.     String readFromPrivateInternalStorage(
  390.         String pFileName
  391.     ){
  392.         try{
  393.             FileInputStream fis = this.openFileInput(pFileName);
  394.             if (fis!=null){
  395.                 InputStreamReader isr = new InputStreamReader(
  396.                     fis,
  397.                     StandardCharsets.UTF_8
  398.                 );
  399.  
  400.                 if (isr!=null){
  401.                     int i; char c; String strAll="";
  402.                     while ((i=isr.read())!=-1){
  403.                         c = (char) i;
  404.                         strAll+=c;
  405.                     }//while
  406.                     isr.close();
  407.                     fis.close();
  408.  
  409.                     return strAll;
  410.                 }//if
  411.             }//if
  412.         }//try
  413.         catch(Exception e){
  414.             Log.e(
  415.                 getClass().getName(),
  416.                 e.toString()
  417.             );
  418.         }//catch
  419.  
  420.         return "";
  421.     }//readFromPrivateInternalStorage
  422. }//MainActivity
Add Comment
Please, Sign In to add comment