i have coded simple calculator with two input boxes and once total button , What i have to is show a circular Progressbar for 3 seconds before i show result after pressing Total button ,here is what i have done .
package com.example.calculator;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity
{
EditText t1;
EditText t2;
TextView tv;
TextView tv1;
Timer singleTask;
int Interval = 3000;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1= (EditText)findViewById(R.id.editText1);
t2= (EditText)findViewById(R.id.editText2);
tv= (TextView)findViewById(R.id.textView1);
tv1= (TextView)findViewById(R.id.textView2);
singleTask= new Timer();
}
public void loadprogressbar()
{
singleTask.schedule(new TimerTask() {
#Override
public void run() {
// have to add code for progress bar but right now just caption text added
tv1.setText("This is for 3 seconds only");
}
}, 1000);
}
#Override
protected void onDestroy(){
super.onDestroy();
if(singleTask != null)
{
singleTask.cancel();
}
}
public void Clicked(View v)
{ int total;
if(v.getId()==R.id.button1)
{
int v1 = Integer.parseInt(t1.getText().toString());
int v2 = Integer.parseInt(t2.getText().toString());
total = v1 + v2;
loadprogressbar();
tv.setText(total+"");
tv.setVisibility(1);
}
else if (v.getId()==R.id.button2)
{
t1.setText("");
t2.setText("");
}
}
#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;
}
}
Xml File is
<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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:visibility="invisible"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
></TextView>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="21dp"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_alignRight="#+id/editText2"
android:text="Clear"
android:onClick="Clicked"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText2"
android:layout_marginTop="35dp"
android:text="Total"
android:onClick="Clicked"
/>
</RelativeLayout>
Problem is that i am not getting any result against Timer code ? according to my thinking it should show text for 3 seconds and then display text . My logic could be wrong as well please guide me ..
If I understand correctly what you want to do is to show a ProgressDialog to simulate that your calculator is doing some calculation. The Timer class is not what you want to use. Basically, you want to wait for 3 seconds (during that time the ProgressDialog will be visible), and then update the UI by setting the TextView with the result. As you might know, you cannot modify the UI thread from a background Thread directly, and you should not make the UI thread sleep. Hence, AsyncTask is your best bet. Below is a sample code to allow you to show a ProgressDialog for 3 seconds. You should update your TextView on the OnPostExecute method since it runs on the UI thread.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends Activity{
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pd = new ProgressDialog(this);
pd.setTitle(getString("Title"));
pd.setIndeterminate(true);
pd.show();
new MyAsycnTask().execute();
}
}
#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 class MyAsycnTask extends AsyncTask <Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pd.hide();
}
}
}
Go with E.Odebugg answer.
If you however need to display a TextView for 3 seconds and then hide, here's how to do it without using TimerTask.
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setVisibility(View.GONE);
}
}, 3000);
The TextView is displayed by default, and after 3 seconds it's hidden. Also, note that postDelayed() is used, which will run the Runnable on UI thread.
So I think your code is wrong in loadprogressbar(). It should be:
public void loadprogressbar()
{
// have to add code for progress bar but right now just caption text added
tv1.setText("This is for 3 seconds only");
singleTask.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
///hide the progressbar here...
}
});
}
}, Interval);
}
And if I were you I would change the name of your function "Clicked", because it can be a reserved word (the color also indicates it)...
Related
I am making boxing countdown timer and to set how long round supposed to last I am using two button first "+" and second "-" my time add every 5 seconds ex "5,10,15,20,25..." but I always I have to click to add 5 second. I would like to hold button and my value will add automatically what should I do?
I hope I add every important information in my question
my code from buttons and display
public void dodawanie1(View view) {
iloscrund=iloscrund+1;
display(iloscrund);
public void odejmowanie1(View view) {
if(iloscrund>1){
iloscrund=iloscrund-1;
display(iloscrund);
}
}
private void display(int numer) {
TextView displayInteger=(TextView) findViewById(R.id.textView16);
displayInteger.setText("" + numer);
}
odejmowanie means decrease value
dodawanie means increase value
If you mean to determine between click and hold, use onTouchListener to determine hold button event.
onTouchListener
I think you should use Runnable and Handler class for do it.
this link should be useful.
Android: Implement a 1 second interval timer before calling a function
activity_auto_inc.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AutoIncActivity">
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="1"
android:textSize="26sp"
android:textColor="#color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/add"
android:text="add"
android:textColor="#color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/num" />
</androidx.constraintlayout.widget.ConstraintLayout>
AutoIncActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AutoIncActivity extends AppCompatActivity implements
View.OnLongClickListener, View.OnTouchListener {
Button add;
TextView txt;
boolean isAddPressed = false;
Handler handler;
final int TIME_INTERVAL = 100;
final int STEP = 1;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_inc);
handler = new Handler();
add = findViewById(R.id.add);
txt = findViewById(R.id.num);
add.setOnLongClickListener(this);
add.setOnTouchListener(this);
}
#Override
public boolean onLongClick(View view) {
if (view.getId() == R.id.add) {
isAddPressed = true;
handler.postDelayed(new AutoInc(), TIME_INTERVAL);
}
return false;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP ||
motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
isAddPressed = false;
}
return false;
}
private class AutoInc implements Runnable {
#Override
public void run() {
if (isAddPressed) {
txt.setText(String.valueOf(Integer.parseInt(txt.getText().toString()) +
STEP));
handler.postDelayed(this, TIME_INTERVAL);
}
}
}
}
No matter how much I edit or change to my Java code for this assignment, it refused to properly update the value of the integer variable I've set for the result. Can someone show me what on earth I'm missing here? Below is my code:
package com.example.minicalc;
import com.example.minicalc.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class MainActivity extends Activity implements OnEditorActionListener {
private static final String TAG = "MiniCalc";
private SharedPreferences savedValues;
private EditText editText1;
private EditText editText2;
private Button button1;
private Spinner spinner1;
private TextView answerLbl;
private int ivalue1 = 0;
private int ivalue2 = 0;
private int ianswer;
private int spinChoice;
//private String[] spinner_strings = {"+", "-", "×", "÷"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate event started");
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
button1 = (Button) findViewById(R.id.button1);
answerLbl = (TextView) findViewById(R.id.answerTxt);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText1.setOnEditorActionListener(this);
editText2.setOnEditorActionListener(this);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
spinChoice = spinner1.getSelectedItemPosition();
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.d(TAG, "onClick event started");
ianswer = 0;
if (spinChoice == 0) {
ianswer = ivalue1 + ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 1) {
ianswer = ivalue1 - ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 2) {
ianswer = ivalue1 * ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 3) {
ianswer = ivalue1 / ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
}
answerLbl.setText(Integer.toString(ianswer));
//answerLbl.setText(""+ianswer);
Log.d(TAG, "answerLbl TEXT IS: " + answerLbl.getText());
}
});
}
#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);
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.d(TAG, "onEditorAction event started");
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
ivalue1 = Integer.parseInt(editText1.getText().toString());
ivalue2 = Integer.parseInt(editText2.getText().toString());
}
return false;
}
#Override
public void onPause() {
Log.d(TAG, "onPause event started");
Editor editor = savedValues.edit();
editor.putString("value1", editText1.getText().toString());
editor.putString("value2", editText2.getText().toString());
editor.commit();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume event started");
editText1.setText(savedValues.getString("value1", ""));
editText2.setText(savedValues.getString("value2", ""));
}
}
Here is my layout XML, activity_main.xml:
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
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.minicalc.MainActivity" >
<TextView
android:id="#+id/valLbl1"
android:labelFor="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="40dp"
android:text="#string/valueLbl1" />
<TextView
android:id="#+id/valLbl2"
android:labelFor="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl1"
android:layout_below="#+id/editText1"
android:layout_marginTop="24dp"
android:text="#string/valueLbl2" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl1"
android:layout_below="#+id/valLbl1"
android:layout_marginTop="20dp"
android:ems="5"
android:inputType="number">
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl2"
android:layout_below="#+id/valLbl2"
android:layout_marginTop="16dp"
android:ems="5"
android:inputType="number" />
<TextView
android:id="#+id/answerTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/answerLblTxt"
android:layout_centerHorizontal="true"
android:ems="7"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/submit" />
<TextView
android:id="#+id/answerLblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/editText2"
android:layout_below="#+id/button1"
android:layout_marginTop="16dp"
android:text="#string/answerLbl" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/valLbl2"
android:layout_marginStart="28dp"
android:layout_toEndOf="#+id/editText2"
android:entries="#array/spinner_strings" />
</RelativeLayout>
Now, the app runs fine, the LogCat messages show up fine...except when I put them in the onClickListener. So yes, I've sorta identified WHERE the problem is, I just don't know WHAT the problem is. I'd show a screen shot of the error, but this is my first time posting. In any case, the phone I'm running the app on is a Samsung Galaxy Note 3, running Android 4.4.4. Can anyone help me?
Your spinners getSelectedItemPoisition() method is only called once in your onCreate() method and it is not called every time you click on the button, resulting in the value never being updated.
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
spinChoice = spinner1.getSelectedItemPosition();
...
}
This line of code needs to be added in the onClick() method causing the new value to be read on button click.
I'm trying to make a rudimentary app to take the user's name (input) and display their name reversed (output). However, I can't seem to get this code to display the output I want. I just came to Android. How do I display a string in the user output?
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Main" >
<Button
android:id="#+id/reverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="166dp"
android:text="#string/reverse" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="#string/desc"
android:textAppearance="?
android:attr/textAppearanceSmall" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/desc"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:ems="10"
android:inputType="text">
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name"
android:layout_alignTop="#+id/reverse"
android:layout_marginTop="67dp"
android:text="#string/reversed"
android:textAppearance="?
android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/displayName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/reverse"
android:layout_below="#+id/textView1"
android:layout_marginTop="46dp"
android:text="#string/medium_text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Java:
package com.example.basicapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main extends Activity {
Button reverse;
#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.main, menu);
return true;
}
public class Reverser extends android.app.Activity {
TextView displayed = (TextView)findViewById(R.id.displayName);
EditText nametext = (EditText)findViewById(R.id.name);
String namestring = nametext.getText().toString();
public void onClickListener() {
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String reverse = new StringBuffer(namestring).reverse().toString();
String dr = reverse;
displayed.setText(dr);
}
});
}
}
}
Thank you.
public class Main extends Activity {
Button reverse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView displayed = (TextView)findViewById(R.id.displayName);
EditText nametext = (EditText)findViewById(R.id.name);
String namestring = nametext.getText().toString();
reverse=(Button)findViewById(R.id.reverse);//assuming you have button with id reverse
reverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String reverse = new StringBuffer(namestring).reverse().toString();
String dr = reverse;
displayed.setText(dr);
}
});
}
#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;
}
}
O.K i have looked around this site and others and i see something similar to what i am wanting but yet it isn't what i am wanting...let me explain
i am learning to build an android app using eclipse that has a media player linked to my shoutcast server i am running, so far the apps works great but it doesn't have an icon on the top were the notification area is and when i go to a different app (a game) to play while leaving the music playing it minimizes the app .. thats fine but when i reopen the app it doesnt stop the mediaplayer infact if i play the player i will have 2 players running i will then have to force stop it using the task manager,, i know this can be done as i have apps on my phone that has icons and it will do what i am wanting
when i searched this site i found a link to youtube that has soemthing similar to what i am wanting
http://www.youtube.com/watch?v=e74z0_Z5QWI&feature=relmfu the code that is shown is as followed
import android.app.Activity;
public class StatusBar extends Activity implements OnclickListener{
NotificationManager nm;
#Override
Protected void onCreate(bundle savedInstance){
//TODO Auto-generated method Stub
super.oncreate(savedInstaceState);
setContentView(R.layout.statusbar);
Button stat = (Button)findViewById(R.id.bStatusBar);
stat.setOnClickListener(this);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
public void onClick(View v){
//TODO Auto-generated method Stub
Intent intent = new Intent(this, StatusBar.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
}
i have add this code to my MainActivity.java but it spits several errors to me that i have tried to fix using quickfix here is the script i currently have in my MainActivity.java file
package com.myapp.mytapp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class MainActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://link to url:8002";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(true);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(true);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
public void homepage (View view) {
goToUrl ( "http://myhomepage.com/");
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
}
here is what is in my activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/black"
android:icon="#drawable/ic_launcher"
android:orientation="vertical"
startForeground()>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/logo" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/homepage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:clickable="true"
android:cursorVisible="true"
android:linksClickable="true"
android:onClick="homepage"
android:text="Home Page" />
</TableRow>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_play"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/play"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/play" >
</Button>
<Button
android:id="#+id/btn_pause"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/pause"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/pause" >
</Button>
<Button
android:id="#+id/btn_stop"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/stop"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/stop" >
</Button>
</LinearLayout>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp" >
</SeekBar>
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/scast" />
<TextView
android:id="#+id/Textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:hint="#string/version" >
</TextView>
</LinearLayout>
can someone tell me what i did wrong or can rewrite what i have and still keep everything working
Thanks in advance
Rob
So whenever the these two lines are commented out its fine, but with them it crashes.
EditText convertValue = (EditText) findViewById(R.id.et_value_convert);
TextView convertResult = (TextView) findViewById(R.id.txt_result);
here's my full class code, xml is below.
package com.doubleelite.maxtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class ConverterActivity extends Activity {
EditText convertValue = (EditText) findViewById(R.id.et_value_convert);
TextView convertResult = (TextView) findViewById(R.id.txt_result);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_converter);
}
#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_converter, menu);
return true;
}
// Custom method to handle button clicks.
public void onClick(View v) {
switch(v.getId()) {
case R.id.btn_to_cel:
convertResult.setText(String.valueOf(convertFahrenheitToCelsius(Integer.valueOf(convertValue.getText().toString()))));
}
}
private float convertFahrenheitToCelsius(float f) {
return (f-32) * (5/9);
}
private float convertCelsiusToFahrenheit(float c) {
return c * (9/5) + 32;
}
}
here is the xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ConverterActivity" >
<EditText
android:id="#+id/et_value_convert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/text_value_convert"
android:inputType="number"
/>
<Button
android:id="#+id/btn_to_cel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/button_celsius"
android:onClick="onClick"
/>
<Button
android:id="#+id/btn_to_fahr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/button_fahr"
android:onClick="onClick"
/>
<TextView
android:id="#+id/txt_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:ignore="HardcodedText" />
</LinearLayout>
Currently you are trying to find view's before setting layout for Activity.change your code as :
public class ConverterActivity extends Activity {
EditText convertValue ;
TextView convertResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_converter);
convertValue = (EditText) findViewById(R.id.et_value_convert);
convertResult = (TextView) findViewById(R.id.txt_result);
}
///YOUR CODE HERE