What i want to do is to add a spinner and a button, in spinner 2 songs are placed when i selected a song it plays and same as for other one but when i run this code it will do nothing just display a spinner and button and i only select a song and when i clicked a play button it do no respond.
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public int soundSelection;
MediaPlayer mp;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
btn=(Button)findViewById(R.id.button1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.soundEntries, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (soundSelection) {
case 1:
if (mp != null && mp.isPlaying())
mp = MediaPlayer.create(MainActivity.this, R.raw.bewafa);
mp.start();
mp.setVolume(100,100);
mp.setLooping(true);
Toast t = Toast.makeText(MainActivity.this,"bewafa",Toast.LENGTH_LONG);
t.show();
break;
case 2:
// if(mp.isPlaying())
mp = MediaPlayer.create(getApplicationContext(), R.raw.dildobaa);
mp.start();
Toast th = Toast.makeText(getApplicationContext(), "dildobaa", Toast.LENGTH_LONG);
th.show();
break;
}
}
});
}
/*Spinner Functions*/
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
soundSelection=(Integer)parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
#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);
}
}
This is the Xml code:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Spinner
android:layout_width="wrap_content"
android:entries="#array/soundEntries"
android:layout_height="wrap_content"
android:id="#+id/spinner1">
</Spinner>
<Button
android:layout_width="wrap_content"
android:text="Play"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:id="#+id/button1" />
This is Strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string-array name="soundEntries">
<item>bewafa</item>
<item>dildobaa</item>
</string-array>
Do below changes to your code:
implement AdapterView.OnItemSelectedListener:
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener {
Change switch cases to 0 and 1. (The count starts with 0)
Comment out the line: if (mp != null && mp.isPlaying())
Change onItemSelected() callback method to:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
soundSelection = pos;
}
Related
Because the class is somewhat old, and the IDE changed so much, i'm struggling a bit trying to do the same steps of the class.
I have created my Intent and i can send it by clicking on the ListView Item. Then it switches activities from the MainActivity to the DetailActivity. Yet when the DetailActivity is displayed (using DetailActivityFragment) the toolbar disappears. I compared XML's and made some improvements but now the toolbar isn't populated like the previous toolbar. The activity also "fills" the notification bar (the bar that extends to the drawer).
Question is, what am I doing wrong and what can i do to replicate the MainActivity toolbar to the new DetailActivity?
MainActivity.java
package com.example.diomonogatarilaptop.sunshine;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Something", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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;
}
if (id == R.id.action_refresh) {
MainActivityFragment.FetchWeatherTask weatherTask = new MainActivityFragment.FetchWeatherTask();
weatherTask.execute("Buraca");
return true;
}
return super.onOptionsItemSelected(item);
}
}
DetailActivity.java:
package com.example.diomonogatarilaptop.sunshine;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container_detail, new DetailActivityFragment())
.commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_detail);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, 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);
}
public static class DetailActivityFragment extends Fragment {
TextView textView;
public DetailActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent =getActivity().getIntent();
View rootView =inflater.inflate(R.layout.fragment_detail, container, false);
if(intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
textView= (TextView) rootView.findViewById((R.id.detail_text));
textView.setText(forecastStr);
}
return rootView;
}
}
}
Activity_detail.xml:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container_detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.sunshine.app.DetailActivity"
tools:ignore="MergeRootFrame">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_detail"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_detail" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Content_detail.xml:
<fragment 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:id="#+id/fragment"
android:name="com.example.diomonogatarilaptop.sunshine.DetailActivity$DetailActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_detail"
/>
Fragment_detail.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: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="com.example.diomonogatarilaptop.sunshine.DetailActivity$DetailActivityFragment"
tools:showIn="#layout/activity_detail">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="New Text"
android:id="#+id/detail_text"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Some ScreenCaptures from debugging on my mobile:
MainActivity
DetailActivity Where the bug happens
I am following the Android Development tutorials on Udacity and I have came across a problem in the app that I can't seem to work out how to fix.
I have created the new activity, and the Intent works perfectly fine in loading the new activity, the only problem is that when the second activity loads there is no actionbar that loads. Any Ideas?
MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
}
DetailActivity.java
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text))
.setText(forecastStr);
}
return rootView;
}
}
}
activity_detail.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.sunshine.app.DetailActivity"
tools:ignore="MergeRootFrame" />
content_detail.xml
<fragment 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:id="#+id/fragment"
android:name="com.example.turnergasoil.sunshine.DetailActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_detail" />
fragment_detail.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: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="com.example.turnergasoil.sunshine.DetailActivityFragment"
tools:showIn="#layout/activity_detail">
<TextView
android:id="#+id/detail_text"
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
When changing the XML and Java file to include the toolbar, the frame layout and toolbar now overlap each other. See below.
When changing the XML and Java file to include the toolbar, the frame layout and toolbar now overlap each other. See below.
Should add Toolbar into the second activity's layout, and
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
EDIT
activity_detail.xml should be like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.sunshine.app.DetailActivity"
tools:ignore="MergeRootFrame">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="#dimen/actionbar_height"
android:background="?attr/colorPrimary" />
</FrameLayout>
OK so I'm trying to make a settings activity, and that's not going well. Right now it only has one setting which is displayed as a Spinner.
I'm successfully saving the selected item to SharedPreferences, but I can't figure out how to make the activity apply the saved data to the View on start.
I am trying to apply whatever int is paired with the key "spinnerPosition" to Spinner.setSelection();, but the default value in sharedPreferences.getInt(String key, int defValue); overrides it.
Here is the file sharedPreferences saves to:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string>com.example.SettingsActivity$1#277a0f70</string>
<string name="finalWeighType">Pounds</string>
<int name="spinnerPosition" value="1" />
</map>
And some Logcat:
04-04 18:21:13.849: D/spinner Listener(9027): ok
04-04 18:21:15.035: D/onPause(9027): Saving Settings
04-04 18:21:15.035: I/System.out(9027): iSavedPos: 9
04-04 18:21:19.030: W/InputEventReceiver(9027): Attempted to finish an input event but the input event receiver has already been disposed.
04-04 18:21:19.036: I/System.out(9027): iSavedPos 9
04-04 18:21:19.037: D/Do(9027): running
04-04 18:21:19.037: D/pos def(9027): ok
04-04 18:21:19.404: D/spinner Listener(9027): ok
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class SettingsActivity extends ActionBarActivity{
private Spinner selectWeighType;
SharedPreferences weighTypeLoader;
String finalWeighType;
public static final String DEFAULT = "UNSET";
public int itemSelectedPosition;
SharedPreferences getItemSavedPosition;
private int itemSavedPosition;
private boolean populated = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// add items to selectWeighType Spinner
populateSelectWeighType();
// add listener to selectWeightType Spinner
selectWeighTypeListener();
weighTypeLoader = getSharedPreferences("weightType", Context.MODE_PRIVATE);
//Load saved data.. hopefully
getItemSavedPosition = getSharedPreferences("weightType", Context.MODE_PRIVATE);
itemSavedPosition = getItemSavedPosition.getInt("spinnerPosition", 9);
System.out.println("iSavedPos " + itemSavedPosition);
}
#Override
protected void onResume() {
super.onResume();
do {Log.d("Do", "running");
switch (itemSavedPosition) {
case 0:
selectWeighType.setSelection(0);
Log.d("pos 0", "ok");
break;
case 1:
selectWeighType.setSelection(1);
Log.d("pos 1", "ok");
break;
case 2:
selectWeighType.setSelection(2);
Log.d("pos 2", "ok");
break;
default:
selectWeighType.setSelection(1);
Log.d("pos def", "ok");
}
populated = true;
}while(populated == false);
}
public void populateSelectWeighType(){
selectWeighType = (Spinner) findViewById(R.id.weight_type_spinner);
ArrayAdapter<CharSequence> selectWeighTypeAdapter =
ArrayAdapter.createFromResource(this,
R.array.weight_type_select,
android.R.layout.simple_spinner_item);
selectWeighTypeAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
selectWeighType.setAdapter(selectWeighTypeAdapter);
}
public void selectWeighTypeListener(){
selectWeighType = (Spinner) findViewById(R.id.weight_type_spinner);
selectWeighType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String weighTypeSelected = parent.getItemAtPosition(position).toString();
itemSelectedPosition = position;
int rowID = (int) id;
Log.d("spinner Listener", "ok");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#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_settings, 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();
Toast weightTypeToast;
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences commitWeighSetting = getSharedPreferences("WeightType", Context.MODE_PRIVATE);
SharedPreferences.Editor editSetting = commitWeighSetting.edit();
editSetting.putString("WeighType",
selectWeighType.getSelectedItem().toString());
editSetting.putInt("spinnerPosition", itemSelectedPosition);
editSetting.commit();
Log.d("onPause", "Saving Settings");
System.out.println("iSavedPos: " + itemSavedPosition);
}
}
Layout xml
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.SettingsActivity"
>
<TextView
android:id="#+id/weight_type_setting_title"
android:text="#string/weight_type_setting_title"
android:textSize="18dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/weight_type_spinner"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center_horizontal"
android:layout_row="0"
android:layout_column="0"
android:layout_columnWeight="0"
android:layout_marginLeft="16dp" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/weight_type_spinner"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/weight_type_setting_title"
android:layout_toEndOf="#+id/weight_type_setting_title"
android:layout_row="0"
android:layout_column="1"
android:spinnerMode="dropdown"
android:layout_columnWeight="0"
android:layout_marginRight="16dp"
android:layout_gravity="center_horizontal" />
</GridLayout>
You're trying to read spinnerPosition value from SharedPreferences instance with name spinnerPosition, while saving spinnerPosition value for SharedPreferences with name WeightType. You should either read the spinnerPosition value from SharedPreferences instance with name WeightType or save it to the SharedPreferences instance with name spinnerPosition.
I am trying to build sample Android app in which the main activity contains several fragments, including a YouTubePlayerFragment. I get no errors with my implementation, but when I run the app in an emulator or on my phone, the main activity is completely blank and unresponsive. The app works fine if I remove the fragment containing the YouTube player.
Any help is greatly appreciated.
Here is my code:
YouTubeFragment.java
package androidsample.example.com.fragments1;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class YouTubeFragment extends YouTubePlayerFragment implements YouTubePlayer.OnInitializedListener {
// TODO: Rename and change types and number of parameters
public static YouTubeFragment newInstance() {
YouTubeFragment fragment = new YouTubeFragment();
return fragment;
}
private void init(){
initialize(DeveloperKey.DEVELOPER_KEY, this);
}
public YouTubeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_you_tube, container, false);
YouTubeFragment ytf = newInstance();
ytf.init();
//inside fragment use getFragmentManager instead of getFragmentSupportManager
getFragmentManager().beginTransaction()
.add(R.id.youTubePlayer, ytf)
.commit();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getActivity(), "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
}
fragement_you_tube.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="androidsample.example.com.fragments1.YouTubeFragment"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/youTubePlayer">
</FrameLayout>
</LinearLayout>
MainActivity.java
package androidsample.example.com.fragments1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="androidsample.example.com.fragments1.Frag2"
android:id="#+id/fragment"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="androidsample.example.com.fragments1.Frag1"
android:id="#+id/fragment2"
android:layout_below="#+id/fragment"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp" />
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="androidsample.example.com.fragments1.YouTubeFragment"
android:id="#+id/fragment3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="68dp" />
</RelativeLayout>
With some help, I have a working version of this (problems with target SDK 21, using 19):
YouTubeFailureRecoveryActivity.java
package androidsample.example.com.fragments2;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
//String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
String errorMessage = "custom ERror MessAgE";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer player,
boolean wasRestored) {
// TODO Auto-generated method stub
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
// TODO Auto-generated method stub
return (YouTubePlayerFragment) getFragmentManager().findFragmentById(
R.id.youtube_fragment);
}
}
MainActivity.java
package androidsample.example.com.fragments2;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class MainActivity extends YouTubeFailureRecoveryActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
#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);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
How do i set a text field in Eclipse to work in conjunction with an item selected in a Spinner? EXAMPLE- If the user selects the second item (out of lets say 3 in the drop down menu) i want them to be able to use the text field to the fight of the spinner to set a value to that item selected. Think of it like a translation tool. If the person selects English out of the menu of languages and then types in an english word (in the text field) i want it to be able to CONVERT that to whatever they chose in the second spinner (Spanish) once they hit the "convert" button.
I apologize if this question seems more in need of a java/eclipse lesson then code help, but i appreciate any help at all :)
MainActivity
package com.overworldinnovations.datatool;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.os.Build;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Spinner spinner1, spinner2;
private Button buttonConvert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
//List<String> list = new ArrayList<String>();
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner2.setOnItemSelectedListener(new CustomOnItemSelectedListener());
/*list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);*/
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.overworldinnovations.datatool.MainActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonConvert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:text="Convert" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Please Select A Data Type To Be Converted"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner1"
android:layout_marginTop="45dp"
android:entries="#array/type_arrays"
android:prompt="#string/data_prompt" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="60dp"
android:entries="#array/type_arrays"
android:prompt="#string/data_prompt" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/spinner2"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="numberSigned" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner1"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="numberSigned" />
</RelativeLayout>
strings
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Data Tool</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="convert">Convert</string>
<string name="data_tool_is_an_application_that_converts_binary_to_decimal_d">Data Tool is an application that converts Binary to Decimal :D</string>
<string name ="data_prompt">Choose a data type</string>
<string-array name = "type_arrays">
<item >Decimal</item>
<item >Binary</item>
<item >Hexidecimal</item>
</string-array>
</resources>
CustomOnItemSelectedListener
package com.overworldinnovations.datatool;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Well, i cannot tell you about your conversion thingy but i will tell you how to listen to do something based on a selected spinner entry and how to manipulate textfields. The rest you have to code :-)
Here comes a class that implements a spinner, and does something based on the selected option in the spinner. It can be made very different too but this should explain things easy.
public class MyClass extends Fragment implements AdapterView.OnItemSelectedListener {
// Your Spinner
public Spinner spinner;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.tab2, container, false);
// Customize from here
final TextView textview = (TextView) view.findViewById(R.id.textView);
final Button button = (Button) view.findViewById(R.id.btn_calculate);
setSpinnerContent( view );
// attach an OnClickListener
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Integer selectedOption = spinner.getSelectedItemPosition();
if (selectedOption==0) {
myString = "Option 1 selected";
}
if (selectedOption==1) {
myString = "Option 2 selected";
}
if (selectedOption==2) {
myString = "Option 3 selected";
}
textview.setText(myString);
}
}
);
return view;
}
private void setSpinnerContent( View view )
{
spinner = (Spinner) view.findViewById( R.id.spinner );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter( adapter );
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // ItemsSelected
//An alternate way to listen to the selected items
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The spinner gets content from an String XML resource like this:
<string-array name="planets_array">
<item>Euro</item>
<item>US-Dollar</item>
<item>Yen</item>
</string-array>
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String val = spinner.getSelectedItem().toString();//Getting Value of Selected Item
txtPerc.setText(val);//TextView
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
Do Something Like This.. And please Clear Your Question.
Hope Its Help..