Android App OnClick Crashing - java

So i have a simple app, just a menu with a few buttons, when a button is clicked you are brought to a new page. The page has a button, which when clicked, keeps changing its background image until it runs out of images (list of image names stored in strings), then you are brought back to the main menu. I can do this twice, then on the third attempt, if i click a button on the menu the app crashes. This doesnt happen on the emulator, only when i run it on my phone. I dont know why this is happening
package com.example.otapp;
import com.example.otapp.R.raw;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.media.MediaPlayer;
public class MainActivity extends ActionBarActivity {
public static String DPExtension;//Holds the letters dp
public String list;
public static int Screen_Height;//holds screen height
public static int Screen_Width;//holds screen width
public Intent intent;
public MediaPlayer audio;
public final static String EXTRA_MESSAGE = "com.example.otapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this code block is for getting the screen proportions
Display getdisplay = getWindowManager().getDefaultDisplay();
DisplayMetrics dispMetrics = new DisplayMetrics();
getdisplay.getMetrics(dispMetrics);
float densitydp = getResources().getDisplayMetrics().density;
float ScreenHeightdp = dispMetrics.heightPixels / densitydp;
float ScreenWidthdp = dispMetrics.widthPixels / densitydp;
//Below dimension value holders do not use pixel density
float ScreenHeightCheck = dispMetrics.heightPixels;
float ScreenWidthCheck = dispMetrics.heightPixels;
DPExtension = "dp";
Screen_Height = (int) ScreenHeightCheck;
Screen_Width = (int) ScreenWidthCheck;
//The printlns are so I can discern the outputs in LogCat
//System.out.println("Screen Height:" + Screen_Height);
//System.out.println("Screen Width:" + Screen_Width);
View Button1 = findViewById(R.id.Button01);
LinearLayout.LayoutParams params = (LayoutParams) Button1.getLayoutParams();
params.height = Screen_Height/3;
Button1.setLayoutParams(params);
View Button2 = findViewById(R.id.Button02);
Button2.setLayoutParams(params);
View Button3 = findViewById(R.id.Button03);
Button3.setLayoutParams(params);
View Button4 = findViewById(R.id.Button04);
Button4.setLayoutParams(params);
Button1.setOnClickListener(onClickListener);
Button2.setOnClickListener(onClickListener);
Button3.setOnClickListener(onClickListener);
Button4.setOnClickListener(onClickListener);
Button1.setBackgroundResource(getResources().getIdentifier("gettingup", "drawable", getPackageName()));
intent = new Intent(this, DisplayMessageActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
audio = MediaPlayer.create(MainActivity.this, raw.buttonsound);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// play sound
audio.start();
// do different things for each different button
switch(v.getId()) {
case R.id.Button01:
list = "Get Up";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button02:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button03:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
case R.id.Button04:
list = "Get Dressed";
intent.putExtra(EXTRA_MESSAGE, list);
startActivity(intent);
break;
}
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:background="#1E90FF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/Button01"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button_send"/>
<Button
android:id="#+id/Button03"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button2_send" />
<Button
android:id="#+id/Button04"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button3_send" />
<Button
android:id="#+id/Button02"
android:layout_width="match_parent"
android:layout_height="125dp"
android:text="#string/button4_send" />
</LinearLayout>
</ScrollView>

If the source above is formatted correctly, line 99, which is where the NullPointerException is thrown, is:
audio.start();
This means that audio is null. It is declared on line 83:
audio = MediaPlayer.create(MainActivity.this, raw.buttonsound);
Most likely what's happening is that the MediaPlayer.create is unable to located the raw.buttonsound. I'd debug at this line and verify that the MediaPlayer is failing to create the audio.

Try moving the definition of the onClickListener object into the onCreate method.
You can declare it as a member variable, but you should create the object and assign it to the field in onCreate()

Related

findViewById from different layout/xml file Android Studio

I'm trying to create a settings page for my app which has the radioGroup for 3 options to help users change the colour of the text in differrent layout/xml file. But in mysettings page I cant call the view from different layout, any idea?
Below are my codes:
Settings.Java
package com.example.sunny.mynote;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.EditText;
/**
* Created by Sunny on 19/04/2015.
*/
public class Settings extends Activity {
private RadioGroup RadioGroup1;
private RadioButton rdbRed, rdbBlue, rdbOrange;
private Button btnSave;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
RadioGroup1 = (RadioGroup) findViewById(R.id.RadioGroup1);
RadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.rdbRed)
{
Toast.makeText(getApplicationContext(), "choice: Red",
Toast.LENGTH_SHORT).show();
}
else if(checkedId == R.id.rdbBlue)
{
Toast.makeText(getApplicationContext(), "choice: Blue",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "choice: Orange",
Toast.LENGTH_SHORT).show();
}
}
});
rdbRed = (RadioButton) findViewById(R.id.rdbRed);
rdbBlue = (RadioButton) findViewById(R.id.rdbBlue);
rdbOrange = (RadioButton) findViewById(R.id.rdbOrange);
editText = (EditText) findViewById(R.id.editText);
btnSave = (Button)findViewById(R.id.btn_Save);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = RadioGroup1.getCheckedRadioButtonId();
if(selectedId == rdbRed.getId()) {
//textView.setText("You chose 'Sound' option");
} else if(selectedId == rdbBlue.getId()) {
//textView.setText("You chose 'Vibration' option");
} else {
//textView.setText("You chose 'Silent' option");
}
finish();
}
});
}
#Override
public void onBackPressed() {
}
}
and I want to FindViewbyID from this layout, an EditText from this view to be exactly
<?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">
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/noteText"
android:singleLine="false"
android:gravity="top"
android:inputType="textImeMultiLine"
android:layout_alignParentBottom="true" />
</RelativeLayout>
I think you can create an intent with extras like this:
Intent i=new Intent(context,Class.class);
i.putExtra("ColorChoice",color);
And then extract this data from your main class with:
intent.getStringExtra("ColorChoice");
You cannot do that in your Settings.java activity if your editText is not in this activity.
You can either use intent with putExtra and getExtra like #user3624383 mentioned. (more on this here)
Or a better way would be to use SharedPreferences to save your settings even if the user exits your app and return to it later

Access fragment from activity besides main activity

I have an existing application that I am trying to modify and could really use some help.
It is a chat application. The original flow of the application was as follows:
Launch-> Splash Screen Activity-> MainActivity (extending Actionbar Sherlock)
Once in the main activity the default fragment is the ChatRoomFragment. From there you can select different tabs and interact with the application.
What I would like to change about the flow to is the following:
Launch->Splash Screen Activity-> Terms of Service/Sign -> MainMenu->MainActivity
I have created the mainmenu layout to contain 4 buttons. Join, Search, Profile, Settings
Here is the problem. My Join button works fine, onClick simply triggers the intent to start MainActivity and and the chat room loads. From this screen you can access the different tabs and fragments within the application.
However, I now would like to have the "search" button set to open a dialog. With a editText field and a search button. Upon clicking search it should pass the search string to the PlacesSearchFragment and populate results.
I copied the code from within my application where this search is normally completed (inside the ChatRoomsFragment but it will not work from within my mainMenu Activity.
How do I start the new fragment from the menu activity??
Code Below:
menuActivity.java
package com.peekatucorp.peekatu;
//import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class menuActivity extends Activity implements ActionBar.TabListener {
Button b1;
Button b2;
Button b3;
EditText txtsearch;
final private static int DIALOG_LOGIN = 1;
final private static int DIALOG_FORGET = 2;
final private static int DIALOG_SEARCH = 3;
private android.app.FragmentTransaction ft;
#Override
public void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = this.getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
if(preferences.getString("Username", "").length()<=0 || preferences.getString("loggedin_user", "").length()<=0){
showDialog(DIALOG_LOGIN);
}
b1= (Button) this.findViewById(R.id.joinbutton);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(menuActivity.this, MainActivity.class);
menuActivity.this.startActivity(intent);
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("loadMain", "1");
editor.commit();
}
});
b2= (Button) this.findViewById(R.id.searchbutton);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showDialog(DIALOG_SEARCH);
}
}
);
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog dialogDetails = null;
switch (id) {
case DIALOG_LOGIN:
if(true){
....some code}
break;
case DIALOG_FORGET:
if(true){
...some code
}
break;
case DIALOG_SEARCH:
if(true){
LayoutInflater inflater = LayoutInflater.from(this);
View dialogview = inflater.inflate(R.layout.menusearch_layout, null);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
dialogbuilder.setTitle("Where ya headed?");
dialogbuilder.setView(dialogview);
dialogDetails = dialogbuilder.create();
}
}
return dialogDetails;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_LOGIN:
...some code
break;
case DIALOG_SEARCH:
final AlertDialog alertDialog3 = (AlertDialog) dialog;
final Button btnLocalsearch = (Button) alertDialog3
.findViewById(R.id.local_search);
final Button btnSearch = (Button) alertDialog3
.findViewById(R.id.btn_search);
final EditText txtsearch = (EditText) alertDialog3
.findViewById(R.id.txtsearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//showDialog(DIALOG_FORGET);
//alertDialog3.dismiss();
// TODO Auto-generated method stub
menuActivity m = com.peekatucorp.peekatu.menuActivity.this;
final TabInfo tab = com.peekatucorp.peekatu.menuActivity.this.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(txtsearch.getText().toString(),"1");
// fragment.setText(characters[position]);
// second, you push the fragment. It becomes visible and the up button is
// shown
m.pushFragment(tab, fragment);
}
});
}
mainmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="wrap_content"
android:layout_height="65dp"
android:layout_marginLeft="10dip"
android:src="#drawable/registration_banner3"
android:id="#+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Join Chat"
android:id="#+id/joinbutton"
android:layout_below="#+id/imageView"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/searchbutton"
android:layout_below="#+id/joinbutton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="55dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profile"
android:id="#+id/prfbutton"
android:layout_below="#+id/searchbutton"
android:layout_marginTop="72dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="#+id/searchbutton"
android:layout_alignStart="#+id/searchbutton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:id="#+id/settingsbutton"
android:layout_below="#+id/prfbutton"
android:layout_marginTop="51dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout android:id="#+id/footer"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#layout/footer_repeat"
android:layout_alignParentBottom="true">
</LinearLayout>
</RelativeLayout>
ChatRoomsFragment.java (WORKING FRAGMENT)
public class ChatRoomsFragment extends SherlockFragment implements OnItemSelectedListener{
String[] items;
List<String> list;
Spinner my_spin;
RadioButton mainRoom;
RadioButton customRoom;
RadioButton GPSRoom;
EditText privateRoom;
EditText GPSsearch;
TextView GPSaddress;
String selected_public;
Context contexxt;
ImageLoader imageLoader;
public AbstractTabStackNavigationActivity navact;
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
setRetainInstance(true);
final View v = inflater.inflate(R.layout.chatrooms_layout, container, false);
contexxt = v.getContext();
// setRetainInstance(true);
SharedPreferences preferences = v.getContext().getSharedPreferences("MyPreferences", this.getActivity().MODE_PRIVATE);
my_spin=(Spinner)v.findViewById(R.id.spinner1);
my_spin.setOnItemSelectedListener(this);
selected_public = preferences.getString("selected_room", "Adult Lobby");
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
GPSsearch = (EditText)v.findViewById(R.id.cr_gps_search);
GPSaddress = (TextView)v.findViewById(R.id.cr_gps_address);
GPSaddress.setText(preferences.getString("user_location", ""));
Button search_go = (Button)v.findViewById(R.id.cr_go_search);
Button address_go = (Button)v.findViewById(R.id.cr_go_address);
Button changeroom = (Button)v.findViewById(R.id.cr_changeroom);
//Button changeroom2 = (Button)v.findViewById(R.id.cr_changeRoom2);
search_go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
MainActivity m = (MainActivity)getActivity();
final TabInfo tab = m.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(GPSsearch.getText().toString(),"1");
// fragment.setText(characters[position]);
// second, you push the fragment. It becomes visible and the up button is
// shown
m.pushFragment(tab, fragment);
}
});
Can someone please explain to me how to get it to load the fragment. Thank you. Let me know if I am leaving out any relevant code. Im getting a null pointer exception as my error.
Well, first of all, here is the code I was talking about in my comment:
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
menuActivity m = dialog.getOwningActivity();
final TabInfo tab = m.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(txtsearch.getText().toString(),"1");
m.pushFragment(tab, fragment);
...
However, now that I type this up, it doesn't make sense that the NPE was on the call to pushFragment like you said. If the activity outer-class reference was really the null pointer, then it should have crashed a few lines earlier, calling getCurrentTabInfo. Thus I don't think this code change will help. Please take a second look at the stack you are seeing, and tell me what line the NPE is happening on.

How can I make multiple activities be in one activity changing only strings?

I have an app that contains a ListView in its menu which I want to link to one activity with the same layout style but the content inside should be different after being clicked on.
The ListView contains a list of songs, and the layout of an individual item when clicked contains a Title (TextView), Lyrics (TextView), a "next_button" button, a "previous_button" button to move between songs, a "back_button" button to get back to the ListView and a "play_tune" button which plays audio for that specific song. Not all of the songs contain audio, but where the "play_tune" button lies, I would like the app icon ic_launcher-web.png showing there instead.
The XML file I would like to show (for a song with audio) is shown below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/song"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
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=".ScoutSongs" >
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<ImageButton
android:id="#+id/play_tune"
android:src="#drawable/play_tune"
android:contentDescription="#string/play_tune"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/Title"
android:layout_alignTop="#+id/Title" />
<ScrollView
android:id="#+id/LyricsView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/back_button"
android:layout_alignLeft="#+id/Title"
android:layout_alignRight="#+id/play_tune"
android:layout_below="#+id/play_tune" >
<TextView
android:id="#+id/Lyrics"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF" />
</ScrollView>
<Button
android:id="#+id/back_button"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/LyricsView"
android:text="#string/back"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/previous_button"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/back_button"
android:layout_alignBottom="#+id/back_button"
android:layout_alignLeft="#+id/LyricsView"
android:text="#string/previous"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/next_button"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/previous_button"
android:layout_alignBottom="#+id/previous_button"
android:layout_toRightOf="#+id/previous_button"
android:text="#string/next"
android:textColor="#FFFFFF" />
My current SongActivity.java file is shown below:
package com.lmarshall1995.scoutsongs;
import com.lmarshall1995.scoutsongs.R;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class SongActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.song);
Intent i = getIntent();
String Title = i.getStringExtra("Title");
String Lyrics = i.getStringExtra("Lyrics");
String TuneToast = i.getStringExtra("TuneToast");
String Tune = i.getStringExtra("Tune");
setupNavigationButton();
Toast toast = Toast.makeText(this, TuneToast , Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
final Button back = (Button) findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
final Button previous = (Button) findViewById(R.id.previous_button);
previous.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent previousIntent = new Intent(SongActivity.this, SongActivity.class);
SongActivity.this.startActivity(previousIntent);
finish();
}
});
final Button next = (Button) findViewById(R.id.next_button);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent nextIntent = new Intent(SongActivity.this, SongActivity.class);
SongActivity.this.startActivity(nextIntent);
finish();
}
});
final ImageButton play_tune = (ImageButton) findViewById(R.id.play_tune);
play_tune.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageButton play_tune = (ImageButton) findViewById(R.id.play_tune);
play_tune.setOnClickListener(new View.OnClickListener() {
MediaPlayer mp = MediaPlayer.create(SongActivity.this, Tune);
public void onClick(View arg0) {
if (mp.isPlaying()) {
mp.stop();
mp.prepareAsync();
mp.seekTo(0);
} else {
mp.start();
}
}
});
}
});
}
private void setupNavigationButton() {}
}
And my Menu.java for my ListView is here:
package com.lmarshall1995.scoutsongs;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class Menu extends ListActivity{
String classes[] = {"Song_AliceTheCamel_Activity", "Song_Bingo_Activity",
"Song_CampfiresBurning_Activity", "Song_DownAtTheStation_Activity",
"Song_EverywhereWeGo_Activity", "Song_FeFi_Activity",
"Song_GingGangGooly_Activity", "Song_HeadShouldersKneesToes_Activity",
"Song_IfYoureHappyAndYouKnowIt_Activity", "Song_JoesButtonFactory_Activity",
"Song_Kumbaya_Activity", "Song_LittleGreenFrog_Activity",
"Song_Meatball_Activity", "Song_NationalAnthem_Activity",
"Song_OldMacDonald_Activity", "Song_PizzaHut_Activity",
"Song_QuartermastersStores_Activity", "Song_RowRowRowYourBoat_Activity",
"Song_ShineUpYourButtons_Activity", "Song_ThreeBlindJellyfish_Activity",
"Song_Underwear_Activity", "Song_Valerie_Activity", "Song_Worms_Activity",
"Song_XCommissionersInTheTown_Activity", "Song_YogiBear_Activity",
"Song_ZipADeeDooDah_Activity"};
String items[] = {"Alice The Camel", "Bingo", "Campfire\'s Burning", "Down At The Station",
"Everywhere We Go", "Fe Fi", "Ging Gang Gooly", "Head, Shoulders, Knees & Toes",
"If You\'re Happy And You Know It", "Joe\'s Button Factory", "Kumbaya",
"Little Green Frog", "Meatball", "National Anthem (UK)", "Old MacDonald", "Pizza Hut",
"Quartermaster\'s Stores", "Row, Row, Row Your Boat", "Shine Up Your Buttons",
"Three Blind Jellyfish", "Underwear", "Valerie", "Worms",
"X-Commissioner\'s In The Town", "Yogi Bear", "Zip A Dee Doo Dah"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
final ImageButton settings = (ImageButton) findViewById(R.id.settings_button);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent settingsIntent = new Intent(Menu.this, Settings.class);
Menu.this.startActivity(settingsIntent);
}
});
final ImageButton back = (ImageButton) findViewById(R.id.exit_button);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, items));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(Menu.this, SongActivity.class);
i.putExtra("Title", "Song_" + classes + "_Title");
i.putExtra("Lyrics", "Song_" + classes + "_Lyrics");
i.putExtra("TuneToast", "To be sung in the tune of \n" + classes);
startActivity(i);
}
}
All of my Titles and Lyrics are currently in my Values\strings.xml file.
How can I make all my songs be in one "SongActivity" class after being selected in ListView? I believe that if you have to write anything out more than once, there should be an easier way to do it.
Edit: How can I make MediaPlayer mp = MediaPlayer.create(SongActivity.this, Tune); and String Tune = i.getStringExtra("Tune"); work together?
When selecting a list item, call your SongActivity with extras in the intent, such as SongName and other params you need. Then read it and populate the fields accordingly.
onItemSelected method:
Intent i = new Intent(this, SongActivity.class);
i.putExtra("songName", "Song name here"); //get song name from the item selected
....
startActivity(i);
In your SongActivity class:
onCreate(...){
Intent i = getIntent();
String songName = i.getStringExtra("songName");
...
}
Edit: this way all other fixed text can be included in SongActivity, just send the song to that activity
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String song = l.getItemAtPosition(position).toString(); //this is the selected song
Intent i = new Intent(Menu.this, SongActivity.class);
i.putExtra("Song", song);
startActivity(i);
}

android: null pointer exception when trying to set any property of button

i have checked everything in this but still i am getting a null pointer exception . whenever i am trying to change the properties of button in java file, app stop working and logcat showing null pointer exception. plzz help me out
here is my code
package com.example.rapid_finger;
import java.util.Random;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class PlayScreen extends Activity {
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Random rand = new Random();
int data = rand.nextInt(99);
String str = Integer.toString(data);
Button b = (Button) findViewById(R.id.b1);
b.setText(str);
setContentView(R.layout.activity_play_screen);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.play_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up- vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here is my xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".PlayScreen" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/scores" />
<Button
android:id="#+id/b1"
android:background="#drawable/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
You did findViewById before you setContentView.
setContentView should come first
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
Random rand = new Random();
int data = rand.nextInt(99);
String str = Integer.toString(data);
Button b = (Button) findViewById(R.id.b1);
b.setText(str);
// Show the Up button in the action bar.
setupActionBar();
}
put setContentView(R.layout.activity_play_screen); after super.onCreate(savedInstanceState);
// replace this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_screen);
Random rand = new Random();
int data = rand.nextInt(99);
String str = Integer.toString(data);
Button b = (Button) findViewById(R.id.b1);
b.setText(str);
// Show the Up button in the action bar.
setupActionBar();
}

Enlarge ImageView image inside onClick event

I am new to Java and Android, so please have mercy. I have 3 buttons and imageView in my activity. Each button generates new version of the picture displayed in ImageView. I would like the imageView to enlarge the current picture to full screen when I click on it. My question is: What would be the best approach to achieve this?
Should I create onClickListener to enlarge the picture?
Should I define a method for ImageView to call in activity_start.xml like android:onClick="myMethodToCall
My activity_start.xml code:
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="template1match"
android:text="image1" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button1"
android:layout_centerHorizontal="true"
android:onClick="template2match"
android:text="image2" />
<Button
android:id="#+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/button2"
android:layout_marginRight="16dp"
android:onClick="template3match"
android:text="image3" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:clickable="true"
android:src="#drawable/wall" />
My Start.java code:
package com.example.matchtemplate;
import java.io.File;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Core.MinMaxLocResult;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class Start extends Activity {
Button button1;
Button button2;
Button button3;
ImageView imageView1;
File cacheDir;
protected static final String TAG = "OpenCV";
private BaseLoaderCallback mLoaderCallBack = new BaseLoaderCallback(this) {
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
Log.i(TAG, "Open CV loaded successfully");
break;
default:
super.onManagerConnected(status);
break;
}
};
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
//addListenerOnButton();
initDir();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start, menu);
return true;
}
#Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this,
mLoaderCallBack);
}
// ADDED THIS: to create/initialize external file
// Be sure write permissions is enabled in the manifest file
// ie add: <uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE"/>
public void initDir() {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"FileList");
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
}
}
// added this to simplify creating full file path
public String getFileAbsPath(String fileName) {
File f = new File(cacheDir, fileName);
return f.getAbsolutePath();
}
public void template1match(View v) {
imageView1 = (ImageView) findViewById(R.id.imageView1);
button1 = (Button) findViewById(R.id.button1);
String infile = getFileAbsPath("wall.jpg");
String tp = getFileAbsPath("template1.jpg");
String outFile = getFileAbsPath("result.jpg");
try {
matchTemplate(infile, tp, outFile, Imgproc.TM_CCOEFF);
Bitmap bm = BitmapFactory.decodeFile(outFile);
imageView1.setImageBitmap(bm);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void template2match(View v) {
imageView1 = (ImageView) findViewById(R.id.imageView1);
button2 = (Button) findViewById(R.id.button2);
String infile = getFileAbsPath("wall.jpg");
String tp = getFileAbsPath("template2.jpg");
String outFile = getFileAbsPath("result.jpg");
try {
matchTemplate(infile, tp, outFile, Imgproc.TM_CCOEFF);
Bitmap bm = BitmapFactory.decodeFile(outFile);
imageView1.setImageBitmap(bm);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void template3match(View v) {
imageView1 = (ImageView) findViewById(R.id.imageView1);
button3 = (Button) findViewById(R.id.button3);
String infile = getFileAbsPath("wall.jpg");
String tp = getFileAbsPath("template3.jpg");
String outFile = getFileAbsPath("result.jpg");
try {
matchTemplate(infile, tp, outFile, Imgproc.TM_CCOEFF);
Bitmap bm = BitmapFactory.decodeFile(outFile);
imageView1.setImageBitmap(bm);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void matchTemplate(String inFile, String templateFile,
String outFile, int match_method) {
Log.i(TAG, "Running Template Matching");
Mat img = Highgui.imread(inFile);
Mat templ = Highgui.imread(templateFile);
// / Create the result matrix
int result_cols = img.cols() - templ.cols() + 1;
int result_rows = img.rows() - templ.rows() + 1;
Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);
// / Do the Matching and Normalize
Imgproc.matchTemplate(img, templ, result, match_method);
Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
// / Localizing the best match with minMaxLoc
MinMaxLocResult mmr = Core.minMaxLoc(result);
Point matchLoc;
if (match_method == Imgproc.TM_SQDIFF
|| match_method == Imgproc.TM_SQDIFF_NORMED) {
matchLoc = mmr.minLoc;
} else {
matchLoc = mmr.maxLoc;
}
// / Show me what you got
Core.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
matchLoc.y + templ.rows()), new Scalar(0, 255, 0));
// Save the visualized detection.
Log.i(TAG, "Writing: " + outFile);
Highgui.imwrite(outFile, img);
}
}
The two are equivalent- all that happens with the xml is that behind the scenes Android will create an onClickListener for you, register it, and that listener will call the function named in the xml. So there's no real reason to prefer one over the other. Since there's no reason to care, I tend to go the xml route as it requires slightly less code.
i saw the Gabe's answer.But i will have my own answer.Both are same despite in case of xml Android will take care of creating the onClicListener for you.But i will prefer to go for coding rather than xml as it will be easier to understand.Suppose someone will see your code tomorrow and will click the image and image will enlarge, he will not the onClicklistener in the code so may get confuse at his first look.Though if he will be a good coder he will look for xml,but if it will be there in the code itself then it will be easier to understand.
if I was in your place I would implement an alert dialogue once the image is clicked, and in the alert dialogue there is a custom .xml which has a fill_parent imageview. So once the image is clicked the alert comes and the image inside becomes the image clicked

Categories