Android emulator does not show image stored - java

I'm working on a project designed to turn a smartphone into a Microscope (little bit of image processing too); I've decided to build my program in Android Studio for android phones.
Looking online I found a few tutorials on how to access the camera, capture an image and store it in memory. For some reason the emulator used to run the program is showing is only capturing the image, but not storing it in memory. Is their an issue with the emulator? How would I transfer this program I'm writing to my Android Google Nexus 5 phone?
here is some XML code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.smartphonemicroscope">
<uses-feature android:name="android.hardware.camera2"></uses-feature> <!-- Acess camera2 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Microscope">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
here is some Java:
package com.example.user.smartphonemicroscope;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.hardware.camera2.CameraDevice;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
public class Microscope extends Activity {
Button button;
ImageView imageView;
static final int CAM_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_microscope);
button = (Button) findViewById(R.id.button);
imageView = (ImageView) findViewById(R.id.image_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getFile();
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(camera_intent, CAM_REQUEST);
}
});
}
private File getFile() {
File folder = new File("sdcard/camera_app");
if(!folder.exists())
{
folder.mkdir();
}
File image_file = new File(folder,"cam_image.jpg");
return image_file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String path = "sdcard/camera_app/cam_image.jpg";
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
I also have a few images of what it looks like in the interface.
Emulator Camera Accessed, after pressing capture button
Image Captured, but will not save

File folder = new File("sdcard/camera_app");
That value is wrong on ~1.5 billion Android devices.
More generally, never hardcode paths. Always use some method to derive a root location to write into. You appear to be wishing to write to external storage. In that case, use a method like getExternalFilesDir() (on Context) or methods on Environment to get a root location to write to.

Related

How to Pass Data From a BroadcastReceiver to an Activity in Android

I am working on my first Android app, which is a paging device. It will intercept a SMS message from a certain number with a certain content in it, display that and then allow the user to send a pre-defined reply back to that same number. I have gathered up code snippets from numerous sources (including stackoverflow of course) but I haven't yet got it working.
My file structure is as shown here
The part I am struggling with is SmsBroadcastReceiver and ReceiveAlert, which should display the content of the SMS and has a button to initiate the reply.
SmsBroadcastReceiver.java looks like this:
package com.example.alert6;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String EXTRA_MESSAGE = "com.example.alert6.MESSAGE";
#Override
public void onReceive(Context context, Intent intent) {
String smsSender = "";
String smsBody = "";
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
smsSender = smsMessage.getOriginatingAddress();
smsBody = smsMessage.getMessageBody();
}
if (smsSender.equals("+420775367297")) {
if (smsBody.contains("Test")) {
intent.putExtra(EXTRA_MESSAGE, smsBody);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // adding this flag starts the new Activity in a new Task
context.startActivity();
}
}
}
}
ReceiveAlertActivity.java is this:
package com.example.alert6;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ReceiveAlertActivity extends AppCompatActivity {
private static final int SMS_PERMISSION_CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_alert);
}
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String taskingalert = intent.getStringExtra(SmsBroadcastReceiver.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView receivedAlert = findViewById(R.id.receivedAlert);
receivedAlert.setText(taskingalert);
public boolean respond(View view) {
if (!hasReadSmsPermission()) {
requestReadAndSendSmsPermission();
return false;
}
Intent intent = new Intent(this, SendResponseActivity.class);
startActivity(intent);
return false;
}
/**
* Runtime permission shenanigans
*/
private boolean hasReadSmsPermission() {
return (ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(ReceiveAlertActivity.this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED);
}
private void requestReadAndSendSmsPermission() {
ActivityCompat.requestPermissions(ReceiveAlertActivity.this, new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS, Manifest.permission.SEND_SMS},
SMS_PERMISSION_CODE);
}
}
And the manifest is this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.alert6">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Alert6">
<activity
android:name=".SendResponseActivity"
android:parentActivityName=".ReceiveAlertActivity">
</activity>
<activity
android:name=".ReceiveAlertActivity"
android:parentActivityName=".MainActivity">
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SmsBroadcastReceiver"
android:enabled="true"
android:exported="true"
tools:ignore="Instantiatable">
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Android Studio is showing errors in SmsBroadcastReceiver and ReceiveAlertActivity but not giving enough information to resolve them.
In SmsBroadcastReceiver, it tells me it cannot resolve method 'startActivity()'. Something needs to go in the brackets, but what?
In ReceiveAlertActivity the problems revolve around receivedalert and taskingalert. It cannot resolve setText because taskingalert is an unknown class. Obviously it's not a class, it's a string so I'm doing something wrong, but what?
Sorting out these problems may not be the end. At the moment I can't test if the app works because the build fails due to the above. Then if I get this lot working, I have some other challenges, like waking up the screen and playing a sound the broadcast receiver is triggered, and stopping the sound when the button is pressed.
You can use an Observable object in your BroadcastReceiver to store the piece of information you want to send and implement the Observer interface in your Activity so that it will be warned of every change occuring to the Observable object.

onActivityResult is not getting called in MainActivity.Java

I am trying to make an app which shows a user selected image which can be set by double-clicking on the button. The app does ask me for an image (which is good) but I don't know how to set it on ImageView if this onActivityResult is not getting called.
MainActivity:
package com.forever.bobby.cheater20;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.tomerrosenfeld.customanalogclockview.CustomAnalogClock;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE = 100;
Button hiddenOnClickListener;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = findViewById(R.id.imageView);
CustomAnalogClock customAnalogClock = (CustomAnalogClock) findViewById(R.id.analog_clock);
customAnalogClock.setAutoUpdate(true);
hiddenOnClickListener = (Button) findViewById(R.id.touchButtonHidden);
hiddenOnClickListener.setOnClickListener(new DoubleClickListener() {
#Override
public void onSingleClick(View v) {
Log.e ("mPressesOnce -_-","..");
}
#Override
public void onDoubleClick(View v) {
Log.e ("mPressesTwice -_-","..");
openGallery();
}
});
}
private void openGallery () {
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, 0);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode,data);
Log.e ("SHould Be Steeted","");
if (requestCode == 0) {
Uri imgUri;
imgUri = data.getData();
// img.setImageURI(imgUri);
}
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.forever.bobby.cheater20">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Any Kind of help is appreciated as I am a newbie
With android sdk >= 23, some permissions e.g. WRITE_EXTERNAL_STORE, READ_EXTERNAL_STORE, etc. you must request it in java code.
Therefore, when user starts using feature need permission, android will show a dialog and user can grant or cancel a permission. You can read more about it on developer.android.com.

Android 7.1.1 cannot create file or folders in external storage. FileNotFoundException

I am attempting to capture sensor data in a textfile that I can extract from the 'external storage' of the phone when I connect it via USB to a PC so I can run the textfile through a python script for graphing purposes. I have not implemented the sensor part yet as I am unable to create files that I can copy over to the PC from the phone after they have been created.
I attempt to create a folder and it does not create the folder and I also attempt to create a file and it also fails and then it throws an exception that the file does not exist. I am at a loss as I have added the permission to the manifest file as you can see below. Is there anything that I am missing? I have done a lot of searching around and there does not seem to be any solution to my problem and the developer.android.com website does not explain anything regarding permissions outside of adding the lines I already added to the manifest file.
I do not own an SDcard so using the sdcard is not a possible solution to my problem.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.project_final">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and here is my entire code that I have done so far which is throwing the errors.
package com.example.mike.project_final;
import android.content.Context;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.hardware.Sensor;
import android.view.View;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView xTV, yTV, zTV, writeTV;
SensorManager sManager;
Sensor sAccelerometer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xTV = (TextView) findViewById(R.id.xTV);
yTV = (TextView) findViewById(R.id.yTV);
zTV = (TextView) findViewById(R.id.zTV);
writeTV = (TextView) findViewById(R.id.writeTV);
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
public void createFile(View view) {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/project_test");
if (!dir.exists()){
dir.mkdir();
xTV.setText("Created");
}
else{
xTV.setText("Exists");
}
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (Exception e) {
writeTV.setText(e.toString());
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy){
//do nothing
}
#Override
public void onSensorChanged(SensorEvent event) {
}
}
Any help with how to setup the rest of the permissions if required will be really appreciated!
EDIT 1:
The issue with permissions have been solved, thank you. I now have an issue that the folder I create does not create as a folder but as a file as shown in the image below. What exactly am I doing wrong?
https://i.imgur.com/srKXJc1g.png
Unfortunately I don't have enough reputation to post images.

Unlock Android device programmatically and load application on boot up

Objective: Unlock Android device programmatically and load application on boot up
API: 10 & 18
IDE: Eclipse
Test device: Emulator
I understand this issue has been widely discussed on stackoverflow and elsewhere. But I am unable to get this to work. My first question is
Can the Emulator be programmatially unlocked and an application be loaded on boot up?
I also read that after API 13 some there were some changes and I am not sure if I am accounting for these changes
Assuming the answer is yes please find code excepts below.
AndroidManifest.xml
<manifest
package="com.example.display">
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.display.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.example.display.myreceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
MainActivity.java
package com.example.display;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Unlock
// http://developer.android.com/reference/android/app/Activity.html#getWindow()
Window window = getWindow();
window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
myreceiver.java
I am expecting this section of the code to get executed on boot up and start the application.
package com.example.display;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class myreceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(myIntent);
}
}
Issue: I have loaded the above code to the emulator and re-started the emulator. I was expecting the code application to unlock the emulator and load the application of boot up. It doesn't happen...
Not sure where to look for next...
Most of the code snippets are from on stackoverflow.
Some of the post that I have referenced are
Trying to start a service on boot on Android
How to launch the application upon booting up the device?
Android - Wake Up and Unlock Device
Thank you in advance.
Hi here i added the unlock programmatically and launch our application using the below code.You need to add the unlock code in broadcast receiver.
Please try and let me. Thanks
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
public class myreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Unlock the screen
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "INFO");
wl.acquire();
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock kl = km.newKeyguardLock("name");
kl.disableKeyguard();
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(myIntent);
}
}

Android basic activity call 2 pages with 1 button respectivly found no erros on validate still won't work in AVD

Can someone tell me whats wrong?? lost
Thanks,Mike
P.S.
I figured this might work instead of the splash for 1st page.
page1 or activity 1
package com.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class test1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.Button01);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(),test2.class);
startActivityForResult(myIntent, 0);
}
});
}
}
page2 or activity 2
package com.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class test2 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Button next = (Button) findViewById(R.id.Button02);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
}) ;
}
}
Manifiest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".test1"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activity2"></activity>
</application>
</manifest>
What is really wrong is you posting a question on StackOverflow, asking "Can someone tell me whats wrong??", without even taking the time to describe what symptoms you are experiencing. You are lucky that I am in a pretty good mood right now.
There are at least two problems:
Your manifest refers to an Activity2 that does not appear to exist
Your activity test2 is not defined in the manifest
I am guessing you just created your manifest incorrectly, seems that you have test2 as the class but tell the manifest it's name is Activity2.

Categories

Resources