enter image description hereHey guys I'm at the end of my Java 1 class working on my project. We are making a memory/concentration game. My issue is that when I click the easy button for the next activity the app crashes. I have tried using fragments and activities and just can't seem to get it right. I have also tried using the layout I need on my main activity just to see if I could get it to display. Even then it just crashes on startup of the app. Any help would be appreciated.
Startup Screen activity.
package com.bignerdranch.android.memory;
import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class MemoryActivity extends Activity {
private Button mEasy;
private Button mMedium;
private Button mHard;
private CheckBox mSilence;
public MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.mkstartmusic);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
mEasy = (Button)findViewById(R.id.easy);
mEasy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent easy = new Intent(getApplicationContext(), EasyGame.class);
startActivity(easy);
}
});
mMedium = (Button)findViewById(R.id.medium);
mMedium.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
mHard = (Button)findViewById(R.id.hard);
mHard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
mSilence = (CheckBox)findViewById(R.id.silence);
mSilence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mSilence.isChecked()) {
player.pause();
} else if(mSilence.isChecked() == false) {
player.start();
}
}
});
}
#Override
protected void onStop() {
super.onPause();
if (player != null){
player.stop();
if (isFinishing()){
player.stop();
player.release();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.activity_memory, menu);
return true;
}
}
Second Activity (Easy option)
package com.bignerdranch.android.memory;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
public class EasyGame extends Activity {
private ImageButton buttOne;
private ImageButton buttTwo;
private ImageButton buttThree;
private ImageButton buttFour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
buttOne = (ImageButton)findViewById(R.id.ImageButton01);
buttOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttTwo = (ImageButton)findViewById(R.id.ImageButton02);
buttTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttThree = (ImageButton)findViewById(R.id.ImageButton03);
buttThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttFour = (ImageButton)findViewById(R.id.ImageButton04);
buttFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.activity_easy, menu);
return true;
}
}
This is the layout for the Easy option
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/easyback"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/easyback"
android:clickable="false"
android:duplicateParentState="false"
android:longClickable="false"
android:scaleType="centerCrop" />
<ImageButton
android:id="#+id/ImageButton04"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_below="#+id/ImageButton01"
android:layout_toRightOf="#+id/ImageButton01"
android:layout_toEndOf="#+id/ImageButton01"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton02"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_above="#+id/ImageButton04"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="22dp"
android:layout_marginEnd="22dp"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton03"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignTop="#+id/ImageButton04"
android:layout_toLeftOf="#+id/ImageButton04"
android:layout_toStartOf="#+id/ImageButton04"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:layout_marginTop="152dp"
android:layout_toLeftOf="#+id/ImageButton02"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
</RelativeLayout>
OK It's not the full crash log you posted but at the top of it I saw roidManifest.xml?. And It's sure that you didn't defined your EasyGame Activity in your androidmanifest.xml so add this line inside application tag,
<manifest package="com....." . . . >
<application . . . >
<activity
android:name=".EasyGame"
android:label="easygame">
</activity>
. . .
</application>
</manifest>
In addition you are trying to cast your ImageButton into Button consider fixing that as well.
Add code below to AndroidManfest
<activity
android:name=".EasyGame"
/>
its simple just add this line to your AndroidManifest
<activity android:name="Activity"/>
The logcat did mentioned that you need to declare your activity within the Android Manifest which you didn't. please read the logcat carefully as it really helps to find what went wrong.
OK, so I had tried all of your guys suggestions which I had were part of the issue, the final issue turned out to that I needed to add my images to the drawable-xhdpi. Thanks for all your help.
Related
Problem
I am creating music player using android studio.
Everything was fine until I added search filter to search songs.
Search filter returns the song right but when I click on searched result wrong music file is opened however the music name shown on player activity is right but the song played is first song of list every time .
Example
There are 4 song items named: A,B,C,D
When searched C ,filtered result C is shown. But when Clicked on it Song name C is shown but Song A is played.
This is really frustrating.
Main Activity.java
package com.example.musicplayer2;
import android.Manifest;
import android.content.Intent;
import android.icu.text.Transliterator;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static boolean shuffleBol = false;
static boolean loopBol = false;
ListView listView;
String[] items;
ArrayAdapter<String> myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission()
{
Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
displaySongs();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file)
{
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
if (files != null){
for (File singlefile : files)
{
if (singlefile.isDirectory() && !singlefile.isHidden())
{
arrayList.addAll(findSong(singlefile));
}
else
{
if (singlefile.getName().endsWith(".mp3") && !singlefile.getName().startsWith("."))
{
arrayList.add(singlefile);
}
}
}
}
return arrayList;
}
void displaySongs()
{
ArrayList<File> mysongs;
mysongs = findSong(Environment.getExternalStorageDirectory());
items = new String[mysongs.size()];
for (int i=0; i < mysongs.size(); i++)
{
items[i] = mysongs.get(i).getName().replace(".mp3","");
}
// ArrayAdapter<String> myAdapter;
myAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String songName = (String) listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),PlayerActivity.class)
.putExtra("songs",mysongs)
.putExtra("songname",songName)
.putExtra("position",position));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem = menu.findItem(R.id.search_view);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
myAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
main activity.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<ListView
android:id="#+id/listViewSong"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:padding="8dp"
>
</ListView>
</RelativeLayout>
PlayerActivity.java
package com.example.musicplayer2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import static com.example.musicplayer2.MainActivity.loopBol;
import static com.example.musicplayer2.MainActivity.shuffleBol;
public class PlayerActivity extends AppCompatActivity {
ImageView btnplay,btnnext,btnprev,btnshuffle,btnloop;
TextView txtsname,txtstart,txtstop;
SeekBar seekmusic;
String sname;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList<File> mySongs;
Thread updateseekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Player");
btnprev = findViewById(R.id.btnprev);
btnnext = findViewById(R.id.btnnext);
btnplay = findViewById(R.id.playbtn);
btnshuffle = findViewById(R.id.btnshuffle);
btnloop = findViewById(R.id.btnloop);
txtsname = findViewById(R.id.txtsn);
txtstart = findViewById(R.id.txtstart);
txtstop = findViewById(R.id.txtstop);
seekmusic = findViewById(R.id.seekbar);
// if a media player is already running then.
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
}
Intent i = getIntent();
Bundle bundle = i.getExtras();
mySongs = (ArrayList)bundle.getParcelableArrayList("songs");
String songName = i.getStringExtra("songname");
position = bundle.getInt("position",0);
txtsname.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString());
sname = mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
mediaPlayer.start();
updateseekbar = new Thread()
{
#Override
public void run() {
int totalDuration = mediaPlayer.getDuration();
int currentPosition = 0;
while (currentPosition<totalDuration)
{
try {
sleep(500);
currentPosition = mediaPlayer.getCurrentPosition();
seekmusic.setProgress(currentPosition);
}
catch (InterruptedException | IllegalStateException e)
{
e.printStackTrace();
}
}
}
};
seekmusic.setMax(mediaPlayer.getDuration());
updateseekbar.start();
seekmusic.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime = createTime(mediaPlayer.getCurrentPosition());
txtstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
// click Listener ON PLAY button
btnplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying())
{
btnplay.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
else
{
btnplay.setBackgroundResource(R.drawable.pause);
mediaPlayer.start();
}
}
});
// click Listener ON next button
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (shuffleBol && !loopBol){
position=getRandom((mySongs.size()));
}
else if(!shuffleBol && !loopBol)
{
position=((position+1)%mySongs.size());
}
Uri u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
sname=mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer.start();
btnplay.setBackgroundResource(R.drawable.pause);
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
}
});
// click Listener ON previous button
btnprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (shuffleBol && !loopBol){
position=getRandom((mySongs.size()));
}
else if(!shuffleBol && !loopBol){
position=((position-1)<0)?(mySongs.size()-1):(position-1);
}
Uri u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
sname=mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer.start();
btnplay.setBackgroundResource(R.drawable.pause);
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
}
});
// click listener for shuffle btn
btnshuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (shuffleBol){
shuffleBol=false;
btnshuffle.setImageResource(R.drawable.shuffle_off);
}
else {
shuffleBol=true;
btnshuffle.setImageResource(R.drawable.shuffle_on);
}
}
});
// click listener for loop btn
btnloop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (loopBol){
loopBol=false;
btnloop.setImageResource(R.drawable.loop_off);
}
else {
loopBol=true;
btnloop.setImageResource(R.drawable.loop_on);
}
}
});
// next Listener ON song completion
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnnext.performClick();
}
});
}
public String createTime(int duration)
{
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10)
{
time+="0";
}
time+=sec;
return time;
}
private int getRandom(int i) {
Random random= new Random();
return random.nextInt(i+1);
}
}
PlayerActivity.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="wrap_content"
android:background="#drawable/bg"
android:orientation="vertical"
android:weightSum="10"
tools:context=".PlayerActivity"
android:baselineAligned="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="7"
android:gravity="center"
android:orientation="vertical"
tools:ignore="Suspicious0dp,UselessParent">
<TextView
android:id="#+id/txtsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="#string/song_name"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="italic">
</TextView>
<ImageView
android:id="#+id/imageview"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginBottom="8dp"
android:src="#drawable/logo">
</ImageView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp">
<SeekBar
android:id="#+id/seekbar"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:layout_marginBottom="40dp">
</SeekBar>
<TextView
android:id="#+id/txtstart"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="-17dp"
android:layout_toLeftOf="#+id/seekbar"
android:text="0:00"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp">
</TextView>
<TextView
android:id="#+id/txtstop"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="false"
android:layout_centerInParent="true"
android:layout_marginLeft="-14dp"
android:layout_marginRight="20dp"
android:layout_toRightOf="#+id/seekbar"
android:text="#string/_4_10"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp">
</TextView>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="98dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/playbtn"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:background="#drawable/pause" />
<ImageView
android:id="#+id/btnnext"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/playbtn"
android:background="#drawable/next" />
<ImageView
android:id="#+id/btnprev"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/playbtn"
android:background="#drawable/previous" />
<ImageView
android:id="#+id/btnshuffle"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toLeftOf="#+id/btnprev"
android:layout_marginTop="85dp"
android:layout_marginRight="35dp"
android:background="#drawable/shuffle_off"/>
<ImageView
android:id="#+id/btnloop"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/btnnext"
android:layout_marginTop="85dp"
android:layout_marginLeft="35dp"
android:background="#drawable/loop_off"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
In above image, you see that you are sending the position of filtered array and sending the songs list (mysongs) which is not filtered. That's why it's happening.
So you need to do is that either send the filtered array. Or add some logic to get the correct position from songs list. that's it.
if you can not figure out then let me know I will update appropriate logic.
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 have an app with many activities using intent. I have a sharedPreferences method for saving values.
I have a welcome screen that I set to display when the app launches (onCreate is called). In the same activity, I delete the sharePreferences method so when I reopen the app the welcome screen will launch again.
The problem is, when I change to another activity and back again to the main activity and press the exit button. When I launch the app again, it does not show the welcome screen. I think, the main activity is still running so, onPause(), onStop() and onDestroy() are never called. When I stay in the same activity (main) and press exit, it will call onDestroy() (that contains the erase sharedPreferences method).
I didn't set the finish() method. If I set that, every moved activity will call onDestroy in Main activity so the welcome screen will launch every move to that activity.
My mainactivity.java
package com.bani.latihan;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class Main extends AppCompatActivity {
RelativeLayout PopupScreen, layoutAsli;
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onDestroy(){
super.onDestroy();
SharedPreferences settings = getSharedPreferences("PreferencesWelcome", Context.MODE_PRIVATE);
settings.edit().remove("ditekan").apply();
}
#Override
public void onCreate(Bundle savedInstanceState) {
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.main);
Button btn1 =(Button)findViewById(R.id.button1);
final Button btn2 =(Button)findViewById(R.id.button2);
PopupScreen = (RelativeLayout)findViewById(R.id.PopupScreen);
layoutAsli = (RelativeLayout)findViewById(R.id.layoutAsli);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(Main.this, Intent2.class);
startActivity(intent2);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
moveTaskToBack(true);
finish();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Isi dewek cuk!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
EditText tvText = (EditText) findViewById(R.id.editText1);
SharedPreferences prefs = getSharedPreferences("Preferences", Context.MODE_PRIVATE);
if (prefs.contains("text")){
tvText .setText(prefs.getString("text", ""));
}
SharedPreferences prefs2 = getSharedPreferences("PreferencesWelcome", Context.MODE_PRIVATE);
if (prefs2.contains("ditekan")){
PopupScreen.setVisibility(View.INVISIBLE);
layoutAsli.setVisibility(View.VISIBLE);
}
}
public void dismisWelcomeMessageBox(View view) {
PopupScreen.setVisibility(View.INVISIBLE);
layoutAsli.setVisibility(View.VISIBLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPause() {
super.onPause();
EditText tvText = (EditText) findViewById(R.id.editText1);
Button btWelcome = (Button) findViewById(R.id.button_welcome);
SharedPreferences.Editor prefEditor = getSharedPreferences("Preferences", Context.MODE_PRIVATE).edit();
SharedPreferences.Editor prefEditor2 = getSharedPreferences("PreferencesWelcome", Context.MODE_PRIVATE).edit();
prefEditor.putString("text", tvText.getText().toString());
prefEditor2.putBoolean("ditekan", btWelcome.isPressed());
prefEditor.apply();
prefEditor2.apply();
}
}
My another activity code:
package com.bani.latihan;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
/**
* Created by Bani Burhanuddin on 21/02/2016.
*/
public class Intent2 extends AppCompatActivity {
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.intent);
Button btnnext = (Button) findViewById(R.id.button5);
Button btnhome = (Button) findViewById(R.id.button6);
Button btnback = (Button) findViewById(R.id.button7);
btnnext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Intent2.this, Intent3.class));
finish();
}
});
btnhome.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Intent2.this, Main.class));
finish();
}
});
btnback.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Intent2.this, Main.class));
finish();
}
});
CompoundButton toggle = (CompoundButton) findViewById(R.id.switch1);
final ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView2.setVisibility(View.GONE);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
imageView2.setVisibility(View.VISIBLE);
} else {
imageView2.setVisibility(View.GONE);
}
}
});
SharedPreferences prefs = getSharedPreferences("Preferences2", Context.MODE_PRIVATE);
if (prefs.contains("text2")) {
toggle.setChecked(prefs.getBoolean("text2", true));
}
}
#Override
public void onPause() {
super.onPause();
CompoundButton toggle = (CompoundButton) findViewById(R.id.switch1);
if (toggle.isChecked()) {
SharedPreferences.Editor editor = getSharedPreferences("Preferences2", MODE_PRIVATE).edit();
editor.putBoolean("text2", true);
editor.apply();
} else {
SharedPreferences.Editor editor = getSharedPreferences("Preferences2", MODE_PRIVATE).edit();
editor.putBoolean("text2", false);
editor.apply();
}
}
}
My Manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<!-- Splash screen -->
<activity
android:name="com.bani.latihan.splashscreen"
android:label="#string/app_name"
android:screenOrientation="sensor"
android:configChanges="keyboardHidden|orientation|screenSize"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Main activity -->
<activity
android:name="com.bani.latihan.Main"
android:screenOrientation="sensor"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
<!-- Intent2 activity -->
<activity
android:name=".Intent2"
android:screenOrientation="sensor"
android:noHistory="true"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
<!-- Intent3 activity -->
<activity
android:name=".Intent3"
android:screenOrientation="sensor"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
<!-- Intent4 activity -->
<activity
android:name=".Intent4"
android:screenOrientation="sensor"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
</application>
</manifest>
My main layout
<RelativeLayout
android:id="#+id/PopupScreen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#123456"
android:orientation="vertical"
android:layout_margin="16dp"
android:padding="16dp"
android:visibility="visible">
<TextView
android:id="#+id/welcome_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:text="#string/welcome"
android:textColor="#ddd333"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/welcome_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/welcome_title"
android:text="#string/welcome_message"
android:textColor="#0dff00"
android:textSize="18sp" />
<Button
android:layout_width="wrap_content"
android:id="#+id/button_welcome"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_gravity="bottom"
android:background="#3b978d"
android:onClick="dismisWelcomeMessageBox"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/ok"
android:textColor="#fff" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/layoutAsli"
android:visibility="invisible"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/hello_world"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText1"
android:layout_below="#+id/hello_world"/>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"
android:src="#drawable/imageview"
android:layout_gravity="center" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/button1"
android:layout_marginTop="111dp"
android:layout_centerHorizontal="true"
android:layout_gravity="left|bottom" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
android:id="#+id/button2"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="59dp"
android:layout_gravity="right|bottom" />
</FrameLayout>
</RelativeLayout>
</RelativeLayout>
I got ur problem. Currently u are using the MoveTaskToBack . It will not destroy the activity ,it just move back in ativity stack after that u finish
activity. So its not calling other callback methods. It always call onDestroy
Use either moveTasktoBack or finish. Dont use both, it will confusing.
I have just started programming in Android and I couldn't get the result on clicking button that I expected. Here s the code.
.java file
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class AndroidLove extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_love);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_love, menu);
return true;
}
public void onButtonClicked(View view) {
TextView textView=(TextView)findViewById(R.id.textView1);
textView.setVisibility(View.VISIBLE);
}
}
.xml file
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".AndroidLove" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="104dp"
android:text="#string/hello_world"
android:visibility="invisible" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:text="#string/Button"
android:onClick="onButtonClicked" />
strings.xml file
<resources>
<string name="app_name">AndroidLove</string>
<string name="action_settings">Settings</string>
<string name="hello_world">First Line\nSecond Line\nThird Line</string>
<string name="Button">Get Lyrics</string>
On clicking the button, the following text should be displayed but its not displayed:-
First Line
Second Line
Third Line
Please help
Edit: Maybe and probably your binding is wrong about onclick, try below code instead of top. Put that code into your onCreate method.
Button button= (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView=(TextView)findViewById(R.id.textView1);
textView.setVisibility(View.VISIBLE);
}
});
You need to get the string value from the strings.xml file which can be acheived by
String st =getResources.getString(R.string.hello_world);
Then set that to textview by
textView.setText(st);
Try this code:
public class AndroidLove extends Activity {
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_love);
textView=(TextView)findViewById(R.id.textView1);
button1 = (Button)findViewByid(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
// do your stuff here
String _data =getResources.getString(R.string.hello_world);
textView.setText(_data);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Hello my name is Hernan so and I am a Android Developer. I make this question because I need insert a google map into a custom dialog I already have my dialog working ok but when I am adding the google map it throws an error in code. This is my code.
Java Code:
package com.sigetdriver.view.popup;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.sigetdriver.R;
public class InsertarDestinoPopup {
private GoogleMap googleMap;
private Context context;
public Dialog dialog;
private Button btnCerrar;
public void dialog(Context _context) {
context = _context;
dialog = new Dialog(_context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup_destino);
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
try {
// Loading map
initilizeMap();
pintarMapa();
} catch (Exception e) {
e.printStackTrace();
}
btnCerrar = (Button) dialog.findViewById(R.id.btnCerrar);
btnCerrar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap(); // *******ERROR HERE*******
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(context,
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
private void pintarMapa() {
googleMap.setMyLocationEnabled(true); // false to disable
}
}
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/btnCerrar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cerrar" />
</LinearLayout>
I dont know if it is the best way to make a dialog or showing a map into dialog, please I need solve this thanks in advance.
Hernan
You can also use activity as a dialog.Here you can do all normal activity methods.
XML Coding
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Java Coding
public class Map extends FragmentActivity {
private View rootView;
GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(0));
setContentView(R.layout.map);
this.rootView=findViewById(R.id.map_view);
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
map = mySupportMapFragment.getMap();
}
#SuppressLint("NewApi")
#Override
public boolean onTouchEvent(MotionEvent event) {
Rect rect = new Rect();
rootView.getHitRect(rect);
if (!rect.contains((int)event.getX(), (int)event.getY())){
setFinishOnTouchOutside(false);
return true;
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
}
return true;
}
}
Manifest File
Here You change the activity as dialog.
<activity
android:name="com.example.mapindialog.Map"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:screenOrientation="landscape"
android:theme="#android:style/Theme.Dialog" >
</activity>
base on your png, it seems like you're using support v4 package,in this case you'll need to replace getFragmentManager with getSupportFragmentManager