Cannot resolve Methods (Beginner issue in Android Studio (java)) - java

I am following a tutorial in how to set up a Surface View in Android Studio using Java. This is my code:
package com.example.benjamin.labb3;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.SurfaceHolder;
public class SurfaceView extends Activity {
private OurView v;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(v);
v = new OurView(this);
}
#Override
protected void onPause() {
super.onPause();
v.pause();
}
#Override
protected void onResume() {
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable {
Thread t = null;
SurfaceHolder holder;
boolean isOk = false;
public OurView(Context context){
super(context);
holder = getHolder();
}
public void run(){
if(isOk){
}
}
public void pause(){
isOk = false;
while (true){
try {
t.join();
t = null;
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void resume(){
isOk = true;
t = new Thread(this);
t.start();
}
}
}
In
setContentView(v);
I am getting the error msg:
"Cannot resolve method
setContentView(com.example.ben3.pl2.SurfaceView.OurView)"
And in
public OurView(Context context){
super(context);
holder = getHolder();
}
I am getting the errors:
"Cannot resolve method super(android.content.Context)"
"Cannot resolve method getHolder()"
Can anyone help me? The tutorial is from 2011 so it could have something to do with them having a older version of AS, or i just missed something perhaps.

Couple things you should fix here. Rename your class and file to MyActivity or at least something other than SurfaceView to avoid confusion. You want to use the SurfaceView from android.view.SurfaceView not your own so you should import that one.
import android.view.SurfaceView;
Also, you must create a new instance of OurView before using it in setContentView().
Here is your code with the changes applied.
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MyActivity extends Activity {
private OurView v;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
v = new OurView(this);
setContentView(v);
}
#Override
protected void onPause() {
super.onPause();
v.pause();
}
#Override
protected void onResume() {
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable {
Thread t = null;
SurfaceHolder holder;
boolean isOk = false;
public OurView(Context context){
super(context);
holder = getHolder();
}
public void run(){
if(isOk){
}
}
public void pause(){
isOk = false;
while (true){
try {
t.join();
t = null;
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void resume(){
isOk = true;
t = new Thread(this);
t.start();
}
}
}

just try to instanciate your view before the setcontentview method
like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v = new OurView(this);
setContentView(v);
}
keep me up to date

Related

Android onCreate of Activity class is not triggered

I am trying to write a plugin for Capacitor. It should pass the accelerometer data to the JavaScript. The bridge works fine.
However, the heading class does not seem to be initialized. The onCreate function does not seem to be executed, so do all the other functions. Nothing is logged to the console.
In AndroidManifest.xml I have requested the following feature:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
The file looks like this:
package de.example.capmap;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import com.getcapacitor.BridgeActivity;
import de.example.Compass;
public class MainActivity extends BridgeActivity {
private Heading heading;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(Compass.class);
heading = new Heading();
}
}
class Heading extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor mAccelerometer;
private static final String TAG = "Heading";
#Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate: Initializing");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(Heading.this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onSensorChanged(SensorEvent event){
Log.i(TAG, "onSensorChanged: " + event.values[0]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.i(TAG, "onAccuracyChanged:" + accuracy);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
and the Compass Plugin, which gets executed:
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginHandle;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.Bridge;
#CapacitorPlugin(name = "Compass")
public class Compass extends Plugin {
public static Bridge staticBridge = null;
#Override
public void load() {
staticBridge = this.bridge;
java.lang.System.out.println("Compass successfully started");
}
public static void onMagneticHeading(float magneticHeading){
Compass pushPlugin = Compass.getCompassInstance();
if (pushPlugin != null) {
pushPlugin.sendMagneticHeading(magneticHeading);
}
}
#PluginMethod()
public void getMagneticHeading(PluginCall call) {
String value = call.getString("value");
JSObject ret = new JSObject();
ret.put("magneticHeading", value);
call.resolve(ret);
}
public void sendMagneticHeading(float magneticHeading) {
JSObject data = new JSObject();
data.put("magneticHeading", magneticHeading);
notifyListeners("heading", data, true);
}
public static Compass getCompassInstance() {
if (staticBridge != null && staticBridge.getWebView() != null) {
PluginHandle handle = staticBridge.getPlugin("Compass");
if (handle == null) {
return null;
}
return (Compass) handle.getInstance();
}
return null;
}
}
How come you're extending an Activity instead of just using a plain class? If it's because you want access to a Context, just pass one in through the constructor (you have one when you create the Heading).
If it's because you want the onPause and onResume lifecycle callbacks, so you know when to register/unregister with the SensorManager, there's a couple of things you could do.
First you can just create some methods the activity can call during onPause/onResume:
class Heading(Context context) {
...
public void sleep() {
sensorManager.unregisterListener(this);
}
public void wake() {
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
}
class MainActivity extends BridgeActivity {
...
#Override
protected void onResume() {
super.onResume();
heading.wake();
}
#Override
protected void onPause() {
super.onPause();
heading.sleep();
}
}
The other approach is to make Heading implement DefaultLifecycleObserver, which basically lets you implement onResume and onPause etc like you're doing, and you make it observe the Activity's lifecycle, instead of the Activity having to manually call stuff to be like "hey onPause just happened". I'll just link the example page, but it basically covers what you're doing here (and the earlier, manual example too) as well as some more advanced stuff

How to get value from MainActivity?

So I have this main activity:
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private volatile boolean stopTask = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
public boolean getStopTask() {
return stopTask;
}
public void startMyTask(View view) {
stopTask = false;
TextView textView = findViewById(R.id.text_view);
MyTask myTask = new MyTask(10, textView);
new Thread(myTask).start();
}
public void stopMyTask(View view) {
stopTask = true;
}
}
I was told that I could access getStopTask() from MyTask by getting an instance of MainActivity and accessing that function directly.
I tried that, but I get an error: "Can't create handler inside thread Thread[Thread-6,5,main] that has not called Looper.prepare()".
Here's MyTask:
import android.widget.TextView;
public class MyTask implements Runnable {
int seconds;
TextView textView;
MyTask(int seconds, TextView textView) {
this.seconds = seconds;
this.textView = textView;
}
#Override
public void run() {
MainActivity mainActivity = new MainActivity();
for (int x = 0; x < seconds; x++) {
boolean stopTask = mainActivity.getStopTask();
if (stopTask)
break;
textView.setText(String.format("x: %s", x));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The error happens right after the app hits:
MainActivity mainActivity = new MainActivity();
How can I get the value of stopTask from MyTask?
I would turn boolean stopTask to static and use it instead of getStopTask() this way:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static boolean stopTask = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
/*
public boolean getStopTask() {
return stopTask;
}*/
public void startMyTask(View view) {
stopTask = false;
TextView textView = findViewById(R.id.text_view);
MyTask myTask = new MyTask(10, textView);
new Thread(myTask).start();
}
public void stopMyTask(View view) {
stopTask = true;
}
}
MyTask.java:
public class MyTask implements Runnable {
int seconds;
TextView textView;
MyTask(int seconds, TextView textView) {
this.seconds = seconds;
this.textView = textView;
}
#Override
public void run() {
//MainActivity mainActivity = new MainActivity();
for (int x = 0; x < seconds; x++) {
boolean stopTask = MainActivity.stopTask;
if (stopTask)
break;
textView.setText(String.format("x: %s", x));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Surface view Black Screen Home Button

i am developing one app where just show clouds walking through the screen using surface view everything gone good until push the Button "HOME BUTTON" so when i returned to my app just showing screen in black, the rest of the app works fine just is when you push the "Home Button"
Where is my Code for the surfaceView
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class mysurfaceview extends SurfaceView implements SurfaceHolder.Callback {
private mysurfaceviewThread bbThread = null;
private int xPosition = (getHeight()/2);
private int yPosition = (getHeight()/2);
private int posicion2 = (getWidth()/2)-40;
private int posicion3 = (getWidth()/4);
private int xDirection = 1;
public mysurfaceview(Context ctx,AttributeSet attrs){
super(ctx, attrs);
getHolder().addCallback(this);
}
public void doDraw(Canvas c){
Paint paint = new Paint();
paint.setColor(Color.WHITE);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.myimage);
c.drawColor(Color.WHITE);
c.drawBitmap(icon, xPosition, yPosition, new Paint());
c.drawBitmap(icon,posicion2,(getHeight()/2),new Paint());
c.drawBitmap(icon,posicion3,(getHeight()/2)+40,new Paint());
}
public void surfaceCreated(SurfaceHolder holder){
if (bbThread!=null) return;
bbThread = new mysurfaceviewThread(getHolder());
bbThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
}
public void surfaceDestroyed (SurfaceHolder holder){
bbThread.detener();
}
public class mysurfaceviewThread extends Thread{
private boolean corriendo,pausa;
private SurfaceHolder surfaceHolder;
public mysurfaceviewThread(SurfaceHolder surfaceHolder){
this.surfaceHolder = surfaceHolder;
}
public synchronized void pausar() {
pausa = true;
}
public synchronized void reanudar() {
pausa = false;
notify();
}
public void detener() {
corriendo = false;
if (pausa)
reanudar();
}
public void run(){
corriendo=true;
while(corriendo){
xPosition+=xDirection;
posicion2+=2;
posicion3+=1;
if(xPosition==getWidth()){
xPosition = -200; }
if(posicion2==getWidth()){
posicion2 = -200; }
if(posicion3==getWidth()){
posicion3 = -200; }
Canvas c = null;
try {
c = surfaceHolder.lockCanvas();
doDraw(c);
synchronized (surfaceHolder){
}
} finally {
if(c != null) surfaceHolder.unlockCanvasAndPost(c);}
synchronized (this) {
while (pausa) {
try {
wait();
} catch (Exception e) {
}
}
}
}
}
}
public mysurfaceviewThread getThread(){
return bbThread;
}
}
Here is the code for Activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class animadofondo2 extends Activity{
private mysurfaceview Clouds;
private mysurfaceview.mysurfaceviewThread CloudsThread;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sufeaviewfondo);
Clouds= (mysurfaceview ) findViewById(R.id.ViewsLaynubes);
}
#Override
protected void onPause() {
super.onPause();
Clouds.getThread().pausar();
Toast.makeText(this, "Pausa", Toast.LENGTH_SHORT).show();
}
#Override
protected void onRestart(){
super.onRestart();
Clouds.getThread().reanudar();
Toast.makeText(this, "Restart", Toast.LENGTH_SHORT).show();
}
#Override protected void onStart() {
super.onStart();
Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
}
#Override protected void onResume() {
super.onResume();
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
}
#Override protected void onStop() {
super.onStop();
Nubecitas.getThread().pausar();
Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
}
#Override protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed(){
Lamar(null);
finish();
}
public void Lamar (View view){
Intent i = new Intent(this, main.class);
startActivity(i);
}
}
Here is the XML for the layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.app.example.proyectsurface.mysurfaceview
android:id="#+id/ViewsLaynubes"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>

Implementing Music Across Activities

Problem: When I use the home button to close the app the music continues playing. So I manually close the app by killing the activity, the music stops... for a few seconds and then starts again (and this time a restart is in order to turn it off).
MusicService.class:
package com.MyApp.App;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MusicService extends Service implements
MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MusicService() {
}
public class ServiceBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.test_music);
mPlayer.setOnErrorListener(this);
if (mPlayer != null) {
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return START_STICKY;
}
public void pauseMusic() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
length = mPlayer.getCurrentPosition();
}
}
public void resumeMusic() {
if (mPlayer.isPlaying() == false) {
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic() {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
return false;
}
}
MainPage.class:
package com.MyApp.App;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
public class MainPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
Intent music = new Intent();
music.setClass(this, MusicService.class);
startService(music);
}
#Override
protected void onDestroy() {
super.onDestroy();
mServ.stopMusic();
}
#Override
protected void onPause() {
super.onPause();
mServ.pauseMusic();
}
#Override
protected void onStop() {
super.onStop();
mServ.stopMusic();
}
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder) binder).getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
void doBindService() {
bindService(new Intent(this, MusicService.class), Scon,
Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(Scon);
mIsBound = false;
}
}
}
(NOTE: I have taken excerpts from my app, so I may have forgotten imports in this code, but all imports are correctly included in the app.)
Fixed:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
doBindService();
Intent music = new Intent();
music.setClass(this, MusicService.class);
startService(music);
}
and
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
please red : onCreate, OnPause , OnResume

CursorLoader does not refresh data

I'm creating application to add movie data via external web service to internal database and display list of movies as the main activity in ListFragment, another activity is responsible for search function.
ListFragment mentioned above fetches data from database using LoaderManager. Also this fragment is retained using setRetainInstance(true).
Problem that I encounter is that when I navigate to search, add something to database, and go back to ListFragment by pressing Back Button its not refreshed i.e. added movie is not displayed.
A few important things:
I'm not using ContentProvider so I manually retrieve Cursor from my data base in onCreateLoaderMethod.
I'm using support library - I hope that all imports are proper (if someone could check).
ListFragment uses custom CursorAdapter as its view.
Here is the code:
package com.mp.movieplanner;
import android.app.Activity;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.mp.movieplanner.data.DataManager;
public class MovieListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<Cursor> {
public static String TAG = MovieListFragment.class.getSimpleName();
private OnMovieSelectedListener mCallback;
private DataManager mDataManager;
private MovieCursorAdapter mAdapter;
public interface OnMovieSelectedListener {
public void onMovieSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.i(TAG, "onAttach(Activity)");
mDataManager = ((MoviePlannerApp)activity.getApplication()).getDataManager();
try {
mCallback = (OnMovieSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnMovieSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate(Bundle)");
final int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "onActivityCreated(Bundle)");
super.onActivityCreated(savedInstanceState);
mAdapter = new MovieCursorAdapter(getActivity(), null, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "onStart()");
if (getFragmentManager().findFragmentById(R.id.movie_details_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach()");
mCallback = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
if (mCallback != null) {
mCallback.onMovieSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity()) {
#Override
public Cursor loadInBackground() {
return mDataManager.getMovieCursor();
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
mAdapter.swapCursor(null);
}
#Override
public void onPause() {
Log.i(TAG, "onPause()");
super.onPause();
}
#Override
public void onStop() {
Log.i(TAG, "onStop()");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
}
I would advise:
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
getLoaderManager().restartLoader(0, null, this);
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
getLoaderManager().initLoader(0, null, this);
}
try that

Categories