Okay, so I've been stuck for a couple of days now working with gestures within my app. All it is, is a basic stopWatch application and also a count down application it uses swipeable views to swap between the 2 different activities.
My problem is in my first fragment for the stopWatch part of the app I use a runnable to create and start the timer which works fine and it is currently set up so if the user taps on the timer Text view, it'll start the runnable and the timer will begin counting up. However the way I have set it up it can only accept one input method which is a single tap. This is where the gestures come in. I want to be able to single click to start the timer, double tap to pause the timer and a long press to stop and clear the timer Text view.
I've tried attaching a gesture detector to just the TextView but anything I try doesn't seem to work, I believe I can set the fragment up so if I were to click anywhere on the screen it would do what I wish but I don't want it to work like that. I want it to only work when the user clicks the timer Text view. I've come to a point where I thought I could get it to work, but that involves putting an onDoubleTapListener to my TextView, but for some reason I cannot do that, so does anyone have a way to do that or a way for my code to work?
Sorry for the long explanation but I figure the more information there is on what I want, the easier it would be for someone to help :)
Below is my code, I know it doesn't look too organised (Thats something I'm trying to work on) but hopefully you can see where I'm going wrong. Thanks!
(Also I know some of the views aren't used at all at the moment purely because I'm trying to get it working one step at a time :P also the part of commented out code, is the current way I'm running the timer I thought I'd leave it in here in case someone is wondering how I am currently starting the timer.)
package com.leccles.swipetabs;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {#link android.support.v4.app.Fragment} subclass.
*
*/
public class FragmentA extends Fragment implements
GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
Button lapButton;
TextView timerText;
ListView lapListView;
TextView mMilliTextView;
String milliText;
long startTime = 0;
long timeInMilliSeconds = 0;
GestureDetectorCompat gDetector;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerText.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
public FragmentA() {
// Required empty public constructor
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Inflate the layout for this fragment
mMilliTextView = (TextView) getView().findViewById(R.id.milliTextView);
lapButton = (Button) getView().findViewById(R.id.lapButton);
timerText = (TextView) getView().findViewById(R.id.timerText);
lapListView = (ListView) getView().findViewById(R.id.lapListView);
this.gDetector = new GestureDetectorCompat(getActivity(), this);
timerText.setOnDoubleTapListener(this);
/*
* timerText.setOnClickListener(new View.OnClickListener() {
*
* #Override public void onClick(View v) { TextView timerText =
* (TextView) v; if (timerText.getText().equals(
* getView().findViewById(R.string.stopWatchTime))) {
* timerHandler.removeCallbacks(timerRunnable);
*
* } else {
*
* startTime = System.currentTimeMillis();
* timerHandler.postDelayed(timerRunnable, 0);
*
* }
*
* }
*
* });
*/
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return true;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
return true;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_a, container, false);
}
}
I figured out the problem it was so simple. I didn't need to use an onDoubleTapListener. A simple onTouchListener worked(I had previously tried and failed at using this) I was trying to use it wrong. I didn't put the Gesture Detector into the on touch so it wouldn't ever work. Here is the working code below with the onTouchListener. I also didn't change the boolean in onTouch to true to state that the touch had been handled.
package com.leccles.swipetabs;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {#link android.support.v4.app.Fragment} subclass.
*
*/
public class FragmentA extends Fragment implements
GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
Button lapButton;
TextView timerText;
ListView lapListView;
TextView mMilliTextView;
String milliText;
long startTime = 0;
String sPauseTime;
long iPauseTime;
long timeInMilliSeconds = 0;
GestureDetectorCompat gDetector;
Handler timerHandler = new Handler();
Runnable pauseRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() + startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerText.setText(String.format("%02d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerText.setText(String.format("%02d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
public FragmentA() {
// Required empty public constructor
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Inflate the layout for this fragment
mMilliTextView = (TextView) getView().findViewById(R.id.milliTextView);
lapButton = (Button) getView().findViewById(R.id.lapButton);
timerText = (TextView) getView().findViewById(R.id.timerText);
lapListView = (ListView) getView().findViewById(R.id.lapListView);
this.gDetector = new GestureDetectorCompat(getActivity(), this);
timerText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
gDetector.onTouchEvent(event);
return true;
}
});
/*
* timerText.setOnClickListener(new View.OnClickListener() {
*
* #Override public void onClick(View v) { TextView timerText =
* (TextView) v; if (timerText.getText().equals(
* getView().findViewById(R.string.stopWatchTime))) {
* timerHandler.removeCallbacks(timerRunnable);
*
* } else {
*
* startTime = System.currentTimeMillis();
* timerHandler.postDelayed(timerRunnable, 0);
*
* }
*
* }
*
* });
*/
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
sPauseTime = timerText.getText().toString();
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
return true;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
sPauseTime = timerText.getText().toString();
timerHandler.removeCallbacks(timerRunnable);
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return true;
}
#Override
public void onLongPress(MotionEvent e) {
timerHandler.removeCallbacks(timerRunnable);
timerText.setText("00:00");
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
return true;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_a, container, false);
}
}
Related
I am very new to programming and I have a problem with a game which I am trying to make.
Almost every time when I exit the game it was crashing.
After adding: if (canvas != null) beforew canvas.drawColor(Color.CYAN); it does not crash on exit anymore but when I return to the game.
Here is the code: (its not my actual game... there is nothing in OnDraw exept canvas.drawColor(Color.CYAN); that keeps it simple)
GameView.java:
package com.example.test.threadtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread theGameLoopThread;
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
theGameLoopThread = new GameLoopThread(this);
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
theGameLoopThread.setRunning(false);
while (retry) {
try {
theGameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
theGameLoopThread.setRunning(true);
theGameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onDraw(Canvas canvas) {
if (canvas != null)
canvas.drawColor(Color.CYAN);
}
}
GameLoopThread.java:
package com.example.test.threadtest;
import android.annotation.SuppressLint;
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 20;
private GameView theView;
private boolean isRunning = false;
public GameLoopThread(GameView theView) {
this.theView = theView;
}
public void setRunning(boolean run) {
isRunning = run;
}
#SuppressLint("WrongCall") #Override
public void run() {
long TPS = 1000 / FPS;
long startTime, sleepTime;
while (isRunning) {
Canvas theCanvas = null;
startTime = System.currentTimeMillis();
try {
theCanvas = theView.getHolder().lockCanvas();
synchronized (theView.getHolder()) {
theView.onDraw(theCanvas);
}
} finally {
if (theCanvas != null) {
theView.getHolder().unlockCanvasAndPost(theCanvas);
}
}
sleepTime = TPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {
}
}
}
}
MainAcitvity.java:
package com.example.test.threadtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am new to android app development, so this may be easy for you. I have searched this forum before I posted so please take a look before marking it as duplicate. I am not declaring static variables in the updatestandard method. Here is my program:
package com.example.new1;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextWatcher;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends ActionBarActivity {
private static final String BILL_TOTAL = "BILL_TOTAL";
private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
private double currentBillTotal;
private int currentCustomPercent;
private EditText tip10EditText;
private EditText total10EditText;
private EditText tip15EditText;
private EditText total15EditText;
private EditText billEditText;
private EditText tip20EditText;
private EditText total20EditText;
private TextView customTipTextView;
private EditText tipCustomEditText;
private EditText totalCustomEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if( savedInstanceState ==null)
{
currentBillTotal=0.0;
currentCustomPercent=0;
}
else
{
currentBillTotal=savedInstanceState.getDouble(BILL_TOTAL);
currentCustomPercent=savedInstanceState.getInt(CUSTOM_PERCENT);
}
tip10EditText=(EditText) findViewById(R.id.tip10editText);
tip15EditText=(EditText) findViewById(R.id.tip15editText);
tip20EditText=(EditText) findViewById(R.id.tip20editText);
total10EditText=(EditText) findViewById(R.id.totaltenEditText);
total20EditText=(EditText) findViewById(R.id.totaltwentyEditText);
total15EditText=(EditText) findViewById(R.id.totalfifteenEditText);
tipCustomEditText=(EditText) findViewById(R.id.tipcustomeditText);
totalCustomEditText=(EditText) findViewById(R.id.totaltcustomeditText);
billEditText=(EditText) findViewById(R.id.billeditText1);
billEditText.addTextChangedListener(billEditTextWatcher);
SeekBar customSeekBar = (SeekBar) findViewById(R.id.customSeekBar);
customSeekBar.setOnSeekBarChangeListener(customSeekBarListner);
customTipTextView = (TextView) findViewById(R.id.customTipTextView);
}
private void updateStandard()
{
double tenPercentTip= currentBillTotal * .1;
double tenPercentTotal = currentBillTotal+tenPercentTip;
total10EditText.setText(String.format("%.02f,tenPercentTotal"));
double fifteenPercentTip= currentBillTotal * .15;
double fifteenPercentTotal= currentBillTotal+fifteenPercentTip;
double twentyPercentTip= currentBillTotal * .20;
double twentyPercentTotal= currentBillTotal+twentyPercentTip;
tip10EditText.setText(String.format("%.02f",tenPercentTip));
tip15EditText.setText(String.format("%.02f",fifteenPercentTip));
total15EditText.setText(String.format("%.02f,fifteenPercentTotal"));
tip20EditText.setText(String.format("%.02f",twentyPercentTip));
total20EditText.setText(String.format("%.02f,twentyPercentTotal"));
}
private void updateCustom()
{
customTipTextView.setText(currentCustomPercent+"%");
double customTipAmount=currentBillTotal*currentCustomPercent*.01;
tipCustomEditText.setText(String.format("%.02f",customTipAmount));
double customTotalAmount=currentBillTotal+customTipAmount;
totalCustomEditText.setText(String.format("%.02f",customTotalAmount));
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putDouble(BILL_TOTAL, currentBillTotal);
outState.putInt(CUSTOM_PERCENT, currentCustomPercent);
}
private OnSeekBarChangeListener customSeekBarListner=new OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
currentCustomPercent=seekBar.getProgress();
updateCustom();
// TODO Auto-generated method stub1
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private TextWatcher billEditTextWatcher=new TextWatcher()
{
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
try
{
currentBillTotal=Double.parseDouble(s.toString());
}
catch(NumberFormatException e)
{
currentBillTotal=0.0;
}
updateStandard();
updateCustom();
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
#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);
}
}
so in eclipse it says in the update standard lines that the variables are not used the tenPercentTotal,fifteenPercentTotal and twentyPercentTotal idk why it says that they are used in the next lines below it pls help this exact program worked before i right clicked my project and selected export android app option that messed up many things idk what happened.
You're spelling their names out in the formatting strings instead of actually using them as arguments in the String#format() method calls.
Eclipse is not wrong (maybe refresh project + Validate if hes outdated).
Assigning values to variable does not count as usage.
Hi I'm beginner with android development and I have a problem with my following test code:
Main Activity:
package com.test.thread;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt = null;
Button btStart = null;
Button btStop = null;
TestClass test = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txtView);
btStart = (Button)findViewById(R.id.bt_start);
btStop = (Button)findViewById(R.id.bt_stop);
test = new TestClass(this, txt);
btStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
test.Stop();
}
});
btStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
try{
synchronized (this) {
wait(50);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(test.isStop()){
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
test.DoSomeThing();
}
}
});
}
}catch( InterruptedException e)
{
e.printStackTrace();
}
}
};
t.start();
}
});
}
#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);
}
}
TestCLas.java:
package com.tutorial.sample;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class TestClass{
private boolean stopIter = false;
private TextView txtV = null;
private int count = 0;
private Context ctx = null;
public TestClass(Context ct, TextView tv) {
// TODO Auto-generated constructor stub
txtV = tv;
stopIter = false;
count = 0;
ctx = ct;
}
public boolean isStop() { return stopIter; }
public void Stop()
{
Toast.makeText(ctx, "stop the test" , Toast.LENGTH_LONG).show();
count = 0;
txtV.setText(Integer.toString(count));
stopIter = true;
}
public void DoSomeThing(){
txtV.setText(Integer.toString(count));
}
}
I want to manage my activity's viewer with threads. I launch a thread in order to modify TextView's text (each sec) when the start button is clicked and stop it when stop button is clicked. But it does not work, it crashes without any exception. Can someone help me please?
wait(1000);
This should NEVER be done on the UI thread.
The UI thread is the one that update the GUI, and communicates with Android to say everything is working as expected. When you have a thread delay on the UI thread, the message to and from the android system get held back, and you app appears to the system as if it has crashed.
I don't know whats going wrong with my app i followed so many tutorials, any hint/help/advise would be appreciated, I am new on android. i am getting error as in onserviceregistrationfailed function of listner.
package com.example.ravinetworkapplication;
import java.io.IOException;
import java.net.ServerSocket;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.pm.ServiceInfo;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdManager.DiscoveryListener;
import android.net.nsd.NsdServiceInfo;
import android.net.nsd.NsdManager.RegistrationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
NsdManager mNsdManager;
Context context;
NsdManager.DiscoveryListener mDiscoveryListner=null;
NsdManager.RegistrationListener mRegistrationListener=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();
}
mNsdManager= (NsdManager) this.getSystemService(Context.NSD_SERVICE);
final ServerSocket mServerSocket;
final ArrayList<String> listName = new ArrayList<String>();
Integer localPort = 0;
final ListView list = (ListView) findViewById(R.id.listView1);
listName.add("arunima");
listName.add("abhishek");
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1,listName);
list.setAdapter(adapter);
try {
mServerSocket = new ServerSocket(0);
localPort = mServerSocket.getLocalPort();
mServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
}
#Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
}
#Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
Log.v("service registrd", "i am on folks");
Toast.makeText(getApplicationContext(), "Registerd", Toast.LENGTH_LONG).show();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
Log.v("service registration fail", "can not register service kumar ravi");
}
};
mDiscoveryListner = new NsdManager.DiscoveryListener() {
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("cannot stop service", "service discovery failed");
}
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("can not start", "Can not start discovery kumar ravi "+errorCode);
}
#Override
public void onServiceLost(NsdServiceInfo service) {
// TODO Auto-generated method stub
}
#Override
public void onServiceFound(NsdServiceInfo service) {
// TODO Auto-generated method stub
Log.v("service found", "we found the service");
if(!service.getServiceType().equals("_myapp.tcp.")){
}
else if(service.getServiceName().equals("kumar")){
}
else {
listName.add(service.getServiceName());
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
Toast.makeText(getApplicationContext(), "Finally found the service "+service.getServiceName(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onDiscoveryStopped(String serviceType) {
// TODO Auto-generated method stub
}
#Override
public void onDiscoveryStarted(String serviceType) {
// TODO Auto-generated method stub
Log.v("Service Discovery Started", "Searching of Service Discovery");
}
};
Log.v("registerd port", localPort.toString());
final NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setPort(localPort);
serviceInfo.setServiceName("kumar");
serviceInfo.setServiceType("_myapp.tcp.");
//mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
Button startBroadcast = (Button) findViewById(R.id.button1);
Button startListen = (Button) findViewById(R.id.button2);
startBroadcast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
});
startListen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.discoverServices("_myapp.tcp.", NsdManager.PROTOCOL_DNS_SD, mDiscoveryListner);
}
});
}
#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
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
mNsdManager.unregisterService(mRegistrationListener);
mNsdManager.stopServiceDiscovery(mDiscoveryListner);
Log.v("Stopped", "Scanning stopped"); }
catch(Exception e){
Log.v("some error in unregistring service", e.toString());
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Long story short I an trying to make an app to convert Celsius to Fahrenheit and back. I want to get input from an edit text so I can use that for my math, but I can't figure it out, nor can I get the button to work right to close it. I want to use an internal anonymous class to do the calculations and read in the value, but again no idea what to do. Does anyone have any idea where to start?
here is what I have
package com.example.a4;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements TextWatcher {
EditText mt=(EditText) findViewById(R.id.et1),
mt2=(EditText) findViewById(R.id.et2);
Button bt = (Button) findViewById(R.id.btn1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mt=(EditText) findViewById(R.id.et1);
// mt2=(EditText) findViewById(R.id.et2);
}
OnClickListener oclBtnOk = new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
};
/*
buttonExit.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
System.exit(0);
}
}
);*/
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
int c = Integer.parseInt(s.toString());
ftoc(c);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
void ftoc(int c){
int f = ((9/5)*c) + 32;
mt2.setText(f);
}
/*
#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;
}
*/
}
You need to move your mt = (EditText)findViewById stuff back to onCreate. Then, if you want to use anonymous classes, do something like:
mt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
...
}
});
Also, make sure you're using View.OnClickListener and not DialogInterface.OnClickListener as you are now (check your imports).