Android Studio app crashes when i try to test it - java

The app crashes when i tried to test, i am using fragments to create the app:
App crashed
I have this in audioFragment.java:
package amaguenet.com.reproductorxassidas;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.media.MediaPlayer;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class audioFragment extends Fragment {
// variable declaration
private ListView mainList;
private MediaPlayer mp;
private final String[] listContent = {"Ahonzubilahi Min Mayli", "Ajabani Khayru Baqin", "Ajabani Rabbu Sama", "Ala Innani Usni",
"Alal Muntaqa Khayril Baraya"};
private final int[] resID = {R.raw.ahonzu_bilahi_min_mayli, R.raw.ajabani_khayru_baqin, R.raw.ajabani_rabbu_sama,
R.raw.ala_innani_usni, R.raw.alal_muntaqa_khayril_baraya};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_audio, container, false);
// Initializing variables
mp = new MediaPlayer();
mainList = (ListView) v.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listContent);
mainList.setAdapter(adapter);
mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
playSong(position);
}
});
return v;
}
public void playSong(int songIndex) {
// Play song
mp.reset();// stops any current playing song
mp = MediaPlayer.create(getActivity().getApplicationContext(), resID[songIndex]);// create's
// new
// mediaplayer
// with
// song.
mp.start(); // starting mediaplayer
}
#Override
public void onDestroy() {
super.onDestroy();
mp.release();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
}
#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);
}
public interface OnFragmentInteractionListener {
}
}
And this in a in fragment_audio (the layout):
<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="amaguenet.com.reproductorxassidas.audioFragment"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
Can some helps with this, i am using Fragments in Android Studio?

You can use getIdentifier() method, here is a simple example:
private final int resID = getContext().getResources().getIdentifier(direction, "raw", PACKAGE_NAME);
direction - string with your file name f.e: "ahonzu_bilahi_min_mayli"
PACKAGE_NAME - is your package name

Related

How do I change my Activity's fragment container's background with a custom dialog with code?

Fairly new to Android and I am trying to do some background color changes. Basically I have a main activity that only has a FrameLayout in it's xml. When the activity is created it opens up a fragment for my program. I have a menu item that when clicked pops a dialog box with 3 seekbars(red, green, blue). I want to change the background color to whatever the seekbars position is. I have all the code finished for the seekbars and I know it works on a simple app I created. For reasons to me unknown my app fails when i try to open the dialog box. What is the proper way to set this up in the Main Activity? I want the user to be able to change the background color whenever they want. All my fragment layouts are transparent. This is the tutorial I have been working off of. http://android-er.blogspot.com/2009/08/change-background-color-by-seekbar.html Any advice would be great. I think my problem is I do not fully understand how to access my main_activity's FrameLayout from with-in my MainActivity java class.
activity_main.xml
<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"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#e3a153">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentView"></FrameLayout>
</LinearLayout>
Color_seekbar_selecter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/myScreen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Change color"
/>
<SeekBar
android:id="#+id/mySeekingBar_R"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_G"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
<SeekBar
android:id="#+id/mySeekingBar_B"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="255"
android:progress="0"/>
</LinearLayout>
menu_main.xml
<menu 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"
tools:context=".MainActivity">
<item android:id="#+id/menu_settings"
android:title="Green" />
<item android:id="#+id/menu_red"
android:title="Red" />
<item android:id="#+id/menu_blue"
android:title="Blue" />
<item android:id="#+id/menu_tan"
android:title="Tan" />
</menu>
MainActivity.java
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends ActionBarActivity {
//public CategoryFragment categoryFragment;
//public RecipeFragment recipeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null)
{
CategoryFragment categoryFragment = new CategoryFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentView, categoryFragment, "categoryFrag")
.commit();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPostResume() {
super.onPostResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.menu_green:
}
return super.onOptionsItemSelected(item);
}
}
I have tried for hours to figure this out, but I just don't know where to put what.
This is the code from the example that I found in the link posted above.
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class SeekColorActivity extends Activity {
private int seekR, seekG, seekB;
SeekBar redSeekBar, greenSeekBar, blueSeekBar;
LinearLayout mScreen;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mScreen = (LinearLayout) findViewById(R.id.myScreen);
redSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_R);
greenSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_G);
blueSeekBar = (SeekBar) findViewById(R.id.mySeekingBar_B);
updateBackground();
redSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
greenSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
blueSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
updateBackground();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private void updateBackground()
{
seekR = redSeekBar.getProgress();
seekG = greenSeekBar.getProgress();
seekB = blueSeekBar.getProgress();
mScreen.setBackgroundColor(
0xff000000
+ seekR * 0x10000
+ seekG * 0x100
+ seekB
);
}
}
categoryFragment.java
package com.example.mikesgamerig.finalproject;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class CategoryFragment extends Fragment {
private ArrayList<String> categoryNameArrayList;
private ArrayAdapter<String> adapter;
private AlertDialog alertDialog;
private AlertDialog alertDialogDelete;
private EditText categoryEditText;
private String getCategoryName;
private List<Category> cats;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//create view
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
//initialize all variables and widgets
inflater = getLayoutInflater(savedInstanceState);
alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setView(inflater.inflate(R.layout.dialog_add_category, null));
alertDialogDelete = new AlertDialog.Builder(getActivity()).create();
alertDialogDelete.setView(inflater.inflate(R.layout.dialog_delete_category, null));
Button buttonAddCategory = (Button) rootView.findViewById(R.id.addCategoryButton);
ListView categoryListView = (ListView) rootView.findViewById(R.id.list);
//Array list to store names of categories
categoryNameArrayList = new ArrayList<String>();
//List of Category Objects
cats = Category.listAll(Category.class);
getCategoryNames();
//iterate through the CategoryList and attach to the ArrayList
//create adapter and fill the listView with all the name of categories
adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.label, categoryNameArrayList);
categoryListView.setAdapter(adapter);
//set OnClick listener for the add category Button.
// This calls another method that will open a custom dialog box
buttonAddCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DisplayAddCategoryDialogBox();
}
});
//set an onItemLongClick listener for the ListView.
//First have to setLongClickable to true.
//the OnItemLongClick listener will call a method to open a custom Dialog to delete a category.
categoryListView.setLongClickable(true);
categoryListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
DeleteCategory(i);
return true;
}
});
//opens up a new fragment with a list of recipes for the specific category.
categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = categoryNameArrayList.get(i);
RecipeFragment fragment = new RecipeFragment();
fragment.SetTitleName(name);
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.fragmentView, fragment)
.addToBackStack(null).commit();
}
});
return rootView;
}
//This method will Display a custom add category Dialog Box.
public void DisplayAddCategoryDialogBox(){
//Show the Dialog box to enter a new category name.
alertDialog.show();
categoryEditText = (EditText) alertDialog.findViewById(R.id.categoryEditText);
Button saveCategoryDialogBtn = (Button) alertDialog.findViewById(R.id.saveBtn);
Button cancelDialogButton = (Button) alertDialog.findViewById(R.id.cancelBtn);
saveCategoryDialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCategoryName = categoryEditText.getText().toString();
//Log.d("STRING VALUE:", getCategoryName);
Category test = new Category(getCategoryName);
test.save();
categoryNameArrayList.add(test.getName());
//Log.d("added Value: ", test.getName());
adapter.notifyDataSetChanged();
alertDialog.hide();
}
});
cancelDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.hide();
}
});
}
//this method will display a custom Delete Category Alert Dialog box.
public void DeleteCategory(final int i)
{
alertDialogDelete.show();
Button noBtn = (Button) alertDialogDelete.findViewById(R.id.noBtn);
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialogDelete.hide();
}
});
Button yesBtn = (Button) alertDialogDelete.findViewById(R.id.yesBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tempString = categoryNameArrayList.get(i);
//Log.d("VALUE OF STRING= ", tempString);
categoryNameArrayList.remove(i);
for (Category category : cats) {
String name = category.getName();
if (name.equals(tempString)) {
category.delete();
}
}
adapter.notifyDataSetChanged();
alertDialogDelete.hide();
}
});
}
//Filles the Array
public void getCategoryNames()
{
for(Category category : cats)
{
String name = category.getName();
categoryNameArrayList.add(name);
}
}
}

Trouble getting video to play on Recyclerview

I have a VideoView inside a RecyclerView. I want to eventually have a list of videos to play on a Recyclerview. I decided to start out with one video, then move on to having multiple videos. I can't seem to get one video to play in the Recyclerview. When I start the app on my phone, all I get is the progress bar. The onPrepared function is never called for some reason. Here's my code.
RecyclerActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.RecyclerView;
public class RecyclerActivity extends ActionBarActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(this);
mRecyclerView.setAdapter(mAdapter);
}
#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_recycler, 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);
}
}
MyAdapter.java
import android.app.ProgressDialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context context;
private ProgressDialog progressDialog;
private MediaController mediaControls;
public static class ViewHolder extends RecyclerView.ViewHolder{
public VideoView mVideoView;
public ViewHolder(View v){
super(v);
mVideoView = (VideoView) v.findViewById(R.id.video_view);
}
}
public MyAdapter(Context mContext) {
context = mContext;
mediaControls = new MediaController(context);
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Random Video");
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_video_view, parent,false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
try{
holder.mVideoView.setMediaController(mediaControls);
holder.mVideoView.setVideoURI(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.kitkat));
} catch (Exception e){
Log.e("Error", e.getMessage());
e.printStackTrace();
}
holder.mVideoView.requestFocus();
holder.mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
progressDialog.dismiss();
holder.mVideoView.start();
}
});
}
#Override
public int getItemCount() {
return 1;
}
my_video_view.xml
<FrameLayout 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"
android:layout_gravity="center"
tools:context=".RecyclerActivity">
<VideoView
android:id="#+id/video_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
activity_recycler.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=".RecyclerActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Any ideas? The video file is a .3gp file by the way. Thanks!
I was stuck on this for far too long as well. After searching everywhere and still struggling I looked at my older code base with the exact same code bar one difference. The VideoView was having its height programatically set. android:layout_height="wrap_content" doesn't appear to make a height adjustment.
So I used a self made utility method to get the screen width and set the height to be in a 16:9 ratio like so. (Maybe just set your height and width to some arbitrary numbers first to see if it's the issue)
public static int getScreenWidth(Context c) {
int screenWidth = 0; // this is part of the class not the method
if (screenWidth == 0) {
WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
}
return screenWidth;
}
Then all it takes is to set the VideoViews height as such
holder.mVideoView.getLayoutParams().height = getScreenWidth(mContext) * 9 /16;
NOTE: My width is set to match_parent, so wrap_content may also fail there too.
Hope this helps.
the problem is with
android:layout_width="wrap_content"
android:layout_height="wrap_content"
before the video is loaded their values are 0 to solve this problem can use set minHeight to 1dp and layout_width to match_parent
and this will do the trick, you do not need fixed width and height.

Sendind data from one activity to another

Hi i'm new here and firstly i want to apologise for my language .I wanted to create my first android app ,and im curently struggle with some issues.
MainActivity ,which represents my main screen containing two buttons and spinner.In spinner user can choose one text file and after selection spinnerActivity should be triggered(screen with opened text file).I found problem because not every record from spinner trigger activity with text file that i want (one trigger file that i want and other trigger screen with empty TextView). Here is layout of spinnerActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView2"
android:layout_width="199dp"
android:layout_height="89dp"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="nie dziala" />
<TextView
android:id="#+id/proximityTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Code of MainACtivity
package com.example.myapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends ActionBarActivity implements OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button click=(Button)findViewById(R.id.button2);
click.setOnClickListener(new View.OnClickListener(){ //nowy actionlistener
#Override
public void onClick(View v) {
Intent activitylauncher=new Intent(MainActivity.this,AboutActivity.class);
//tworzenie nowej intencji Create an intent for a specific component.
startActivity(activitylauncher);
}
});
final Button click2=(Button)findViewById(R.id.button1);
click2.setOnClickListener(new View.OnClickListener() { //nowy actionlistener
#Override
public void onClick(View v) {
Intent activitylauncher=new Intent(MainActivity.this,RandomActivity.class);
//tworzenie nowej intencji Create an intent for a specific component.
startActivity(activitylauncher);
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.recipie_array, android.R.layout.simple_spinner_item);
// Specify the layut to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// String i=Integer.toString(pos);
if(pos==1)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
intent3.putExtra("txt",(pos));
startActivity(intent3);
}
if(pos==2)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
startActivity(intent3);
}
if(pos==1)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
startActivity(intent3);
}
}
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#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);
}
}
and the code of spinneractivity
package com.example.myapp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class SpinnerActivity extends ActionBarActivity implements SensorEventListener {
TextView proxText;
SensorManager sm;
Sensor proxSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
//proximitymeter
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
proxSensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
proxText=(TextView)findViewById(R.id.proximityTextView);
sm.registerListener(this,proxSensor,SensorManager.SENSOR_DELAY_NORMAL);
Intent intent3 = getIntent();
int value = intent3.getIntExtra("txt", 0);
//finish();
if (value==1)
{
open("przepis1.txt");
}
if (value==2)
{
open("przepis2.txt");
}
if (value==3)
{
open("przepis3.txt");
}
}
public void open(String name){
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,name);
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader bufor = new BufferedReader(new FileReader(file));
String line;
while ((line = bufor.readLine()) != null) {
text.append(line);
text.append('\n');
}
bufor.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.textView2);
//Set the text
tv.setText(text);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.spinner, 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);
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
//proxText.setText(String.valueOf(event.values[0]));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
Can someone look at this and help me with finding bugs?Thanks
Position starts form 0, I think problem is with the conditions,
You can write like this-
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Intent intent = new Intent(MainActivity.this, SpinnerActivity.class);
intent.putExtra("txt", pos + 1);
startActivity(intent);
}

YouTubeFragmentPlayer Android App - Only Black Box appearing

I am trying to build sample Android app in which the main activity contains a YouTubePlayerFragment. I get no errors with my implementation, but when I run this app on an AVD or my phone, the fragment for the YouTubePlayerFragment is just a black box. No video loads.
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.activity_main, 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();
}
}
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
<?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">
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youTubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
I don't think you need to create a newInstance(). The instance is created in your xml. And when you are in onCreateView that is a specific instance already.
So you should be able to replace these lines
YouTubeFragment ytf = newInstance();
ytf.init();
With
this.init();
Or more simply
init();
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>

OnLongClickListener - not getting fired + android

I have this OnLongClickListener which is not getting fired. I think I have setup everything correctly and it has worked with a contextmenu before but right now it's not firing and the log is not even giving me any error.
I really hope you can give me any ideas. It is probably a silly mistake somewhere.
package fragments;
import interfaces.AsyncTaskCompleteListener;
import java.util.List;
import com.example.slidingmenu.R;
import dialog.EditDialog;
import services.GetRequest;
import model.Post;
import adapter.PostAdapter;
import android.os.Bundle;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class HomeFragment extends Fragment implements AsyncTaskCompleteListener, View.OnLongClickListener {
private ListView mainListView;
private GetRequest service;
private ProgressDialog dialog;
private ActionMode mActionMode;
public HomeFragment() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedIntanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
mainListView = (ListView) rootView.findViewById(R.id.mainListView);
mainListView.setOnLongClickListener(this);
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please wait...");
service = new GetRequest(this);
service.execute();
dialog.show();
registerForContextMenu(mainListView);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch(item.getItemId()) {
case R.id.edit:
Log.d("edit", "pressed");
FragmentManager fragmentManager = getFragmentManager();
EditDialog editDialog = new EditDialog();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.add(android.R.id.content, editDialog).addToBackStack(null).commit();
mode.finish();
return true;
default:
return false;
}
}
};
#Override
public boolean onLongClick(View v) {
Toast.makeText(getActivity(), "PRESSED", Toast.LENGTH_SHORT).show();
Log.d("hey", "pressed");
if(mActionMode != null) {
return false;
}
mActionMode = getActivity().startActionMode(mActionModeCallback);
mainListView.setSelected(true);
return true;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Toast.makeText(getActivity(), "Refresh!", Toast.LENGTH_SHORT).show();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please wait while refreshing...");
dialog.show();
service = new GetRequest(this);
service.execute();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTaskComplete(List<Post> posts) {
PostAdapter adapter = new PostAdapter(getActivity(), R.layout.listview_item_row, posts);
LayoutInflater inflater = (LayoutInflater)getActivity().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View header = (View)inflater.inflate(R.layout.listview_header_row, null);
if(mainListView.getHeaderViewsCount() == 0) {
mainListView.addHeaderView(header);
}
mainListView.setAdapter(adapter);
if(dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public void onTaskComplete(String result) {
// TODO Auto-generated method stub
}
}
Here is the xml file where I have my ListView:
<?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="match_parent" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainListView"
android:longClickable="true"
android:clickable="true"
></ListView>
</LinearLayout>
You are attaching a listener to the entire view instead of each row. I'm not sure why nothing is being fired, but those touch events are probably being intercepted by other views.
Instead of ListView.setOnLongClickListener(), you should use ListView.setOnItemLongClickListener().
Here is the link for the Android Docs for this method.
Since you are registerForContextMenu for your listview already. setOnLongClickListener is not longer needed. What you needs is onCreateContextMenu method and onContextItemSelected.
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
// create menu item here
}
#Override
public boolean onContextItemSelected(MenuItem item){
// do your long click listener here
}

Categories