How to get current displayed image position? - java

I want to display the images front and back ward. Like Windows Picture and Fax Viewer This is my code:
package com.my.imagechange;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class ImageChangeDemo extends Activity
{
/** Called when the activity is first created. */
// private Gallery gallery;
private ImageView imgView;
int i=0;
int j=6;
ImageButton btrt,btlt;
Button bt1,bt2;
private Integer[] Imgid ={R.drawable.androidlogo,R.drawable.androids, R.drawable.cool, R.drawable.cupcake2009, R.drawable.donut2009, R.drawable.eclair2009};
int imglength=Imgid.length;
//System.out.println(imglength);
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagechange);
System.out.println(imglength);
btlt=(ImageButton)findViewById(R.id.bt1);
btrt=(ImageButton)findViewById(R.id.bt2);
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageResource(Imgid[0]);
btlt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int choice1=j--;
switch(choice1)
{
case 5:imgView.setImageResource(Imgid[5]);
break;
case 4:imgView.setImageResource(Imgid[4]);
break;
case 3:imgView.setImageResource(Imgid[3]);
break;
case 2:imgView.setImageResource(Imgid[2]);
break;
case 1:imgView.setImageResource(Imgid[1]);
break;
}
}
});
btrt.setOnClickListener(new View.OnClickListener()
{ #SuppressWarnings("unused")
#Override
public void onClick(View v)
{
int choice2=i++;
switch(choice2)
{
case 1:imgView.setImageResource(Imgid[1]);
break;
case 2:imgView.setImageResource(Imgid[2]);
break;
case 3:imgView.setImageResource(Imgid[3]);
break;
case 4:imgView.setImageResource(Imgid[4]);
break;
case 5:imgView.setImageResource(Imgid[5]);
break;
}
}
});
}}
It works forward fine, but when I click backward it doesn't work. Where did I make my mistake? Can anybody tell me?
Thanks in advance.

Please change like this
int choice1=--j;
Edit:
Here the problem is after execution of this code int choice1=j--; choice1 contain value 6, which is not in the switch case

Hi now the code works finely. My code is
package com.my.imagechange;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
public class ImageChange extends Activity
{
private Gallery gallery;
private ImageView imgView;
private ImageButton btlt,btrt;
private Integer[] Imgid= {
R.drawable.androidlogo, R.drawable.androids, R.drawable.cool, R.drawable.cupcake2009, R.drawable.donut2009, R.drawable.eclair2009};
int imglength=Imgid.length;
int img_position;
int img_minus;
int img_plus;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageResource(Imgid[0]);
btlt=(ImageButton)findViewById(R.id.bt1);
btrt=(ImageButton)findViewById(R.id.bt2);
System.out.println("----->"+imglength +"----->");
btlt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
btrt.setEnabled(true);
System.out.println("left button has been clicked");
System.out.println("position: "+img_position);
img_minus=--img_position;
System.out.println("minus:"+img_minus);
imgView.setImageResource(Imgid[img_minus]);
//imgView.setBackgroundDrawable(getResources().getDrawable(id));
if(img_minus==0)
{
btlt.setEnabled(false);
}
}
});
btrt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
btlt.setEnabled(true);
System.out.println("right button has been clicked");
System.out.println("position: "+img_position);
img_plus=++img_position;
System.out.println("plus: "+img_plus);
imgView.setImageResource(Imgid[img_plus]);
if(img_plus==5)
{
btrt.setEnabled(false);
}
}
});
} }
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#ffffff">
<ImageView android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/androidlogo"/>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom"
android:layout_gravity="fill_horizontal"
>
<ImageButton android:id="#+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/butleft"
android:layout_alignParentLeft="true">
</ImageButton>
<ImageButton android:id="#+id/bt2"
android:src="#drawable/butright"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true">
</ImageButton>
</RelativeLayout>
</LinearLayout>

Related

Search filter on list view returns wrong result on clicking

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.

Viewpager in Dialog?

I'm trying to have a dialog where you can click a "next" button to swipe right to the next screen. I am doing that with a ViewPager and adapter:
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(adapter);
However, I get a NullPointerException saying that pager is null. Why is this happening? Here is the Page Adapter class:
public class MyPageAdapter extends PagerAdapter {
public Object instantiateItem(ViewGroup collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
Here's my layout for the DIALOG:
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Let me know on how to avoid this situation.
PS: Each of the layouts that should be in the view pager look like this, just diff. text:
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/voice2"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="Slide 1!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_gravity="center"
android:textSize="50sp" />
</RelativeLayout>
Without Using Enum Class
You should call findViewById on dialog. so for that you have to add dialog before findViewById..
Like this,
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
After solving your null pointer exception the other problem's solution here, if you wont use enum class you can use below code...
MainActivity.java
package demo.com.pager;
import android.app.Dialog;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter(MainActivity.this);
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
pager.setAdapter(adapter);
dialog.show();
}
});
}
}
activity_main.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:id="#+id/activity_main"
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="demo.com.pager.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
MyPageAdapter.java
package demo.com.pager;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class MyPageAdapter extends PagerAdapter {
Context mContext;
int resId = 0;
public MyPageAdapter(Context context) {
mContext = context;
}
public Object instantiateItem(ViewGroup collection, int position) {
/* int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);*/
LayoutInflater inflater = LayoutInflater.from(mContext);
switch (position) {
case 0:
resId = R.layout.fragment_blue;
break;
case 1:
resId = R.layout.fragment_pink;
break;
}
ViewGroup layout = (ViewGroup) inflater.inflate(resId, collection, false);
collection.addView(layout);
return layout;
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
FragmentBlue.java
package demo.com.pager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
public class FragmentBlue extends Fragment {
private static final String TAG = FragmentBlue.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
return view;
}
}
fragment_blue.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:background="#4ECDC4">
</RelativeLayout>
voicedialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Please check and reply.
Using Enum Class
Try this code, This is working if any doubt ask again. Happy to help.
MainActivity.java
package demo.com.dialogdemo;
import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIComponents();
setupListeners();
}
private void setupUIComponents() {
button = (Button) findViewById(R.id.button);
}
private void setupListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialogItemDetails = new Dialog(MainActivity.this);
dialogItemDetails.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogItemDetails.setContentView(R.layout.dialoglayout);
dialogItemDetails.getWindow().setBackgroundDrawable(
new ColorDrawable(Color.TRANSPARENT));
ViewPager viewPager = (ViewPager) dialogItemDetails.findViewById(R.id.viewPagerItemImages);
viewPager.setAdapter(new CustomPagerAdapter(MainActivity.this));
dialogItemDetails.show();
}
});
}
}
activity_main.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">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dialog" />
</RelativeLayout>
ModelObject1.java
public enum ModelObject1 {
RED(R.string.red, R.layout.fragment_one),
BLUE(R.string.blue, R.layout.fragment_two);
private int mTitleResId;
private int mLayoutResId;
ModelObject1(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
CustomPagerAdapter.java
package demo.com.dialogdemo;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject1 modelObject = ModelObject1.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject1.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject1 customPagerEnum = ModelObject1.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
dailoglayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="ITEM IMAGES"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerItemImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" />
</RelativeLayout>
fragmentone.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="one"/>
</LinearLayout>

xml layout crashes on loading for android app

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.

Android passing data between activities [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello this is my first question so please forgive me if its in bad format, I have my main activity with three buttons,Button 1 and 2 lead to numberpickers that allow user to pick from numbers to set a background image. My problem is once they pick the color (rgb) i need it sent back to the main activity but then i want the button to immediately change to the background color they chose then they can go to button two and do the same thing, at the end of the process both button1 and 2 should be the colors they have chosen. Which i will then mix in button 3(which i havent at all started on) My main problem is i pick one then it set but then i pick the other one and it onCreates() and sets the other back to a default , So i somehow need to change the colors immedietly after the activity returns to the main activity my code is a bit ugly but ive just been trying to get it working then i was gonna go back and make it more efficient so my apologize
//MAIN CONTENT
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="50dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.MainActivity"
tools:showIn="#layout/activity_main">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/mixButton"
android:id="#+id/screen1MixerButton"
android:layout_below="#+id/screen1Button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="103dp" />
<Button
android:text="#string/Color1Text"
android:layout_width="162dp"
android:layout_height="188dp"
android:id="#+id/screen1Button1"
android:src="#ffffff"
android:background="#ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
<Button
android:text="#string/Color2Text"
android:layout_width="162dp"
android:layout_height="188dp"
android:id="#+id/screen1Button2"
android:background="#ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/screen1Button1" />
</RelativeLayout>
//COLORRPICKER1 ACTIVITY
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.ColorPicker1"
tools:showIn="#layout/activity_color_picker1">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/numberPicker1"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/numberPicker2"
android:orientation="horizontal"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/numberPicker2"
android:layout_alignParentEnd="true"
android:orientation="horizontal"
android:id="#+id/numberPicker3"></NumberPicker>
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="71dp"
android:id="#+id/surfaceView1"
android:layout_gravity="center_vertical"
android:background="#000000"
android:layout_below="#+id/numberPicker1"
android:layout_alignParentStart="true"
android:layout_marginTop="99dp"></SurfaceView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Color"
android:id="#+id/PickColor1"
android:layout_below="#+id/surfaceView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp" />
//COLORPICKER2 activity
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.ColorPicker2"
tools:showIn="#layout/activity_color_picker2">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/numberPicker1"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/numberPicker2"
android:orientation="horizontal"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/numberPicker2"
android:layout_alignParentEnd="true"
android:orientation="horizontal"
android:id="#+id/numberPicker3"></NumberPicker>
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="71dp"
android:id="#+id/surfaceView2"
android:layout_gravity="center_vertical"
android:background="#000000"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"></SurfaceView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Color"
android:id="#+id/PickColor2"
android:layout_below="#+id/surfaceView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp" />
</RelativeLayout>
//MAIN ACTIVITY
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;'
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MYTAG";
public static Button colorButton1;
private Button colorButton2;
private Button mixerButton;
int red1, green1, blue1,red2, green2, blue2 =255;
public static final int REQUEST_CODE= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "in onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//START SETTING UP BUTTONS
colorButton1 = (Button) findViewById(R.id.screen1Button1);
colorButton2 = (Button) findViewById(R.id.screen1Button2);
mixerButton = (Button) findViewById(R.id.screen1MixerButton);
//ONCLICKLISTENER FOR MULTIPLE BUTTONS
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.screen1Button1:
Log.i(TAG, "screen1Button1 TAPPED");
Toast.makeText(MainActivity.this, "screen1Button1 TAPPED", Toast.LENGTH_LONG).show();
Intent i1 = new Intent(MainActivity.this,ColorPicker1.class);
startActivityForResult(i1,REQUEST_CODE);
break;
case R.id.screen1Button2:
Log.i(TAG, "screen1Button2 TAPPED");
Toast.makeText(MainActivity.this, "screen1Button2 TAPPED", Toast.LENGTH_LONG).show();
Intent i2 = new Intent(MainActivity.this,ColorPicker2.class);
startActivity(i2);
Log.i(TAG, "BACKFROM1");
break;
case R.id.screen1MixerButton:
Log.i(TAG, "screen1MixerButton TAPPED");
Toast.makeText(MainActivity.this, "screen1MixerButton TAPPED", Toast.LENGTH_LONG).show();
Intent i3 = new Intent(MainActivity.this,MixedColorScreen.class);
startActivity(i3);
Log.i(TAG, "test value recieved" + red1);
Log.i(TAG, "test value recieved" + green1);
Log.i(TAG, "test value recieved" + blue1);
Log.i(TAG, "test value recieved" + red2);
Log.i(TAG, "test value recieved" + green2);
Log.i(TAG, "test value recieved" + blue2);
red1 = getIntent().getIntExtra("ColorPicker1_red",0);
green1 = getIntent().getIntExtra("ColorPicker1_green",0);
blue1 = getIntent().getIntExtra("ColorPicker1_blue",0);
red2 = getIntent().getIntExtra("ColorPicker2_red",0);
green2 = getIntent().getIntExtra("ColorPicker2_green",0);
blue2 = getIntent().getIntExtra("ColorPicker2_blue",0);
colorButton1.setBackgroundColor(Color.rgb(red1, green1, blue1));
colorButton2.setBackgroundColor(Color.rgb(red2, green2, blue2));
break;
}
}
};
colorButton1.setOnClickListener(onClickListener);
colorButton2.setOnClickListener(onClickListener);
mixerButton.setOnClickListener(onClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "in onCreateOptionsMenu");
// 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) {
Log.i(TAG, "in onOptionsItemsSelected");
// 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);
}
}
//colorpicker1 activity
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;
public class ColorPicker1 extends AppCompatActivity {
private static final String TAG = "MYTAG";
NumberPicker np, np2, np3;
SurfaceView img;
int red, green, blue ;
private Button pickColorButton1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pickColorButton1 = (Button) findViewById(R.id.PickColor1);
pickColorButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {;
Intent colorPick1 = new Intent(ColorPicker1.this,MainActivity.class);
colorPick1.putExtra("ColorPicker1_red",red);
colorPick1.putExtra("ColorPicker1_green", green);
colorPick1.putExtra("ColorPicker1_blue", blue);
//TRY
//MainActivity.colorButton1 = (Button) findViewById(R.id.screen1Button1);
//colorPick1.setBackgroundColor(Color.rgb(red, green, blue));
//END TRY
Log.i(TAG, "PUTING IN PUTEXTRAS VALUES RED BLUE GREEN =" + red +green + blue);
startActivity(colorPick1);
}
});
//STARTING LOGS ----------------------------------------------------------------------------
Log.i(TAG,"IN COLORPICKER1");
Toast.makeText(ColorPicker1.this, "IN COLORPICKER1", Toast.LENGTH_LONG).show();
//SETUP NUMBERPICKERS-----------------------------------------------------------------------
np = (NumberPicker) findViewById(R.id.numberPicker1);
np.setMinValue(0);
np.setMaxValue(255);
np.setWrapSelectorWheel(true);
np2 = (NumberPicker) findViewById(R.id.numberPicker2);
np2.setMinValue(0);
np2.setMaxValue(255);
np2.setWrapSelectorWheel(true);
np3 = (NumberPicker) findViewById(R.id.numberPicker3);
np3.setMinValue(0);
np3.setMaxValue(255);
np3.setWrapSelectorWheel(true);
//VALUE CHANGED LISTENERS-------------------------------------------------------------------
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
red = np.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
green = np2.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np3.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
blue = newVal;
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
//CLOSE-------------------------------------------------------------------------------------
}
}
//colorpicker2 activity
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;
public class ColorPicker2 extends AppCompatActivity {
private static final String TAG = "MYTAG";
NumberPicker np, np2, np3;
SurfaceView img;
int red, green, blue ;//might not need
private Button pickColorButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pickColorButton2 = (Button) findViewById(R.id.PickColor2);
pickColorButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ColorPicker2.this, "COlorPick2", Toast.LENGTH_LONG).show();
Intent colorPick2 = new Intent(ColorPicker2.this,MainActivity.class);
colorPick2.putExtra("ColorPicker2_red",red);
colorPick2.putExtra("ColorPicker2_green", green);
colorPick2.putExtra("ColorPicker2_blue", blue);
Log.i(TAG, "PUTING IN PUTEXTRAS VALUES RED BLUE GREEN =" + red + green + blue);
startActivity(colorPick2);
}
});
//STARTING log -----------------------------------------------------------------------------
Log.i(TAG, "IN COLORPICKER2");
Toast.makeText(ColorPicker2.this, "IN COLOPICKER2", Toast.LENGTH_LONG).show();
//SETTING UP NUMBER PICKERS ----------------------------------------------------------------
np = (NumberPicker) findViewById(R.id.numberPicker1);
np.setMinValue(0);
np.setMaxValue(255);
np.setWrapSelectorWheel(true);
np2 = (NumberPicker) findViewById(R.id.numberPicker2);
np2.setMinValue(0);
np2.setMaxValue(255);
np2.setWrapSelectorWheel(true);
np3 = (NumberPicker) findViewById(R.id.numberPicker3);
np3.setMinValue(0);
np3.setMaxValue(255);
np3.setWrapSelectorWheel(true);
//SETTING UP LISTENERS ---------------------------------------------------------------------
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
red = np.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
green = np2.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np3.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
blue = newVal;
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
//end --------------------------------------------------------------------------------------
}
}
For this you have to call startActivityForResult every time when you open ColorPicker1/2/3
Like this
Intent i1 = new Intent(MainActivity.this,ColorPicker1.class);
startActivityForResult(i1,REQUEST_CODE_COlLOR1);
//REQUEST_CODE must be greater than`0` so keep it `101` for example
and for ColorPicker2 keep REQUEST_CODE_COlLOR2 as 102 and for ColorPicker3 REQUEST_CODE_COlLOR2 as 103
and in your ColorActivity1/2/3 Call intent like this with respective request codes
Intent i = new Intent();
i.putExtra("color1", yourColor);
setResult(REQUEST_CODE_COlLOR1, i);
finish();
for in Second color activity
Intent i = new Intent();
i.putExtra("color2", yourColor);
setResult(REQUEST_CODE_COlLOR2, i);
finish();
In your mixed
Intent i = new Intent();
i.putExtra("color3", yourColor);
setResult(REQUEST_CODE_COlLOR3, i);
finish();
and then write OnActivityResult Override method in MainActivity to get the result from ColorPicker1/2/3
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_CODE_COlLOR1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your first button
yourColor = data.getExtras().get("color1");
}
}
if (requestCode == REQUEST_CODE_COlLOR2) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your second button
yourColor2 = data.getExtras().get("color2");
}
}
if (requestCode == REQUEST_CODE_COlLOR3) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your mixed color button
yourColor3 = data.getExtras().get("color3");
}
}
}

Can someone who uses android studio tell me what to do?

My app shuts down when clicking a button, anyone knows why? And if you fins any errors please tell me ;)This activity is about two buttons that when pressed show a TimePickerDialog and save the time.
Here's my code:
package app.alexdickson.com.workout1;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
ImageButton botoFlexio;
ImageButton botoAbdominals;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
int hourDefinitivaFlexio;
int minuteDefinitvaFlexio;
int hourDefinitivaAbs;
int minuteDefinitivaAbs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
botoFlexio = (ImageButton) findViewById(R.id.botoFlexio);
botoAbdominals = (ImageButton) findViewById(R.id.botoAbdominals);
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.botoFlexio:
botoFlexio.setBackgroundResource(R.drawable.flexioclicat);
showDialog(DIALOG_ID);
hourDefinitivaFlexio = hour_x;
minuteDefinitvaFlexio = minute_x;
break;
case R.id.botoAbdominals:
botoFlexio.setBackgroundResource(R.drawable.abdominalsclicat);
showDialog(DIALOG_ID);
hourDefinitivaAbs = hour_x;
minuteDefinitivaAbs = minute_x;
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID)
return new TimePickerDialog(Main2Activity.this, kTimePickerListener, hour_x, minute_x, true);
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x = hourOfDay;
minute_x = minute;
Toast.makeText(Main2Activity.this, hour_x + ": " + minute_x, Toast.LENGTH_LONG).show();
}
};
And here's my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoAbdominals"
android:background="#drawable/abdominals"
android:contentDescription="ImatgeAbdominals"
android:layout_marginTop="50dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoFlexio"
android:layout_gravity="top"
android:layout_marginTop="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/flexio"
android:contentDescription="ImatgeFlexio"
/>
Thanks for your help !!!!
Register listener with your Button after initialize it.
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
You need to set listeners to the ImageButtons.
For example:
#Override
protected void onCreate(Bundle savedInstanceState) {
....
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
}

Categories