I have the following code , im receiving an error :
enter image description here
package com.example.photopicker;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button addimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addimage=findViewById(R.id.button_pick_photo);
addimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Registers a photo picker activity launcher in single-select mode.
ActivityResultLauncher<PickVisualMediaRequest> pickMedia =
registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
// Callback is invoked after the user selects a media item or closes the
// photo picker.
if (uri != null) {
Log.d("PhotoPicker", "Selected URI: " + uri);
} else {
Log.d("PhotoPicker", "No media selected");
}
});
// Include only one of the following calls to launch(), depending on the types
// of media that you want to allow the user to choose from.
// Launch the photo picker and allow the user to choose images and videos.
pickMedia.launch(new PickVisualMediaRequest.Builder()
**.setMediaType(new ActivityResultContracts.PickVisualMedia.ImageAndVideo())**
.build());
}
});
}
}
This code i got it from the Android developer Website :
https://developer.android.com/training/data-storage/shared/photopicker
but Doesnt seem to work , and im not able to find any online solution.
Try replacing:
new ActivityResultContracts.PickVisualMedia.ImageAndVideo()
with:
ActivityResultContracts.PickVisualMedia.Companion.getImageAndVideo()
ImageAndVideo is a Kotlin object — it is not a class that you instantiate yourself. However, the source code lacks the #JvmField annotation, so I think that just referring to ActivityResultContracts.PickVisualMedia.ImageAndVideo will fail, as outlined in the docs.
Related
I have tried to install OpenCV for Java-App Development in Android Studio. The app starts on the emulator and tried to load but instantly shuts down. This happens when the app encounter anything related to OpenCV in the code (excluding imports).
This is not the entire project, if you want to compile and need everything drop a comment
package com.example.cse535a1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.content.Context;
import android.view.View;
import android.hardware.*;
import android.widget.FrameLayout;
import org.opencv.core.*;
public class MainActivity extends AppCompatActivity {
Camera c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))) {
this.finish();
System.exit(0);
}
// System.loadLibrary(Core.NATIVE_LIBRARY_NAME); ---------------------------------CRASHES HERE
// Mat mat = Mat.eye(3, 3, CvType.CV_8UC1);
// Log.i("OPENCV", mat.dump());
Button button_symptoms = (Button)findViewById(R.id.button_symptoms);
Button button_upload_signs = (Button)findViewById(R.id.button_upload_signs);
Button button_measure_heart_rate = (Button)findViewById(R.id.button_measure_heart_rate);
Button button_measure_respiratory_rate = (Button)findViewById(R.id.button_measure_respiratory_rate);
c = getcam();
CameraView cv1 = new CameraView(getApplicationContext(), c);
FrameLayout view_camera = (FrameLayout)findViewById(R.id.view_camera);
view_camera.addView(cv1);
button_symptoms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
Intent intent = new Intent(getApplicationContext(), Loggin_symptoms.class);
startActivity(intent);
}
});
button_upload_signs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
}
});
button_measure_heart_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
}
});
button_measure_respiratory_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
SensorManager manager_sensor = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor_accelerometer = manager_sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
});
}
I have previously done some research before posting on StackOverflow and I found this->
Android crashes when using OpenCV from activity
This has led me to the install instructions on-> Installing OpenCV 2.4.13.7. The necessary part can be found under Application Development with Static Initialization.
But unfortunately, the entire process of having an Android.mk file is no longer in use. So to solve this problem what do I do now?
Is there a different file where the OPENCV_INSTALL_MODULES:=on line must be inserted?
So, I think I have found the solution to this problem in my case.
Upon looking in the Logcat tab in Android studio, I noticed a problem that libopencv_java451.so was not found. In the jniLibs folder there was instead libopencv_java4.so.
A simple rename fixed this problem. There are two places where I renamed the files.
jniLibs folder in the project directory
jniLibs in the opencv sdk directory (though this one might be ultimately responsible)
Depending on the system (for me-> x86 and x86_64), rename your files.
I have attached a pic showing my project file structure, look at the large yellow marks which show the renamed files.
I'm working on a simple number guessing game. At the moment I have it set that when you guess the correct number it takes you to WinActivity.java. All I want it to do on that screen is say "You won" and to play a little trumpet victory sound (and also display a button that'll bring them to the GameActivity if they want to play again).
The trouble is, when I try bringing in a MediaPlayer the app doesn't even start.
Here is my code for my WinActivity that contains the MediaPlayer.
package com.example.jeremy.numberguessinggame;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class WinActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_win);
MediaPlayer trumpetsound = MediaPlayer.create(this,R.raw.trumpet);
trumpetsound.start();
Button btnPlayAgain = (Button) findViewById(R.id.button2);
TextView youWon = (TextView) findViewById(R.id.textViewYouWon);
btnPlayAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent playAgainIntent = new Intent(WinActivity.this,GameActivity.class);
startActivity(playAgainIntent);
}
});
}
}
When I run the app the Messages Gradle Build window will pop up and says "error: cannot find symbol variable raw".
I added the raw folder to the res location, and was able to drag the sounds into the folder no problem.
I just don't see why I can't make this MediaPlayer work.
I would love some help. If you need more information I'll be glad to give it to you.
Hi I have been racking my brain for hours, did research online but nobody seems to have an answer. My emulator was running my code no problem then I ran it again and I get "Session 'MainActivity': error". I looked through this main activity about 10 times but there is no error sign anywhere and it looks like it should be working fine, I mean it was working before no problem. So I'm not sure if there really is a problem I don't see that Android Studio is not pointing out properly or if this is a different problem all together.
Any help would be greatly appreciated. Thank you.
package tekvision.codedecrypter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import gameInfo.GameDatabase;
public class MainActivity extends ActionBarActivity {
//Runs before the application is created
private Button mCampaignButton;
private final Context context = this;
//When the application is created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiate a GameDatabase object (this activity)
final GameDatabase gDB = new GameDatabase(context);
gDB.fillGameDatabase();
//Keeps screen on so it doesn't fall asleep
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//Finding button by button id after application is created
mCampaignButton = (Button)findViewById(R.id.campaignButtonID);
//Checks if the campaign button is clicked
mCampaignButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ans = gDB.getAnswer("Ancient",1);
//Toast pop up message
Toast toast = Toast.makeText(getApplicationContext(),
ans ,
Toast.LENGTH_SHORT);
toast.show();
//Intent to go from main activity to campaign Level Select Activity
final Intent intent = new Intent(MainActivity.this, CampaignSelectLevel.class);
startActivity(intent);
}
});
}
}
Try rebuilding and cleaning your project.
Build > Rebuild Project
and
Build > Clean Project
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my application I noticed these three things:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The problem is I don't want the user to click on Back at a certain point in my application. I don't want to disable the back button completely in my application, only when one intent is called. How can I do that?
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my application, some of the toast notifications are residual and are popping outside of my application. Is there a reason for that? Did I miss something in the activity lifecycle to handle the cancellation of toasts at a certain point?
Lastly, this one is rather tough to solve. How do I lock my screen so that when the user rotates the device, that the activity doesn't not get called again and the asynctask can still resume without starting over again?
Thanks a lot for your time. Just curious why these things happen and what should I look into?
Here's my code:
//Main Activity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.*;
public class MainActivity extends Activity {
//fields
private ProgressDialog progressBar;
private Context context;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_setup);
//Set the context
context = this;
//Initialize the start setup button and add an onClick event listener to the button
final Button start_setup_button = (Button) findViewById(R.id.start_setup_button);
start_setup_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Executes the AsyncTask
new RetrieveInfoTask().execute();
//Instantiates the intent to launch a new activity
Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public class RetrieveInfoTask extends AsyncTask<Void, Void, Void> {
//Called on the UI thread to execute progress bar
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage(MainActivity.this.getString(R.string.retrieve_info));
progressBar.show();
}
//Methods that retrieves information from the user device. This is performed in the Background thread
private void retrieveInfo() {
try {
//Reading the drawable resource line by line
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//doInBackground calls retrieveInfo() to perform action in Background
#Override
protected Void doInBackground(Void... params) {
retrieveInfo();
return null;
}
//When the background task is done, dismiss the progress bar
#Override
protected void onPostExecute(Void result) {
if (progressBar!=null) {
progressBar.dismiss();
}
}
}
}
//RetrieveInfoActivity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class RetrieveInfoActivity extends Activity {
private static String TAG = "RetrieveInfoActivity";
private Context context;
String fileLastSync = "09-18-2014 03:47 PM";
#Override
public void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.retrieve_info);
//Once the new activity is launched, the setup is complete
Toast.makeText(getApplicationContext(), "Setup Complete!",
Toast.LENGTH_LONG).show();
//Gets the 'last synced' string and sets to datetime of the last sync
Resources resources = context.getResources();
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);
//Dynamically sets the datetime of the last sync string
TextView lastSyncTextView = ((TextView) findViewById(R.id.last_sync) );
lastSyncTextView.setText(syncString);
//calls registerReceiver to receive the broadcast for the state of battery
this.registerReceiver(this.mBatInfoReceiver,new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
//Battery level
int level = intent.getIntExtra("level", 0);
//Dynamically sets the value of the battery level
TextView batteryTextView = ((TextView) findViewById(R.id.battery) );
batteryTextView.setText("Battery Level: " + String.valueOf(level)+ "%");
//If the battery level drops below 25%, then announce the battery is low
//TODO: Add 25 to constants file.
if(level < 25) {
Toast.makeText(getApplicationContext(), "Low Battery!",
Toast.LENGTH_LONG).show();
}
//Plugged in Status
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//Battery Status
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//If the device is charging or contains a full status, it's charging
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
//If the device isCharging and plugged in, then show that the battery is charging
if(isCharging && plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Charging.." + String.valueOf(level)+ "%",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unplugged!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onDestroy() {
try {
super.onDestroy();
unregisterReceiver(this.mBatInfoReceiver);
}
catch (Exception e) {
Log.e(RetrieveInfoctivity.TAG, getClass() + " Releasing receivers-" + e.getMessage());
}
}
}
//StartSetupActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartSetupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
//FragmentsActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentsActivity extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
}
First of all whenever you want to disable back press just override onBackPressed() method and remove super. like this:
#Override
public void onBackPressed() {
//super.onBackPressed();
}
Second you'r using application context to show toast. use activity context.
Toast.makeText(this or YourActivity.this, "Setup Complete!", Toast.LENGTH_LONG).show();
Third just add this attribute into your manifest class. This will avoid recrating your activity when orientation change
android:configChanges="orientation"
I'll answer these in order:
Back Button
You can override onBackPressed in your Activity and determine if you want to consume it or let Android process it.
#Override
public void onBackPressed()
{
// Set this how you want based on your app logic
boolean disallowBackPressed = false;
if (!disallowBackPressed)
{
super.onBackPressed();
}
}
Toasts
Toasts are enqueued with the Notification Manager. If you show multiple Toasts in a row, they get queued up and shown one at a time until the queue is empty.
Locking Orientation For Activity
Use android:screenOrientation="landscape" or android:screenOrientation="portrait" on your activity element in your manifest to lock the orientation.
I think that these questions should be asked separately, because the answer in detail to every item of your question is too long, but I hope this helps:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The
problem is I don't want the user to click on Back at a certain point
in my application. I don't want to disable the back button completely
in my application, only when one intent is called. How can I do that?
You can override the onBackPressed on the activities you don't want the user to go back.
#Override
public void onBackPressed() {
//Leave it blank so it doesn't do anything
}
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my
application, some of the toast notifications are residual and are
popping outside of my application. Is there a reason for that? Did I
miss something in the activity lifecycle to handle the cancellation of
toasts at a certain point?
I think that the reason behind that is that toast go into a que, and are showed in order, even if the app is no longer visible.
Lastly, this one is rather tough to solve. How do I lock my screen so
that when the user rotates the device, that the activity doesn't not
get called again and the asynctask can still resume without starting
over again?
For this, you can use the following code in your manifest
android:configChanges="orientation|screenSize"/>
However this is NOT recommended by google, I suggest you read the following link to get a little more information on how to handle orientation changes:
http://developer.android.com/guide/topics/resources/runtime-changes.html
I'm new to Java, Android and JUnit. I want to learn how to write JUnit tests for an Android application. To that end, I have a very simple Android app (2 activities, 2 buttons, each button goes to the other activity). I want to test the button. This app runs fine on my phone when it's plugged in. I've been looking at the samples provided in the SDK, and I am trying to emulate them.
My problem is that when I right-click on my test project, and choose Run As -> Android JUnit test, nothing happens. I don't know why.
My test code.
package com.example.twoactivities.test;
import android.app.Instrumentation.ActivityMonitor;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import com.example.twoactivities.MainActivity;
import com.example.twoactivities.MainActivity2;
public class ClickButton extends ActivityInstrumentationTestCase2<MainActivity> {
private Button mButton2;
private long TIMEOUT_IN_MS = 100000;
public ClickButton() {
super(MainActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
final MainActivity a = getActivity();
// ensure a valid handle to the activity has been returned
assertNotNull(a);
}
#SmallTest
public void click(){
// Set up an ActivityMonitor
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(MainActivity2.class.getName(), null, false);
//check if button is enabled
assertTrue("button is enabled", mButton2.isEnabled());
//click button
mButton2.performClick();
MainActivity2 MainActivity2 = (MainActivity2) activityMonitor.waitForActivityWithTimeout(TIMEOUT_IN_MS );
assertNotNull("MainActivity2 is null", MainActivity2);
// assertEquals("Monitor for MainActivity2 has not been called", 1, activityMonitor.getHits());
// assertEquals("Activity is of wrong type", MainActivity2.class, MainActivity2.getClass());
// Remove the ActivityMonitor
getInstrumentation().removeMonitor(activityMonitor);
}
// public void tearDown() {
// }
}
(I know it's really simple, but I'm just trying to get the basics down.)
My application.
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void activity2(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity2.class);
startActivity(intent);
}
}
Activity 2 of my application.
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void activity1(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity.class);
startActivity(intent);
}
}
Any ideas why my test class doesn't run?
Thanks,
Stephanie
You have to right click on the test itself, not the project.
According to documentation Android testing API supports JUnit 3 code style, but not JUnit 4. Try naming your test method testClick