Link to home
Start Free TrialLog in
Avatar of Saqib Husain
Saqib HusainFlag for Pakistan

asked on

Cannot find symbol variable

While compiling my code I am getting this error

error: cannot find symbol variable DrawingImageView

Can someone lead me to how to overcome this?

package rectangle.android.com.rectangletouch;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.drive.DriveClient;
import com.google.android.gms.drive.DriveResourceClient;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{

    private static final String TAG = "MEDIA";
    private TextView tv;
    private ImageView drawingImageView;
    private static boolean show_state;
    private int height, width;
    private static Date lastDate;
    private static int iSwitch_num;
    private static final String TAGDRIVE = "drive";

    private static String write_Str;
//    private static String read_str;
    private static final int REQUEST_WRITE_PERMISSION = 786;
    private static final int REQUEST_READ_PERMISSION = 785;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            writeToSDFile(write_Str);
        }
//        if (requestCode == REQUEST_READ_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            read_str = readFromSDFile();
//        }
    }
    private void request_write_Permissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
        } else {
            writeToSDFile(write_Str);
        }
    }
//    private void request_read_Permissions() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_PERMISSION);
//        } else {
//            read_str = readFromSDFile();
//        }
//    }
    public class MyData{
        private boolean show_state;
        private int switch_num;
        private Date lastDate;
        public MyData(boolean show_state, int switch_num, Date lastDate){
            this.show_state = show_state;
            this.switch_num = switch_num;
            this.lastDate = lastDate;
        }
        public String getShow_State(){
            return show_state? "show":"hide";
        }
        public int getSwitch_num(){
            return switch_num;
        }
        public Date getLastDate(){
            return lastDate;
        }
        public String toString(){
            SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
            String date = format.format(getLastDate());
            return String.valueOf(getShow_State()) + "\n" + String.valueOf(getSwitch_num()) + "\n" + date;
        }
    }
    private String getCertificateSHA1Fingerprint(Context mContext) {
        PackageManager pm = mContext.getPackageManager();
        String packageName = mContext.getPackageName();
        int flags = PackageManager.GET_SIGNATURES;
        PackageInfo packageInfo = null;
        try {
            packageInfo = pm.getPackageInfo(packageName, flags);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Signature[] signatures = packageInfo.signatures;
        byte[] cert = signatures[0].toByteArray();
        InputStream input = new ByteArrayInputStream(cert);
        CertificateFactory cf = null;
        try {
            cf = CertificateFactory.getInstance("X509");
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        X509Certificate c = null;
        try {
            c = (X509Certificate) cf.generateCertificate(input);
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        String hexString = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(c.getEncoded());
            hexString = byte2HexFormatted(publicKey);
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (CertificateEncodingException e) {
            e.printStackTrace();
        }
        return hexString;
    }

    @NonNull
    public static String byte2HexFormatted(byte[] arr) {
        StringBuilder str = new StringBuilder(arr.length * 2);
        for (int i = 0; i < arr.length; i++) {
            String h = Integer.toHexString(arr[i]);
            int l = h.length();
            if (l == 1) h = "0" + h;
            if (l > 2) h = h.substring(l - 2, l);
            str.append(h.toUpperCase());
            if (i < (arr.length - 1)) str.append(':');
        }
        return str.toString();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e("SHA1:", getCertificateSHA1Fingerprint(this.getBaseContext()));
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        height = displayMetrics.heightPixels;
        width = displayMetrics.widthPixels;
        String read_str = readFromSDFile();
//        request_read_Permissions();
        Intent intent = new Intent(getBaseContext(), RetrieveContentsActivity.class);
        intent.putExtra("string", read_str);
        startActivity(intent);
        drawRectangle(show_state);
    }
    public void drawRectangle(boolean type){
        drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
        Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
                .getDefaultDisplay().getWidth(), (int) getWindowManager()
                .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawingImageView.setImageBitmap(bitmap);
        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(10);
        float leftx, topy, rightx, bottomy;
        if(type){
            leftx = width / 2 - 40;
            topy = height / 2 - 40;
            rightx = width / 2 + 40;
            bottomy = height / 2 + 40;
        } else{
            leftx = 0;
            topy = 0;
            rightx = 0;
            bottomy = 0;
        }
        canvas.drawRect(leftx, topy, rightx, bottomy, paint);
    }
    private boolean checkExternalMedia(){
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // Can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
            return true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // Can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
            return false;
        } else {
            // Can't read or write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
            return false;
        }
    }
    public String getExternalSdCardPath() {
        String path = null;

        File sdCardFile = null;
        List<String> sdCardPossiblePath = Arrays.asList("sdcard", "external_sd", "ext_sd", "external", "extSdCard", "SDCARD");

        for (String sdPath : sdCardPossiblePath) {
            File file = new File("/", sdPath);

            if (file.isDirectory() && file.canWrite()) {
                path = file.getAbsolutePath();

                String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
                File testWritable = new File(path, "test_" + timeStamp);

                if (testWritable.mkdirs()) {
                    testWritable.delete();
                }
                else {
                    path = null;
                }
            }
        }

        if (path != null) {
            sdCardFile = new File(path);
        }
        else {
            sdCardFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
        }

        return sdCardFile.getAbsolutePath();
    }
    private void writeToSDFile(String str){
        File dir = new File(getExternalSdCardPath() + "/rectangle_show");
        if(!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(dir, "Rectangle.txt");
        try {
            FileOutputStream f = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(f);
            pw.print(str);
            pw.flush();
            pw.close();
            f.close();
            String msg = "File written to "+ file.getPath();
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.i(TAG, "******* File not found. Did you" +
                    " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Nullable
    private String readFromSDFile(){
        File dir = new File(getExternalSdCardPath() + "/rectangle_show");
        File file = new File(dir, "Rectangle.txt");
        try {
            StringBuffer fileContent = new StringBuffer("");
            byte[] buffer = new byte[1024];
            FileInputStream f = new FileInputStream(file);
            int n;
            while ((n = f.read(buffer)) != -1)
            {
                fileContent.append(new String(buffer, 0, n));
            }
            String data = fileContent.toString();
            String[] separted = data.split("\n");
            if(separted[0].equals("show")){
                show_state = true;
            } else {
                show_state = false;
            }
            try{
                iSwitch_num = Integer.parseInt(separted[1]);
            }catch (NumberFormatException e){
                e.printStackTrace();
            }
            SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
            try{
                lastDate = format.parse(separted[2]);
            } catch (ParseException e){
                e.printStackTrace();
            }
            return data;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            show_state = false;
            iSwitch_num = 0;
            lastDate = Calendar.getInstance().getTime();
            Log.i(TAG, "******* File not found. Did you" +
                    " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        super.onTouchEvent(event);
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            Date nowDate = Calendar.getInstance().getTime();
            if ((nowDate.getTime() - lastDate.getTime()) / 1000 < 1){
                Toast.makeText(this, "Please touch after 5s", Toast.LENGTH_SHORT).show();
                return false;
            }
            lastDate = nowDate;
            if(!show_state){
                drawRectangle(true);
                show_state = true;
            } else{
                drawRectangle(false);
                show_state = false;
            }
            iSwitch_num++;
            MyData myData = new MyData(show_state, iSwitch_num, lastDate);
            if(checkExternalMedia()){
                String out_str = myData.toString();
                write_Str = out_str;
                request_write_Permissions();
                Intent intent = new Intent(getBaseContext(), QueryFilesActivity.class);
                intent.putExtra("string", out_str);
                startActivity(intent);
            } else{
                Toast.makeText(this, "SD Card is removed or write-protected!", Toast.LENGTH_SHORT).show();
            }
            return true;
        }
        return false;
    }
}

Open in new window

Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

java is not supported on android devices without rooting the device
SOLUTION
Avatar of George Walton
George Walton
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Saqib Husain

ASKER

Thanks for both the responses.

This program had been working as is but has gone berserk now. I only changed the background to black from white in the layout and the display to full screen. Since then bringing it back to the original also does not work.

Anyhow, can you please do the change to the code. I am not sure I understand how you want me to do it. I am new to this sector.

Thanks in advance.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I changed it accordingly but the error remained the same. From the looks I have a feeling that there would be something wrong with the imports.
So is your error occuring at line 182?
Yes, the last part
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@ Saqib Husain, Syed

Any more you'd like to ask here? Obviously you can close the question if it didn't produce what you wanted in the end.
krakatoa
Sorry for sleeping on this. I really could not get this to work. I do agree to krakatoa's comment that R needs a reference. But it could not help me achieve my target. I did make a subsequent attempt to learn Java but miserably failed. So I am now abandoning the idea.