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);
Related
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).
Following a tutorial, I did set up onClick-Listeners before.
Now I am trying to make a simple app for listening to one stream, but my onClickListener doesn't do anything.
I created a new very simple app in android studio 3.3.2 to find out what is happening. I guess it is something very basic.
package com.example.musicplay;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_main);
final Button play_button = findViewById(R.id.play_button);
Log.i("Button found","this one: " + play_button.getText());
play_button.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the play button is clicked on.
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "A click happened!", Toast.LENGTH_SHORT).show();
}
});
setContentView(R.layout.activity_main);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play_button"/>
</LinearLayout>
The toast message should appear when the button is clicked, but nothing happens.
You are calling setContentView twice. This will replace the view hierarchy set up by the first call. Remove the second call to setContentView.
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.
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 have seen many people telling that you can set setContentView outside the oncreate method, but I didn't find anywhere an example. Now when I try to use setContentView, my app just crashes. Here is my source code:
AlarmActivity.java:
package com.alarm.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
public class AlarmActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button buton = new Button(this);
buton.setId(101);
buton.setText("New alarm");
buton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
RelativeLayout layout1 = new RelativeLayout(this);
layout1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout1.addView(buton);
setContentView(layout1);
Button nou =(Button)findViewById(101);
nou.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
New_ala nou1=new New_ala();
nou1.nou_alarma();
}
});
}
}
New_ala.java:
package com.alarm.example;
public class New_ala extends AlarmActivity{
public void nou_alarma() {
setContentView(R.layout.timepicker);
}
}
TimePicker.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TimePicker
android:id="#+id/timePicker"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true">
<Button
android:id="#+id/picker_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Save">
</Button>
<Button
android:id="#+id/picker_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel">
</Button>
</LinearLayout>
</LinearLayout>
On more detail, I can use setContentView(R.layout.timepicker) inside the oncreate method without any problems so the problem is that setContentView isn't working properly inside the New_ala.java class. Can anyone help me?
The code after setting the intent:
AlarmActivity:
package com.alarm.example;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class AlarmActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this, NewAlarmActivity.class));
}
}
NewAlarmActivity:
package com.alarm.example;
import android.os.Bundle;
public class NewAlarmActivity extends AlarmActivity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timepicker);
}
}
You can call setContentView any time you are running on the event (UI) thread. Be aware that when you do, any fields you initialized by calling findViewById will need to be reset.
The best way to do that is to have multiple activities: instead of nou1.nou_alarma();, create an intent and start a new activity with the new layout.
startActivity(new Intent(this, NewAlarmActivity.class));
And in the onCreate method of NewAlarmActivity, set the content view to R.layout.timepicker
The setContentView() method can be called only once per activity. If you want to completely change the layout at some point you should either go for ViewFlipper or have 2 layouts in the activity and show only one of them at given time by calling view.setVisibility(View.GONE); and view.setVisibility(View.VISIBLE); respectively.