I am fairly new to android development and as my first app I want to make a flashlight app. So the first steps I want to do is to make a button in the center such that it changes it's text to "ON" and "OFF" alternately after every click. I made the java code but it Android studio gives me this error: '#Override' not applicable to field. Here is my java code:
package com.danielfernandzz.flashlight;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
public boolean switchState = false;
Button switchbutton = (Button) findViewById(R.id.Switch);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Switched(View v){
if(!switchState){
switchState = true;
switchbutton.setText("OFF");
}else{
switchState = false;
switchbutton.setText("ON");
}
}
}
And here is my xml code (in case you need it):
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.danielfernandzz.flashlight.MainActivity">
<Button
android:id="#+id/Switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="8dp"
android:onClick="Switched"
android:text="ON"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
I tried commenting out the #Override and no error came. But when I ran the app, it crashed so I assume that the app crashed because #Override wasn't there?
I don't understand why this is happening to me, I have seen other questions but their error is something different.
NOTE: I am using the latest version Android Studio 3.0
try this
1.move you switchbutton = (Button) findViewById(R.id.Switch); inside your onCreate() method
2.place #Override before onCreate()
sample code
public class MainActivity extends AppCompatActivity {
public boolean switchState = false;
Button switchbutton ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchbutton = (Button) findViewById(R.id.Switch);
}
public void Switched(View v){
if(!switchState){
switchState = true;
switchbutton.setText("OFF");
}else{
switchState = false;
switchbutton.setText("ON");
}
}
}
As according #Jerrol you can place the #Override before onCreate. There is no need to place it before variable initialization.Could you give us the crash log that you are getting after removal.
Related
Ive tried copying the instance of main class to sub class but it says cant find symbol
Below are the code ive tried
Here is my HTML CODE
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#drawable/shiva" >
<Button
android:id="#+id/bp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="509dp"
android:layout_marginBottom="91dp"
android:text="#string/play" />
<Button
android:id="#+id/bp1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="94dp"
android:layout_marginTop="94dp"
android:layout_marginEnd="410dp"
android:layout_marginBottom="91dp"
android:text="#string/pause" />
<Button
android:id="#+id/bp2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="95dp"
android:layout_marginTop="95dp"
android:layout_marginEnd="308dp"
android:layout_marginBottom="93dp"
android:text="#string/stop" />
</android.widget.RelativeLayout>
Here is my java code
package com.example.rd;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button Play;
Button Pause;
Button Stop;
MediaPlayer md;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Play = findViewById(R.id.bp);
Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
md = MediaPlayer.create(getApplicationContext(), R.raw.rudhra);
md.start();
}
MediaPlayer md;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Pause = findViewById(R.id.bp1);
Pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
md = MediaPlayer.create(getApplicationContext(), R.raw.rudhra);
md.pause();
}
MediaPlayer md;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState);
setContentView(R.layout.activity_main);
Stop = findViewById(R.id.bp2);
Stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
md = MediaPlayer.create(getApplicationContext(), R.raw.rudhra);
md.stop();
}
});
};
});
}
});
}
Here im getting 2 errors
1.cannot find symbol
super.onCreate(savedInstanceState);
2.cannot find symbol
super.onCreate(savedInstanceState);
As im beginner can any1 help me to fix it
Learn about Activity Lifecycle first. According to it an activity has only one oncreat() method in its lifecycle. Here you seem to have added two oncreate().
Remove the second one and your code will work.
I'm now trying something with a youtube custom player. I'm trying to have it play a video containing a playlist of a certain game's original soundtracks.
The thing is, everything was done by the book (again), yet I still have this concurring problem of force stopping every time I tried to open the APK. Here are the code :
XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical"
tools:context=".MainActivity">
<view
android:id="#+id/YoutubePlayView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Play Video" />
</LinearLayout>
Java :
package my.videoplayerapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
YouTubePlayerView mYoutubePlayerView;
Button PlayVidButton;
YouTubePlayer.OnInitializedListener mOnInitializedListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting.");
PlayVidButton = findViewById(R.id.buttonPlay);
mYoutubePlayerView = findViewById(R.id.YoutubePlayView);
mOnInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Log.d(TAG, "onClick: Initialization Done.");
youTubePlayer.loadVideo("DBToMwdYBME");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.d(TAG, "onClick: Initialization Failed.");
}
};
PlayVidButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Initializing Youtube Player.");
mYoutubePlayerView.initialize((YoutubeVidPlayerConfig.getApiKey()), mOnInitializedListener);
Log.d(TAG, "onClick: Initialization Done.");
}
});
}
}
Logcat, linked : https://drive.google.com/open?id=1w5TfCIfyCWCrOZmrjb0lzTpndoQc2SJ0
I'm trying to actually be able to play the video through the button, I know the method of playing the next video or even playing sequence of videos, I just don't know why it keeps on crashing as I speak right now...
Any help would be appreciated in advance!
You have a view with the id of "YoutubePlayView" but your class is called "YoutubePlayerView". Change one of them and it should work (well it shouldn't force close at this spot).
Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.
Code:
MainActivity.java
package com.leuchtstein.flashlight;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView) ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void triggerlight(View view) {
if (stat == false) {
text.setText("ON");
stat = true;
} else {
text.setText("OFF");
stat = false;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.leuchtstein.flashlight.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/desc_textview"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
app:layout_constraintHorizontal_bias="0.95"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="triggerlight"
android:text="Turn on/off"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.387" />
Well, thanks in advance.
Don't call
TextView text = (TextView) findViewById(R.id.textView) ;
in initialisation, rather call it in onCreate() method.
This is because Android first initializes the script, and calls onCreate only when setContentView() has been called and it has set up the button, &c. Thus findViewById(int id) can't find anything yet.
Put
text = (TextView) findViewById(R.id.textView);
in onCreate() and put
TextView text;
in initialisation instead.
Try this :
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
You haven't provided the logcat or any other any ifo, but one thing I can see here that could go wrong is this :
TextView text = (TextView) findViewById(R.id.textView);
Change your code to look like this :
public class MainActivity extends AppCompatActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
So the difference is, you assign a value to your TextView using findViewById, after you have have called setContentView().
All view assignments should be only done after setContentView()is called in activities because that is where you set your root view and when you call findViewById(), the system looks up a view with an id in the root view.
First of all let me tell you that I am a beginner at this... I started to try developing apps about a week ago.
When I start my app on a real device it starts normally But when I click the button "oneplus" it says that app isn't responding...
this app adds one number to the number in TextView .Earlier I faced same problem and thought it was because of fragments.So i removed them and made a very simple app But still the problem persists
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="0"
android:id="#+id/num"
android:textSize="70sp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginTop="100dp"
android:text=" + 1 "
android:textSize="50sp"
android:id="#+id/plusone"
android:onClick="onClick"
/>
</RelativeLayout>`
mainactivity.java
package com.example.tjain.oneup;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View v) {
final TextView number = (TextView) findViewById(R.id.num);
int original = Integer.parseInt(number.getText().toString());
int newnum = original + 1;
number.setText(newnum);
}
}
I am facing this error in other apps too. Maybe I am repeating my mistake . Please point it out. Thanks in advance
As I doubt for two scenario in your onClick for Exception
NumberFormat Exception
ResourceNotFound Exception
For First,
try
{
int original = Integer.parseInt(number.getText().toString());
}catch(Exception ex)
{
ex.printStacktrace();
}
For Second,
Because int is not a argument for TextView's setText (only if its not a part of String resource id), as it will find with resource id not accepting as String value. and obvious Resource Not Found exception
you have to convert int to String,
number.setText(String.valueOf(newnum));
What I would recommend doing is adding your UI elements at the class level of your activity so you have one TextView object and one Button object, that way you only have to search for the resource once and you can add a click listener to the button itself like this:
public class MainActivity extends Activity{
private TextView mNumberTextView;
private Button mOnePlusButton;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNumberTextView = findViewbyId(R.id.num);
mOnePlusButton = findViewbyId(R.id.plusone);
mOnePlusButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
int original = Integer.parseInt(mNumberTextView.getText().toString());
mNumberTextView.setText(original + 1);
}
});
}
}
Edit: Since you're still new at this, it's always a good idea to check the documentation.
You should use
number.setText(+newnum);
instead
number.setText(newnum);
I just started learning android development using android studio, and i finished the "Starting another activity" , I tried practicing on what I've learned by changing the code a bit and messing with it.
(The tutorial was about displaying text sent by another activity)
So i added a seekBar in order to change the text size. After i send the text to another activity using an intent it crashes, but if i remove the seekBar listener , it works fine.
DisplayMessageActivity.java:
package com.keddy.myfirstapp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayMessageActivity extends ActionBarActivity {
public SeekBar _seekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Getting the intent received by some other activity
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//Text view initialization
final TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
//Showing text on screen
setContentView(textView);
_seekbar = (SeekBar)findViewById(R.id.seekBar1);
_seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Toast.makeText(getApplicationContext(),"Progress Changing",Toast.LENGTH_SHORT).show();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"Started Tracking",Toast.LENGTH_SHORT).show();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"Progress Stopped Changing",Toast.LENGTH_SHORT).show();
}
});
}
I included the onCreate() method only , because that was the only thing I've changed.
activity_display_message.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.keddy.myfirstapp.DisplayMessageActivity">
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/seekBar1"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:indeterminate="false"
android:max="100"
/>
</RelativeLayout>
I've searched around and saw the reason was NullPointerException , but i dont know how to fix it , since i have no experience with Java nor Android Development.
if you find a solution please provide:
Code Example
How to avoid it again
Why did it happen
Any help whatsoever will be appreciated.
Change
setContentView(textView);
to
setContentView(R.layout.activity_display_message);
You must setContentView(...) and after add _seekbar = (SeekBar)findViewById(R.id.seekBar1);
The reason is you are adding textview in your Content
i.e. setContentView(textview);
Your activity is unable to find seekbar1 view. This is the reason why your app is crashing.
Instead of adding textview in Javacode add in xml and use it same way you are using seekbar, and change setContentView(textView) to setContentView(R.layout.your_xml_file_name);