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).
Related
part of the code
package com.example.pass;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class Permission extends ActionBarActivity implements OnClickListener, OnKeyListener{
EditText Date;
EditText Time;
EditText userName;
EditText userSurname;
Button btnOK;
Button Cancel;
EditText Name;
String Surname;
Button clear;
ListView list;
ArrayList<String> Items;
ArrayAdapter<String> aa;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission);
list = (ListView)findViewById(R.id.listView1);
Items = new ArrayList<String>();
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Items);
list.setAdapter(aa);
// Include dialog.xml file
// Set dialog title
final Dialog dialog = new Dialog(Permission.this);
dialog.setContentView(R.layout.dialog_permission);
dialog.setTitle("Custom Dialog");
clear = (Button)findViewById(R.id.clear);
Button add = (Button) findViewById(R.id.add);
// Create custom dialog object
// set values for custom dialog components - text, image and button
userName = (EditText) dialog.findViewById(R.id.dialog_username);
userSurname = (EditText)dialog.findViewById(R.id.dialog_usersurname);
Time = (EditText)dialog.findViewById(R.id.dialog_time2);
Date = (EditText)dialog.findViewById(R.id.dialog_date2);
btnOK = (Button) dialog.findViewById(R.id.OK);
Cancel = (Button) dialog.findViewById(R.id.Cancel);
btnOK.setOnClickListener(this);
userName.setOnKeyListener(this);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentDate=Calendar.getInstance();
int mYear = mcurrentDate.get(Calendar.YEAR);
int mMonth = mcurrentDate.get(Calendar.MONTH);
int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker=new DatePickerDialog(Permission.this, new OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
// TODO Auto-generated method stub
/* Your code to get date and time */
Date.setText(selectedyear+"-"+(selectedmonth+1)+"-"+selectedday);
}
},mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show(); }
});
Time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentTime=Calendar.getInstance();
int mHour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int mMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker=new TimePickerDialog(Permission.this, new OnTimeSetListener() {
public void onTimeSet(TimePicker timepicker, int selectedhour, int selectedminute ) {
// TODO Auto-generated method stub
/* Your code to get date and time */
if (selectedminute<10){
Time.setText(selectedhour+":"+"0"+(selectedminute)+""+"val");
}
else
Time.setText(selectedhour+":"+(selectedminute));
}
},mHour, mMinute, false);
mTimePicker.setTitle("Select date");
mTimePicker.show(); }
});
Cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
dialog.dismiss();
}
});
// OK.setOnClickListener(new OnClickListener() {
/* #Override
public void onClick(View v) {
// TODO Auto-generated method stub
this.addItem(this.userName.getText().toString());
//CONVERTING THE TEXT IN TO STRING...
System.out.println(Name);
}
});*/
clear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
dialog.show();
}
});
}
private void addItem(String item){
if(item.length()>0){
this.Items.add(item);
this.aa.notifyDataSetChanged();
this.userName.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.permission, 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 onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==KeyEvent.ACTION_DOWN&&keyCode==KeyEvent.KEYCODE_DPAD_CENTER){
this.addItem(this.userName.getText().toString());
this.addItem(this.userSurname.getText().toString());
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == this.btnOK){
this.addItem(this.userName.getText().toString());
this.addItem(this.userSurname.getText().toString());
}
}
}
Everytime i try to change to custom layout everything crashes, i dont know how to do it not losing dialog window, because text i am reading from is in my custom dialog. I know that maybe creating new adapter class can solve the problem but i want to try another way.
Use CTRL + Left click on android.R.layout.simple_list_item_1 to open it.
Copy the contents to your own XML layout file, and edit it as your wish.
Change
android.R.layout.simple_list_item_1
To
R.layout.your_layout
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.
Edited code after following this link ...Set wallpaper from ViewPager .I developed simple viewpager app along with the background music. However, I want to modify my app so that image chosen by user will give them option to set as wallpaper....I don't want to implement any buttons in my app. User should be able to just touch the image , which will give them option to set as wallpaper...
I am getting error at this code curruntPosition=arg0;. It says "Current position cannot be resolve to a variable". I don't know what it mean ...
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
//Here you can set the wallpaper
curruntPosition=arg0;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
oursong = null;
}
}
imageadapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
I just start with programming, so please give some explanations, or it will be great if you provide some codes .
First add this Permission to the Manifest
<uses-permission android:name="android.permission.SET_WALLPAPER">
Now for some code.
imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Explantion : This will set that the Image will be clickable , when the image is clicked it will set the phone Wallpaper with the selected drawable.
getApplicationContext()
is the Context from the Activity.
This changes will take place inside the Adapter.
Activity
add this variable
int currentPosition;
package com.thenewboston.jordy;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Startingpoint extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startingpoint);
}
int counter;
Button add, sub;
TextView display;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.startingpoint, menu);
return true;
counter = 0;
add = (Button) findViewById(R.id.BAdd);
sub = (Button) findViewById(R.id.Bsub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Your total is " + counter);
}
});
}
}
hello,
i just started following tutorial to make android apps with eclips.
Now I get this error unreachable code at the line with "counter = 0"
I think it's has to do something with the line "return true" because, when i remove that the error is gone but then i get other errors :s, does someone know what the problem is here?
Thanks in advance
Any code after the return will never be executed. Therefore you get unreachable code.
Put return at the end of the method
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.startingpoint, menu);
counter = 0;
...
return true;
}