Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?xml version="1.0" encoding="utf-8"?>
- <menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item
- android:id="@+id/idMenuItemExampleLoadImageFromUrl"
- android:title="@string/strMenuItemExampleLoadImageFromUrl"></item>
- </menu>
- //attaches the menu to the Activity
- @Override
- public boolean onCreateOptionsMenu(Menu pMenu) {
- MenuInflater minf = getMenuInflater();
- minf.inflate(
- R.menu.my_menu,
- pMenu
- );
- return super.onCreateOptionsMenu(pMenu);
- }//onCreateOptionsMenu
- //code the behavior of each menu item
- @Override
- public boolean onOptionsItemSelected(
- @NonNull MenuItem pItem
- )
- {
- switch(pItem.getItemId()){
- case R.id.idMenuItemExampleLoadImageFromUrl:
- break;
- }//switch
- return super.onOptionsItemSelected(pItem);
- }//onOptionsItemSelected
- ////////
- package com.joythis.android.textcapturer;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.util.Log;
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import javax.net.ssl.HttpsURLConnection;
- /**
- * Created by Artur Marques on 2018.
- */
- public class AmIoHttp {
- public static String io_https_ReadAll(
- String pUrl
- ){
- String ret="";
- HttpURLConnection urlConnection = null;
- try {
- URL url = new URL(pUrl);
- urlConnection = (HttpsURLConnection) url.openConnection();
- InputStream in = urlConnection.getInputStream();
- InputStreamReader isr = new InputStreamReader(in);
- BufferedReader br = new BufferedReader(isr);
- String strLine = "";
- while ((strLine = br.readLine())!=null){
- ret+=strLine;
- }
- br.close();
- isr.close();
- in.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally //The finally block always executes when the try block exits
- {
- if (urlConnection != null) {
- urlConnection.disconnect();
- }//if
- }//finally
- return ret;
- }//io_https_ReadAll
- public static String io_http_ReadAll(
- String pUrl
- ){
- String ret="";
- HttpURLConnection urlConnection = null;
- try {
- URL url = new URL(pUrl);
- urlConnection = (HttpURLConnection) url.openConnection();
- InputStream in = urlConnection.getInputStream();
- InputStreamReader isr = new InputStreamReader(in);
- BufferedReader br = new BufferedReader(isr);
- String strLine = "";
- while ((strLine = br.readLine())!=null){
- ret+=strLine;
- }
- br.close();
- isr.close();
- in.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally //The finally block always executes when the try block exits
- {
- if (urlConnection != null) {
- urlConnection.disconnect();
- }//if
- }//finally
- return ret;
- }//io_http_ReadAll
- public final static String TAG = "@AmIoHttp";
- public static Bitmap readBitmapFromUrl(
- String pUrl
- ){
- Bitmap ret = null;
- try{
- URL url = new URL(pUrl);
- InputStream is = url.openStream();
- ret = BitmapFactory.decodeStream(is);
- is.close();
- }
- catch (Exception e){
- Log.e(
- TAG,
- e.getMessage()
- );
- }
- return ret;
- }//readBitmapFromUrl
- }//AmIoHttp
- //
- package com.joythis.android.textcapturer;
- import android.app.Activity;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.util.Log;
- import android.view.ViewGroup;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.LinearLayout;
- import android.widget.Spinner;
- import android.widget.Toast;
- import androidx.core.content.ContextCompat;
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.nio.charset.StandardCharsets;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
- import javax.net.ssl.HttpsURLConnection;
- public class AmUtil {
- public final static String E_EMPTY_STRING =
- "cannot parse an empty string";
- public final static String E_CANNOT_PARSE_INT_FROM_STRING =
- "cannot parse int from existing string";
- public final static String E_NO_EDITTEXT =
- "null EditText is not parseable";
- public final static String TAG_AM_UTIL = "@AmUtil";
- Activity mActivity;
- public AmUtil(Activity pA){
- this.mActivity = pA;
- }//AmUtil
- public void fb(
- String pStrMsg
- ){
- Toast t = Toast.makeText(
- this.mActivity,
- pStrMsg,
- Toast.LENGTH_LONG
- );
- t.show();
- }//fb
- /*
- public void phoneTo(
- String pStrPhoneNumber
- ){
- try {
- Uri uriForPhoneNumber = Uri.parse("tel:" + pStrPhoneNumber);
- Intent intentForMakingThePhoneCall =
- new Intent(
- Intent.ACTION_CALL
- );
- intentForMakingThePhoneCall.setData(
- uriForPhoneNumber
- );
- boolean bUserAuthorizedTheAppToMakePhoneCalls =
- ContextCompat.checkSelfPermission(
- mActivity,
- Manifest.permission.CALL_PHONE
- ) == PackageManager.PERMISSION_GRANTED;
- if (bUserAuthorizedTheAppToMakePhoneCalls) {
- this.mActivity.startActivity(
- intentForMakingThePhoneCall
- );
- }
- else{
- boolean bUserAcceptsExplanationsOnWhyThePermissionIsImportant =
- mActivity.shouldShowRequestPermissionRationale(
- Manifest.permission.CALL_PHONE
- );
- if (bUserAcceptsExplanationsOnWhyThePermissionIsImportant){
- fb("Without this permission, the app can NOT make phone calls.");
- }
- }
- }//try
- catch(Exception e){
- Log.e(
- getClass().getName(),
- e.toString()
- );
- }//catch
- }//phoneTo
- */
- public Map<Integer, ArrayList<String>>
- identifyPermissionsGrantedAndDenied(
- String[] paNecessaryPermissions
- )
- {
- Map<Integer, ArrayList<String>> retMap = new HashMap<>();
- ArrayList<String> alGranted = new ArrayList<>();
- ArrayList<String> alDenied = new ArrayList<>();
- for (String permission : paNecessaryPermissions){
- boolean bGranted =
- ContextCompat.checkSelfPermission(
- mActivity,
- permission
- ) == PackageManager.PERMISSION_GRANTED;
- boolean bDenied =
- ContextCompat.checkSelfPermission(
- mActivity,
- permission
- ) == PackageManager.PERMISSION_DENIED;
- if (bGranted) alGranted.add(permission);
- if (bDenied) alDenied.add(permission);
- }//for
- retMap.put(/* Integer 0 */ PackageManager.PERMISSION_GRANTED, alGranted);
- retMap.put(/* Integer -1 */ PackageManager.PERMISSION_DENIED, alDenied);
- return retMap;
- }//identifyPermissionsGrantedAndDenied
- public void requestNecessaryPermissionsNotYetGranted(
- String[] paNecessaryPermissions,
- int piCallBackCodeForWhenTheUserResponds
- ){
- /*
- do not request permissions already granted
- */
- Map<Integer, ArrayList<String>> map =
- this.identifyPermissionsGrantedAndDenied
- (paNecessaryPermissions);
- ArrayList<String> alDenied = map.get(PackageManager.PERMISSION_DENIED);
- if(alDenied.size()>0){
- //convert from ArrayList<String> to String[]
- String[] aDenied = new String[alDenied.size()];
- alDenied.toArray(aDenied);
- this.mActivity.requestPermissions(
- //alDenied, //invalid syntax , because String[] is expected
- aDenied,
- piCallBackCodeForWhenTheUserResponds
- );
- }//if
- }//requestNecessaryPermissionsNotYetGranted
- /*
- receives a list of necessary permissions
- returns a String which states the status of each necessary permission
- */
- public String permissionsStatusToString(
- String[] paNecessaryPermissions
- ){
- String strRet = "";
- Map<Integer, ArrayList<String>> map =
- this.identifyPermissionsGrantedAndDenied(paNecessaryPermissions);
- ArrayList<String> alGranted =
- map.get(PackageManager.PERMISSION_GRANTED);
- ArrayList<String> alDenied =
- map.get(PackageManager.PERMISSION_DENIED);
- strRet+="GRANTED:\n";
- for(String spg : alGranted) strRet+=spg+"\n";
- strRet+="\n";
- strRet+="DENIED:\n";
- for(String spd : alDenied) strRet+=spd+"\n";
- return strRet;
- }//permissionsStatusToString
- public void populateSpinnerWithOptions(
- Spinner pSpn,
- String[] pOptions
- ){
- if (pSpn!=null && pOptions!=null && pOptions.length>0){
- ArrayAdapter<String> ad = new ArrayAdapter<>(
- this.mActivity,
- android.R.layout.simple_spinner_item,
- pOptions
- );
- ad.setDropDownViewResource(
- android.R.layout.simple_spinner_dropdown_item
- );
- pSpn.setAdapter(ad);
- ad.notifyDataSetChanged();
- }
- }
- public static String CalendarToString(
- Calendar pC
- ){
- String strRet = "";
- int year, month, day, hour, minutes, seconds;
- year = pC.get(Calendar.YEAR);
- month = pC.get(Calendar.MONTH)+1;
- day = pC.get(Calendar.DATE);
- hour = pC.get(Calendar.HOUR_OF_DAY);//CTRL^Q
- minutes = pC.get(Calendar.MINUTE);
- seconds = pC.get(Calendar.SECOND);
- String strYear, strMonth, strDay,
- strHour, strMinutes, strSeconds;
- strYear = String.valueOf(year);
- strMonth = AmUtil.addZeroIfNeededForHaving2Digits(month);
- strDay = AmUtil.addZeroIfNeededForHaving2Digits(day);
- strHour = AmUtil.addZeroIfNeededForHaving2Digits(hour);
- strMinutes = AmUtil.addZeroIfNeededForHaving2Digits(minutes);
- strSeconds = AmUtil.addZeroIfNeededForHaving2Digits(seconds);
- strRet = String.format(
- "%s-%s-%s %s:%s:%s",
- strYear,
- strMonth,
- strDay,
- strHour,
- strMinutes,
- strSeconds
- );
- return strRet;
- }//CalendarToString
- public static Calendar CalendarFromString(
- String pStrCalendar //Y-M-D hh:mm:ss
- ) throws Exception //consequence: use try{}catch{Exception e} at the caller
- {
- Calendar ret = Calendar.getInstance();
- ret.clear();
- int year, month, day, hour, minutes, seconds;
- //TODO: init year .. seconds
- String[] aCalendarParts = pStrCalendar.split(" ");
- boolean bCaution = aCalendarParts.length==2;
- if (bCaution){
- String strDate = aCalendarParts[0];
- String strTime = aCalendarParts[1];
- String[] aDateParts = strDate.split("-");
- String[] aTimeParts = strTime.split(":");
- boolean bSecondCaution = aDateParts.length==3 && aTimeParts.length==3;
- if (bSecondCaution){
- try {
- year = Integer.parseInt(aDateParts[0]);
- month = Integer.parseInt(aDateParts[1]);
- day = Integer.parseInt(aDateParts[2]);
- hour = Integer.parseInt(aTimeParts[0]);
- minutes = Integer.parseInt(aTimeParts[1]);
- seconds = Integer.parseInt(aTimeParts[2]);
- ret.set(Calendar.YEAR, year);
- ret.set(Calendar.MONTH, month-1);
- ret.set(Calendar.DATE, day);
- ret.set(Calendar.HOUR_OF_DAY, hour);
- ret.set(Calendar.MINUTE, minutes);
- ret.set(Calendar.SECOND, seconds);
- return ret;
- }//try
- catch(Exception e){
- //failure in extracting numbers from the date or the time
- String strError = e.getMessage().toString();
- Log.e(TAG_AM_UTIL, strError);
- }//catch
- }//if second caution
- }//if first caution
- String strError = "Could NOT parse Calendar string!";
- Log.e(TAG_AM_UTIL, strError);
- throw new Exception(strError);
- //return null; //never happens
- }//CalendarFromString
- public static int randomInt(
- int pMin,
- int pMax
- ){
- Random r = new Random();
- int iMax = Math.max(pMin, pMax);
- int iMin = Math.min(pMin, pMax);
- int iAmplitude = iMax-iMin+1;
- int iJump = r.nextInt(iAmplitude);
- int iDest = iMin+ iJump;
- return iDest;
- }//randomInt
- private static String
- addZeroIfNeededForHaving2Digits(
- int pSomeNumber
- )
- {
- if (pSomeNumber<10)
- return "0"+pSomeNumber;
- else
- return String.valueOf(pSomeNumber);
- }//addZeroIfNeededForHaving2Digits
- public static enum COMPARISON_TYPES {
- COMPARE_TYPE_EXACT_MATCH_CASE_SENSITIVE,
- COMPARE_TYPE_EXACT_MATCH_CASE_INSENSITIVE,
- COMPARE_TYPE_CONTAINS_CASE_SENSITIVE,
- COMPARE_TYPE_CONTAINS_CASE_INSENSITIVE,
- }
- public static int arrayStringContainsElement(
- String[] pA,
- String pE,
- COMPARISON_TYPES pComparisonType
- ){
- if (pA!=null){
- int iHowMany = pA.length;
- for (int idx=0; idx<iHowMany; idx++){
- String strCurrent = pA[idx];
- boolean bMatchCaseInsensitive = strCurrent.equalsIgnoreCase(pE);
- boolean bMatchCaseSensitive = strCurrent.equals(pE);
- boolean bMatchContainsCaseSensitive = strCurrent.indexOf(pE)!=-1;
- boolean bMatchContainsCaseInsensitive = strCurrent.toLowerCase().indexOf(pE.toLowerCase())!=-1;
- boolean bMatch = false;
- switch (pComparisonType){
- case COMPARE_TYPE_EXACT_MATCH_CASE_INSENSITIVE:
- bMatch = bMatchCaseInsensitive;
- break;
- case COMPARE_TYPE_EXACT_MATCH_CASE_SENSITIVE:
- bMatch = bMatchCaseSensitive;
- break;
- case COMPARE_TYPE_CONTAINS_CASE_SENSITIVE:
- bMatch = bMatchContainsCaseSensitive;
- break;
- case COMPARE_TYPE_CONTAINS_CASE_INSENSITIVE:
- bMatch = bMatchContainsCaseInsensitive;
- break;
- }//switch
- if (bMatch) return idx;
- }
- }
- return -1;
- }//arrayStringContainsElement
- public static Float readFloatFromEditText (EditText pEt) throws Exception {
- if (pEt!=null){
- String strEt = pEt.getText().toString().trim();
- try{
- float f = Float.parseFloat(strEt);
- return f;
- }
- catch (Exception e){
- throw (e);
- }
- }//if
- else{
- throw new Exception("No EditText");
- }//else
- }//readFloatFromEditText
- public static int readIntFromEt (
- EditText pEt
- ) throws Exception
- {
- if (pEt!=null){
- String strEt =
- pEt.getText().toString().trim();
- Boolean bEmptyString = strEt.isEmpty();
- if (bEmptyString){
- //cannot extract int from empty string
- throw new Exception (AmUtil.E_EMPTY_STRING);
- }//if
- else{
- try {
- int i = Integer.parseInt(strEt);
- return i;
- }//try
- catch (Exception e){
- throw new Exception
- (AmUtil.E_CANNOT_PARSE_INT_FROM_STRING);
- }//catch
- }//else
- }//if we have a valid EditText
- else{
- throw new Exception
- (AmUtil.E_NO_EDITTEXT);
- }//else
- }//readIntFromEt
- /*
- receives the name of a file, located in the "private internal storage"
- returns the entire text content of that file
- */
- public String genericPrivateInternalStorageFileReader(
- String pFileName
- ){
- String strAll = "";
- try{
- FileInputStream fis = mActivity.openFileInput(
- pFileName
- );
- if (fis!=null){
- InputStreamReader isr = new InputStreamReader(
- fis,
- StandardCharsets.UTF_8
- );
- char c; int i;
- final int END_OF_FILE = -1;
- while ((i=isr.read())!=END_OF_FILE){
- c = (char)i; //cast the byte to a char
- strAll+=c; //concatenate the char to the already read file contents
- }//while
- isr.close();
- }//if
- fis.close();
- }//try
- catch(Exception e){
- /*
- e.g. : file does not exist
- */
- Log.e(TAG_AM_UTIL, e.getMessage().toString());
- }//catch
- return strAll;
- }//genericPrivateInternalStorageFileReader
- /*
- receives a file name and the content, to be written into the "private internal storage"
- returns true on success, false on failure
- */
- public boolean genericPrivateInternalStorageFileWriter(
- String pFileName,
- String... pContent
- ){
- try {
- FileOutputStream fos =
- mActivity.openFileOutput(pFileName, Activity.MODE_PRIVATE);
- if (fos!=null){
- OutputStreamWriter osw = new OutputStreamWriter(
- fos,
- StandardCharsets.UTF_8
- );
- for (String strPartial : pContent){
- osw.write(strPartial);
- }//for
- osw.close();
- }//if
- fos.close();
- return true;
- }//try
- catch (Exception e){
- Log.e(TAG_AM_UTIL, e.getMessage().toString());
- return false;
- }//catch
- }//genericPrivateInternalStorageFileWriter
- /*
- receives the text for an about to be created new Button
- receives the already existing LinearLayout where the dyn created Button
- is to be added
- receives an already existing click listener to be assigned to the
- about to be created new Button
- */
- void createNewButtonInLinearLayout (
- String pStrButtonText, //text for the new Button
- LinearLayout pLayoutWhereToAddTheNewButton, //LL where to add the Button (can NOT be null)
- Button.OnClickListener pButtonClickHandler //object that handles the behavior for the new Button
- )
- {
- Button btnNewNumber = new Button(mActivity);
- btnNewNumber.setText(pStrButtonText);
- LinearLayout.LayoutParams wh = new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.MATCH_PARENT,
- ViewGroup.LayoutParams.WRAP_CONTENT
- );
- btnNewNumber.setLayoutParams(wh);
- btnNewNumber.setOnClickListener(pButtonClickHandler);
- pLayoutWhereToAddTheNewButton.addView(btnNewNumber);
- }//createNewButtonInLinearLayout
- public void actionQuit(){
- Intent intentQuitToMain = new Intent(Intent.ACTION_MAIN);
- intentQuitToMain.addCategory(Intent.CATEGORY_HOME);
- intentQuitToMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- mActivity.startActivity(intentQuitToMain);
- mActivity.finish();
- }//actionQuit
- public static String io_https_ReadAll(
- String pUrl
- ){
- String ret="";
- HttpURLConnection urlConnection = null;
- try {
- URL url = new URL(pUrl);
- urlConnection = (HttpsURLConnection) url.openConnection();
- InputStream in = urlConnection.getInputStream();
- InputStreamReader isr = new InputStreamReader(in);
- BufferedReader br = new BufferedReader(isr);
- /*
- //this would eliminate the new line separators
- String strLine = "";
- while ((strLine = br.readLine())!=null){
- ret+=strLine;
- }
- */
- int i;
- while((i=br.read())!=-1){
- char c = (char) i;
- ret+=c;
- }//while
- br.close();
- isr.close();
- in.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally //The finally block always executes when the try block exits
- {
- if (urlConnection != null) {
- urlConnection.disconnect();
- }//if
- }//finally
- return ret;
- }//io_https_ReadAll
- }//AmUtil
- //
- package com.joythis.android.textcapturer;
- import androidx.annotation.NonNull;
- import androidx.appcompat.app.AppCompatActivity;
- import android.content.Context;
- import android.content.Intent;
- import android.graphics.Bitmap;
- import android.net.Uri;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.Menu;
- import android.view.MenuInflater;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.ArrayAdapter;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.ListView;
- import android.widget.TextView;
- import android.widget.Toast;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.nio.charset.StandardCharsets;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.HashMap;
- import java.util.Map;
- public class MainActivity extends AppCompatActivity {
- Context mContext;
- TextView mTvAbout, mTvCapturedText;
- ImageView mIvCapturedImage;
- ArrayList<String> mAlRecords;
- ArrayAdapter<String> mAd;
- ListView mLvRecords;
- class MyTaskToReadRemoteImageAndDisplayItOnAnImageView
- extends AsyncTask<
- String, //because the argument required for the task to execute, is an URL (a string)
- Void, //because I will not be doing progress control
- Bitmap //because the result of whatever will happen in background is a Bitmap
- >
- {
- /*
- in "doInBackground" code whatever can NOT run in the main thread
- */
- @Override
- protected Bitmap doInBackground(String... strings) {
- String strUrl = strings[0];
- Bitmap bitmapThatCorrespondsToTheRemoteImage =
- AmIoHttp.readBitmapFromUrl(strUrl);
- return bitmapThatCorrespondsToTheRemoteImage;
- //return null;
- }//doInBackground
- /*
- code whatever you want to do AFTER the background code ends
- */
- @Override
- protected void onPostExecute(Bitmap bitmap) {
- mIvCapturedImage.setImageBitmap(bitmap);
- super.onPostExecute(bitmap);
- }//onPostExecute
- }//MyTaskToReadRemoteImageAndDisplayItOnAnImageView
- //attaches the menu to the Activity
- @Override
- public boolean onCreateOptionsMenu(Menu pMenu) {
- MenuInflater minf = getMenuInflater();
- minf.inflate(
- R.menu.my_menu,
- pMenu
- );
- return super.onCreateOptionsMenu(pMenu);
- }//onCreateOptionsMenu
- //code the behavior of each menu item
- /*
- code that processes the user interface, always runs in the "Main Thread"
- nothing more should run on the main thread
- above all, code that depends on external resources should NOT
- run directly in the main thread
- */
- @Override
- public boolean onOptionsItemSelected(
- @NonNull MenuItem pItem
- )
- {
- switch(pItem.getItemId()){
- case R.id.idMenuItemExampleLoadImageFromUrl:
- //https://arturmarques.com/edu/ddm/ddm.png
- String strTestUrl =
- "https://arturmarques.com/edu/ddm/ddm.png";
- //can NOT work because it would run on the main thread
- /*
- loadImageAtUrlToImageView(
- strTestUrl, //URL for some image
- mIvCapturedImage //an ImageView object
- );
- */
- //can work because it happens in its thread, asynchronously
- MyTaskToReadRemoteImageAndDisplayItOnAnImageView t = new
- MyTaskToReadRemoteImageAndDisplayItOnAnImageView();
- t.execute(strTestUrl);
- break;
- }//switch
- return super.onOptionsItemSelected(pItem);
- }//onOptionsItemSelected
- void loadImageAtUrlToImageView (
- String pUrl,
- ImageView pImageViewThatWillDisplayTheImageAtTheUrl
- ){
- Bitmap bitmap = AmIoHttp.readBitmapFromUrl(pUrl);
- pImageViewThatWillDisplayTheImageAtTheUrl.
- setImageBitmap(bitmap);
- }//loadImageAtUrlToImageView
- public final static String MY_TSV_DB = "SHARES.DB";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- init();
- }//onCreate
- boolean qualityControl(
- Object[] pCheckThese
- ){
- boolean bRet = true;
- for (Object o : pCheckThese){
- bRet = bRet && (o!=null);
- }//for
- return bRet;
- }//qualityControl
- Map<Object, Boolean> altQualityControl(
- Object[] pCheckThese
- ){
- Map<Object, Boolean> aRet= new HashMap<>();
- for (Object o : pCheckThese){
- boolean bOk = o!=null;
- aRet.put(o, bOk);
- }//for
- return aRet;
- }//altQualityControl
- void init(){
- mContext = this;
- mTvAbout = findViewById(R.id.idTvAbout);
- mTvCapturedText = findViewById(R.id.idTvCapturedText);
- mIvCapturedImage = findViewById(R.id.idIvCapturedImage);
- mLvRecords = findViewById(R.id.idLvRecords);
- mAlRecords = new ArrayList<>();
- mAd = new ArrayAdapter<>(
- mContext,
- android.R.layout.simple_list_item_1,
- mAlRecords //memory address for the data
- );
- mLvRecords.setAdapter(mAd);
- Object[] aRelevant = {mTvAbout, mTvCapturedText};
- boolean bCanProceed = qualityControl(aRelevant);
- if (!bCanProceed){
- Toast t = Toast.makeText(
- this,
- getString(R.string.strThereIsNullObject),
- Toast.LENGTH_LONG
- );
- return;
- }//if
- mTvAbout.setText(
- whereIsThePrivateInternalStorage()
- +"\nText Captured:"
- );
- /*
- TODO: avoid reprocessing the Intent on reexecutions of onCreate
- */
- checkIfCalledForSharingAndDisplayingSharedData();
- refresh();
- }//init
- void checkIfCalledForSharingAndDisplayingSharedData(){
- Intent intentHowWasICalled = getIntent();
- if (intentHowWasICalled!=null){
- String strAction =
- intentHowWasICalled.getAction();
- //share
- boolean bIWantToAnswer =
- strAction.equals(Intent.ACTION_SEND);
- boolean bIWantToAnswer2 =
- strAction.compareTo(Intent.ACTION_SEND)==0;
- boolean bIWantToAnswer3 =
- strAction.compareToIgnoreCase(Intent.ACTION_SEND)==0;
- if (bIWantToAnswer){
- //it was a share!
- String strType =
- intentHowWasICalled.getType();
- Toast.makeText(
- mContext,
- strType,
- Toast.LENGTH_LONG
- ).show(); //"image/png" "image/jpeg"
- boolean bIsText =
- strType.startsWith("text/");
- boolean bIsImage =
- strType.startsWith("image/");
- if (bIsText){
- String strTextThatWasShared =
- intentHowWasICalled.getStringExtra(
- Intent.EXTRA_TEXT
- );
- insert(strTextThatWasShared); //record the received text
- refresh(); //shows the text
- mTvCapturedText.setVisibility(View.GONE); //hides the TextView
- //enough for principle demonstration
- mTvCapturedText.setText(
- strTextThatWasShared
- );
- }//if text was shared
- else
- if (bIsImage){
- //content://saksçdlkaslçdkasdlçakd
- Uri uriForTheReceivedImage =
- intentHowWasICalled.getParcelableExtra(
- Intent.EXTRA_STREAM
- );
- if (uriForTheReceivedImage!=null){
- mIvCapturedImage.setImageURI(
- uriForTheReceivedImage
- );
- }//if
- }//if
- }//if the Activity was called from an ACTION_SEND Intent (e.g. Share from another app)
- }//if got an Intent object with all the necessary data
- }//checkIfCalledForSharingAndDisplaySharedText
- void dynAddObjsToLayout(
- LinearLayout pL,
- Uri pImgSource
- ){
- ImageView iv = new ImageView(mContext);
- iv.setImageURI(pImgSource);
- iv.setContentDescription("Bla bla bla");
- pL.addView(iv);
- }
- void refresh(){
- /*
- String strNewContent = readFile(MY_TSV_DB);
- mTvCapturedText.setText(strNewContent);
- */
- //mAlRecords = new ArrayList<>(); //NO GO! would break the Adapter
- mAlRecords.clear();
- //mAlRecords.addAll(readFile(MY_TSV_DB)); //original order
- ArrayList<String> alTemp = readFile(MY_TSV_DB);
- for (int idx=0; idx<alTemp.size(); idx++){
- String strContent = alTemp.get(idx);
- mAlRecords.add(0, strContent);
- }//for
- mAd.notifyDataSetChanged();
- }//refresh
- /*String*/ArrayList<String> readFile(
- String pFileName
- ){
- String strContent =
- readFromPrivateInternalStorage(pFileName);
- /*
- somewhat useless while the app is not rewritten using
- a true "Record" class data type
- and a collection of Records is kept (for example in ArrayList<Record>)
- */
- ArrayList<String> aRet = new ArrayList<>();
- String[] aRecords =
- strContent.split("\n");
- for(String record : aRecords){
- String strAfterReplacement =
- record.replace(
- "<br>", "\n"
- );
- aRet.add(strAfterReplacement);
- }//for
- return aRet;
- //return strContent;
- }//readFile
- /*
- will record with a TSV structure of our imagination
- the data in a file, in the private internal storage of the app
- <when> \t <text> \n
- */
- void insert(String pStrWhatToInsert){
- Calendar cal = Calendar.getInstance();
- String strYMD = String.format(
- "%d-%d-%d",
- cal.get(Calendar.YEAR),
- (cal.get(Calendar.MONTH)+1),
- cal.get(Calendar.DAY_OF_MONTH)
- );
- //replace the TSV reserved-symbols for innocuos alternatives
- // \n -> "<br>" ; \t -> " "
- String strAfterReplacement =
- pStrWhatToInsert.replace(
- "\n",
- "<br>"
- );
- strAfterReplacement =
- pStrWhatToInsert.replace(
- "\t",
- " "
- );
- String strRecord = String.format(
- "%s\t%s\n",
- strYMD,
- strAfterReplacement
- );
- Boolean bOK =
- writeToPrivateInternalStorage(
- MY_TSV_DB,
- //pStrWhatToInsert+"\n",
- strRecord,
- MODE_APPEND
- );
- if (bOK){
- Toast t = Toast.makeText(
- mContext,
- "New record added to TSV DB",
- Toast.LENGTH_LONG
- );
- t.show();
- }//if
- }//insert
- /*
- to read and write in the Private Internal Storage
- we need tools for dumping and recovering text from
- that exclusive non-volatile file-system area
- */
- String whereIsThePrivateInternalStorage(){
- File pis = this.getFilesDir();
- return pis.getAbsolutePath();
- }//whereIsThePrivateInternalStorage
- Boolean writeToPrivateInternalStorage(
- String pFileName,
- String pFileContent,
- int pWriteMode //PRIVATE (destructive) / APPEND (cumulative)
- ){
- try {
- FileOutputStream fos = openFileOutput(
- pFileName,
- //MODE_APPEND
- pWriteMode
- );
- if (fos!=null){
- OutputStreamWriter osw = new OutputStreamWriter(
- fos,
- StandardCharsets.UTF_8
- );
- if (osw!=null){
- osw.write(pFileContent);
- osw.close();
- fos.close();
- return true;
- }//if
- }//if
- }//try
- catch (Exception e){
- Log.e(
- getClass().getName(),
- e.toString()
- );
- }//catch
- return false;
- }//writeToPrivateInternalStorage
- String readFromPrivateInternalStorage(
- String pFileName
- ){
- try{
- FileInputStream fis = this.openFileInput(pFileName);
- if (fis!=null){
- InputStreamReader isr = new InputStreamReader(
- fis,
- StandardCharsets.UTF_8
- );
- if (isr!=null){
- int i; char c; String strAll="";
- while ((i=isr.read())!=-1){
- c = (char) i;
- strAll+=c;
- }//while
- isr.close();
- fis.close();
- return strAll;
- }//if
- }//if
- }//try
- catch(Exception e){
- Log.e(
- getClass().getName(),
- e.toString()
- );
- }//catch
- return "";
- }//readFromPrivateInternalStorage
- }//MainActivity
- //
- 1 - layout LL RL CL
- 2 - init / assocs / behavior
- 3 - depende avaliar competência extra relacionada com o comportamento
- 4 - storage : ficheiros ou SQLite
- 5 - capacidade criativa
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement