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.
Related
I have just gone through the android "first app" tutorial located Here, and I want to start experimenting on my own with the stuff that tutorial taught me.
What I want to do is take the message the user writes in the first activity, and display it in a TextView element, which i have defined in the XML file for the second activity. How do I edit the properties of a text view using the java code? I have no idea how to edit any of the properties of the element, even though I know its android:id . Can anyone give me any insight into this?
TextView textView = (TextView) findViewById(R.id.id_of_the_textview);
textView.setText(yourNewText);
What I want to do is take the message the user writes in the first activity
I assume you'll use an EditText in your FirstActivity, so you have to get the text from this widget and pass it as an extra in your intent used to switch to the second activity.
In your FirstActivity onCreate method it will look like :
EditText myEditText = (EditText) findViewById(R.id.yourEditTextId);
Intent i = new Intent(this, ToClass.class);
i.putExtra("myText", myEditText.getText().toString());
startActivity(i);
And in your SecondActivity onCreate methode :
Intent intent = getIntent();
String text = intent.getExtras().getString("myText");
TextView myTextView = (TextView) findViewById(R.id.yourTextViewId);
myTextView.setText(text);
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends Activity {
Button button1;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Calculated.java
public class Calculated extends Activity {
TextView mTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getIntent().getStringExtra("mytext"));
}
calculated.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"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
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()
I have a problem with btn.setOnClickListener(this). I have a simple project that works good, but when I add an action to the button I get the message:
unfortunatelay (app name) has stopped
When I comment btn.setOnClickListener(this) out the project works without any problem.
Here is my code:
package com.example.hello;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
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.Button;
public class MainActivity extends ActionBarActivity {
public static final Context PlaceholderFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().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.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 implements OnClickListener {
Button btn;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
btn=(Button)rootView.findViewById(R.id.Entrer);
btn.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// here is the problem error: no eclosing istance of the type MainActivityis accessible in scope
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
}
My layout is as follows:
<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.hello.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:text="#string/hello_world"
android:textSize="16dp" />
<Button
android:id="#+id/Entrer"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:text="Entrer" />
</RelativeLayout>
I dont know if I have simple things that are not go correctly. I'm new to Android programming. Thank you!
btn is null, so when you set onClickListener you get NullPointerException. It's null because it's located in fragment_main.xml, not activity_main.xml. You should move this code from onCreate()
btn = (Button) findViewById(R.id.Entrer);
btn.setOnClickListener(this);
to PlaceholderFragment() as follows:
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);
btn=(Button) rootView.findViewById(R.id.Entrer);
btn.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
return rootView;
}
}
btn=(Button)findViewById(R.id.Entrer);
btn.setOnClickListener(this);
Most likely, findViewById above is returning null. btn.setOnClickListener is crashing on a null pointer exception. (Because btn is null).
It is extremely likely, since you are using the default fragment structure created by the Eclipse solution, that the Button is really in the fragment layout file (fragment_main.xml) and not in activity_main.xml. (Hence, the button is not in the Activity view, it's in the fragment view).
If that's the case, then move the above two lines into the onCreateView method of the PlaceholderFragment.
I'm new in android programming and I'm making a very simple app.
I only have one text view and one button, and when I click the button I want to show in the text view a value that represents how long the activity was open.
this is my xml file:
<Button
android:id = "#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button"
android:layout_centerHorizontal="true"
android:text=" " />
</RelativeLayout>
and this is my java file:
package com.diogoc.teste;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(Listener);
}
#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;
}
private OnClickListener Listener = new OnClickListener() {
public void onClick(View v) {
//It's here
textView.setText("You take");
}
};
}
Thank you.
Add this member variable to the class:
long startTime;
Add this to your onCreate()-method:
startTime = System.currentTimeMillis();
Add this to your onClick()-method:
long timeElapsedMS = System.currentTimeMillis()-startTime; //gets the time difference in milliseconds
long timeElapsedSeconds = timeElapsedMS/1000;
textView.setText("You took "+timeElapsedSeconds+" seconds");
Something like this in your onCreate will work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Other stuff omitted */
final long start= System.currentTimeMillis();
final Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
textView.setText(System.currentTimeMillis() - start);
handler.postDelayed(this, 100);
}
}, 100);
}
The code in the run() method will run indefinately every 100 ms, updating the text in your textview with the milliseconds passed since the call to onCreate().
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);
}