How to store a number from edittext in a variable (integer) each time when user enter a number and to use the variable in 'onSensorChanged'? Like here: if (event.values[0] == (1 - UserInputVariable)) {acceleration.setText(UserInputVariable);}
My code is:
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
EditText mEdit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
acceleration=(TextView)findViewById(R.id.acceleration);
mEdit = (EditText)findViewById(R.id.editText1);
}
#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 void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.values[0] == 1) {
acceleration.setText(mEdit);
}
else{ acceleration.setText("X: "+event.values[0]+
"\nY:"+event.values[1]);
}
}
}
mEdit.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#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) {
doSomething();
}
});
you can use edit text change listener to handle whenever user enter something.
Related
I have 2 EditText in my activity,lets say editText1 ,editText2 and A Double Variable d=200
I want when user change/insert value for editText1 ,editText2 value will update in real Time as editText1*d
Also when user change/insert value for editText2 ,editText1 will be update in real time as editText2*d
I tried to use addTextChangedListener->onTextChangedbut it works fine for one Edit text,when I set this function for both editText then application crash
because its creating an infinite loop,how can I solve this problem?
update :bellow is my code
et1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Editable a = et1.getText();
Double aa = Double.parseDouble(a.toString())*100;
String aaa = aa.toString();
et2.setText(aaa);
}
#Override
public void afterTextChanged(Editable s) {
}
});
et2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Editable b=et2.getText();
Double bb=Double.parseDouble(b.toString());
String bbb=bb.toString();
et1.setText(bbb);
}
#Override
public void afterTextChanged(Editable s) {
}
});
EditText et1, et2;
TextWatcher watcher1 = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
Editable a = et1.getText();
Double aa = Double.parseDouble(a.toString())*100;
String aaa = aa.toString();
et2.removeTextChangedListener(watcher2);
et2.setText(aaa);
et2.addTextChangedListener(watcher2);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
TextWatcher watcher2 = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
Editable b=et2.getText();
Double bb=Double.parseDouble(b.toString());
String bbb=bb.toString();
et1.removeTextChangedListener(watcher1);
et1.setText(bbb);
et1.addTextChangedListener(watcher1);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
et1.addTextChangedListener(watcher1);
et2.addTextChangedListener(watcher2);
i think you have to create textwatcher separately then in your TextWatcher_EdOne
TextWatcher TextWatcher_EdOne = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//disable editext2 textwatcher
et2.removeTextChangedListener(TextWatcher_EdTwo);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
///do your stuff
}
#Override
public void afterTextChanged(Editable s) {
// enable textwatcher on et2 again
et2.addTextChangedListener(TextWatcher_EdTwo);
}
}
and will do it for the other textWatcher , this way you will avoid infinite loop
You should implement a TextWatcher, It works pretty much like how it sounds. When the user changes (adds/removes text from) what is existing in the EditText, it will "Activate" this class. To test it out, you can use logs or set a breakpoint at any one of these statements.
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Your action here
edit = fromEditText.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
}
}
and in onCreate, add this to connect your EditText to the TextWatcher
fromEditText.addTextChangedListener(new MainActivity.MyTextWatcher(fromEditText));
You can add a bunch of EditText's to a single TextWatcher. All you need to do is rinse and repeat. Just change the name of the respective EditText and add it to the TextWatcher. Be aware, that if you have some EditText change the text of another EditText, it can result in an infinite loop.
this is my code....
StudentLogin.java class
public class StudentLogin extends Activity implements OnClickListener, OnItemSelectedListener{
Spinner sp1,sp2;
EditText reg;
Button b1,b2,b3;
String a1,a2,studreg,studdept,studyr;
SQLiteDatabase db1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_login);
reg=(EditText) findViewById(R.id.editText1);
sp1=(Spinner)findViewById(R.id.spinner1);
sp2=(Spinner)findViewById(R.id.spinner2);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Cursor c=db1.rawQuery("Select * from StudReg", null); // Im getting an error here
int count=c.getCount();
int flag=0;
c.moveToFirst();
String regno=reg.getText().toString();
String yr=a1;
String dept=a2;
Toast.makeText(getApplicationContext(), regno, Toast.LENGTH_LONG).show();
if(regno.trim().length()>0&&!yr.equals("Select Year")&&!dept.equals("Select Dept"))
{
for(int i=0;i<count;i++)
{
studreg=c.getString(c.getColumnIndex("register"));
studdept=c.getString(c.getColumnIndex("deptmt"));
studyr=c.getString(c.getColumnIndex("year"));
if(regno.equals(studreg)&&yr.equals(studyr)&&dept.equals(studdept))
{
flag=1;
break;
}
c.moveToNext();
}
c.close();
if(flag==1)
{
Intent inn=new Intent(StudentLogin.this,StudyMaterials.class);
startActivity(inn);
}
else
{
Toast.makeText(getApplicationContext(), "Invalid User!\nKindly try again..", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Kindly fill all the fields..", Toast.LENGTH_SHORT).show();
}
}
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intt=new Intent(StudentLogin.this,StudentRegister.class);
startActivity(intt);
}
});
b3=(Button)findViewById(R.id.button3);
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent int1=new Intent(StudentLogin.this,Update.class);
startActivity(int1);
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p, View v,
int a, long l) {
// TODO Auto-generated method stub
a1=p.getItemAtPosition(a).toString();
//Toast.makeText(getApplicationContext(), a1, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p, View v,
int a, long l) {
// TODO Auto-generated method stub
a2=p.getItemAtPosition(a).toString();
//Toast.makeText(getApplicationContext(), a2, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
List<String> categories = new ArrayList<String>();
categories.add("Select Department");
categories.add("CSE");
categories.add("IT");
categories.add("CIVIL");
categories.add("MECH");
categories.add("ECE");
categories.add("EEE");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(dataAdapter);
List<String> categories1 = new ArrayList<String>();
categories1.add("Select Year");
categories1.add("I");
categories1.add("II");
categories1.add("III");
categories1.add("IV");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(dataAdapter1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.student_login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> p, View v, int it,
long l) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This code validates whether the user is already registered or not..
Please help me solve this error...
you need to initialize database
//dbHelper its a helper class for database
database = dbHelper.getWritableDatabase();
You have given the table name but you are not saying it on which db the table exists(as db1 is not initialized).So follow #Madhur answer to solve this null pointer exception.Also a suggestion when working with db(better to use loaders instead of working on MainThread).
I have couple of activities. On the mainActivity I have 4 buttons each leads to another activity.
On three of the activities I activate a thread which draws in a canvas and in each of them I have a button to return to the mainActivity. I have tried using:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// i tried also (theClassName.this,MainActivity.Class)
startActivity(i);
When I clicked on the return button, I did return to the mainActivity but the app stopped responding (it alerted me that the app isn't responding and I had to choose between waiting or exiting the app. Waiting doesn't help).
When I used
finish();
instead,
And clicked on the return button, I returned to the home screen of the device (went out of the app) but didn't exit it - I could still go back to the app using the task manager, and when I did it put me back in the activity I entered and not the mainActivity.
As I said I have 4 buttons on the mainActivity and when I use the fourth one it goes to another activity that doesn't activate a thread, it only has listView, and when I return from it to the mainActivity it does work.
How can I fix it? Thanks for the help
*when the problem occurs there is no error stack trace.
*if you need to see any code tell and I'll be happy to post it here
The code:
MainActivity:
public class MainActivity extends Activity {
Button classic;
Button vsPlayer;
Button vsComp;
// Button settings;
Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
classic=(Button) findViewById(R.id.Classic);
classic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ClassicActivity.class);
startActivity(i);
}
});
vsPlayer=(Button) findViewById(R.id.PlayerVSPlayer);
vsPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,VsPlayerActivity.class);
startActivity(i);
}
});
vsComp=(Button) findViewById(R.id.PlayerVSComp);
vsComp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,VsCompActivity.class);
startActivity(i);
}
});
/* settings=(Button) findViewById(R.id.Settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
});
*/
scores=(Button) findViewById(R.id.Scores);
scores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ScoresActivity.class);
startActivity(i);
}
});
}//onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mains, menu);
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
MainActivity.this.finish();
}
}
-=------ some other activity:
public class ClassicActivity extends Activity {
Classic g;
ImageView left;
ImageView right;
ImageView up;
ImageView down;
TextView pause;
TextView back;
TextView scoretv;
LinearLayout surface;
LinearLayout screen;
LinearLayout stoped;
LinearLayout gameover;
ScoreDataSource sds;
Button no;
Button yes;
EditText name;
Button continueb;
Button leave;
//protected static TextView MyScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*requestWindowFeature(Window.FEATURE_NO_TITLE);
v= new GameView1(this);
setContentView(v);
*/
setContentView(R.layout.activity_classic);
sds=new ScoreDataSource(this);
gameover=(LinearLayout) findViewById(R.id.gameover);
screen = (LinearLayout)findViewById(R.id.screen);
surface = (LinearLayout)findViewById(R.id.surface);
g= new Classic(this, surface);
surface.addView(g);
//MyScore=(TextView) findViewById(R.id.MyScore);
//MyScore.setText("My score:"+gv.getPoints());
left=(ImageView) findViewById(R.id.left);
right=(ImageView) findViewById(R.id.right);
up=(ImageView) findViewById(R.id.up);
down=(ImageView) findViewById(R.id.down);
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="LEFT"&&g.snake.getDir()!="RIGHT"){
g.snake.Left();
}
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="RIGHT"&&g.snake.getDir()!="LEFT"){
g.snake.Right();
}
}
});
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="UP"&&g.snake.getDir()!="DOWN"){
g.snake.Up();
}
}
});
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="DOWN"&&g.snake.getDir()!="UP"){
g.snake.Down();
}
}
});
pause=(TextView) findViewById(R.id.Pause);
back=(TextView) findViewById(R.id.Back);
stoped=(LinearLayout) findViewById(R.id.stoped);
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(g.getRunning()){
pause.setText("continue");
g.setRunning(false);
}
else{
pause.setText("pause");
g.setRunning(true);
new Thread(g.snakethread).start();
}
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
g.setRunning(false);
stoped.setVisibility(View.VISIBLE);
}
});
no=(Button) findViewById(R.id.no);
yes=(Button) findViewById(R.id.yes);
continueb=(Button) findViewById(R.id.Continue);
leave=(Button) findViewById(R.id.leave);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
name=(EditText) findViewById(R.id.name);
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String date = df.format(c.getTime());
sds.open();
Score s=new Score(0,name.getText().toString(),date, g.getPoints(),"Classic");
s=sds.createScore(s);
sds.close();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
continueb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stoped.setVisibility(View.GONE);
g.setRunning(true);
new Thread(g.snakethread).start();
}
});
leave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
scoretv=(TextView) findViewById(R.id.scoretv);
screen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(g.getGameover()){
scoretv.setText("Your score is:"+g.getPoints());
gameover.setVisibility(View.VISIBLE);
g.setGameover(false);
}
}
});
}
#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;
}
}
----ClassicActivity usus this activity:
public class Classic extends SurfaceView implements Runnable {
private boolean isRunning=false;
private final long FPS=8;//MAX is 16
final float scale = Resources.getSystem().getDisplayMetrics().density;
float PART_SIZE= 10*scale;
private SurfaceHolder holder;
Thread snakethread;
static SnakePlayer snake;
Arena a;
LinearLayout view;
Bitmap arena;
Food food1;
Boolean gameover;
int points;
Paint writePB=new Paint();
Paint writePR=new Paint();
public Classic(Context context,LinearLayout view) {
super(context);
this.gameover=false;
this.view=view;
this.a=new Arena(view,PART_SIZE,33,36,1,0);
this.food1=new Food(PART_SIZE,"GRAY");
points=0;
writePB.setColor(Color.BLACK);
writePB.setTextSize(PART_SIZE);
writePR.setColor(Color.RED);
writePR.setTextSize(PART_SIZE);
snakethread=new Thread(this);
holder= getHolder();
holder.addCallback(new SurfaceHolder.Callback(){
#Override
public void surfaceCreated(SurfaceHolder arg0) {
setRunning(true);
snakethread.start();
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,int arg3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
setRunning(false);
while(true){
try {
snakethread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
snake=new SnakePlayer(0+3*PART_SIZE, 0+3*PART_SIZE, "RIGHT",PART_SIZE,2,"RED","BLACK");
}
#SuppressLint("WrongCall")
#Override
public void onDraw(Canvas c) {
a.onDraw(c);
c.drawText("Your Score:"+points, 5*scale, 10*scale, writePB);
food1.drawFood(c);
snake.onDraw(c);
}
#SuppressLint("WrongCall")
#Override
public void run() {
long stepPerSecond=1000/FPS;
long startTime;
long sleepTime;
Canvas c = null;
while(isRunning){
startTime=System.currentTimeMillis();
c = null;
try{
c=this.getHolder().lockCanvas();
onDraw(c);
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
AllChecks(c);
sleepTime= stepPerSecond-(System.currentTimeMillis()-startTime);
if(sleepTime>0)
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(gameover){
try{
c=this.getHolder().lockCanvas();
c.drawText("GAMEOVER", 125*scale, 150*scale, writePR);
c.drawText("Touch Anywhere To Continue ", 87*scale, 162*scale, writePR);
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
}
}
boolean firstTime=true;
public void AllChecks(Canvas c){
/*
* Call all the right function, to check if the snake has bumped in a wall, or eaten a food.
*/
if(Arena.WallCollision(snake.getxLoc(), snake.getyLoc())){
setRunning(false);
gameover=true;
}
if(snake.snakeCollisionNoHead(snake.getxLoc(), snake.getyLoc())){
setRunning(false);
gameover=true;
}
if(firstTime){
firstTime=false;
changeFoodLoc(food1);
}
if(food1.hasEaten(snake.getxLoc(), snake.getyLoc())){
changeFoodLoc(food1);
snake.Add();
points+=10;
}
}
public void changeFoodLoc(Food food){
/*
* if a snake has eaten a food it changes the location of the food randomly
*/
Random rnd = new Random();
food.x=(rnd.nextInt(32) + 3)*food.SIZE;
food.y=(rnd.nextInt(35) + 1)*food.SIZE;
if(snake.snakeCollision(food.getX(), food.getY()))
changeFoodLoc(food);
}
public void setRunning(boolean b){
isRunning=b;
}
public Boolean getRunning(){
return isRunning;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public Boolean getGameover() {
return gameover;
}
public void setGameover(Boolean gameover) {
this.gameover = gameover;
}
}
First I would try removing the override on the MainActivity for onPause - you do not need to call finish. In your second activity, if you want to go back to the MainActivity- call finish on the 2nd activity and it should go back to the MainActivity.
How do I get values from a SeekBar?
I have a code of a class that has three SeekBars (PRICEbar)
I want to pass the values of these SeekBars to next Activity (screen)
as Intents
I know how toimplement OnClickListener but how can I extract the
values from the SeekBars?
ex: if PRICEbar is pointing to value 10 ... I need to get the value of 10
Filters.java
public class Filters extends Activity implements OnSeekBarChangeListener{
// declare text objects variables
private SeekBar PRICEbar;
private TextView PRICEtextProgress,DISTANCEtextProgress, RATINGtextProgress;
Button back;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load the layout
setContentView(R.layout.filters);
PRICEbar = (SeekBar)findViewById(R.id.PRICEseekBarID); // make seekbar object
PRICEbar.setOnSeekBarChangeListener(this);
PRICEbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
PRICEtextProgress = (TextView)findViewById(R.id.PRICEtextViewProgressID);
PRICEtextProgress.setText("Price:: Rs "+progress);
seekBar.setMax(100);
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (seekBar == PRICEbar)
PRICEtextProgress.setText("Price:: Rs "+progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
The SeekBar class is a subclass of ProgressBar, which contains a getProgress() method.
Calling PRICEbar.getProgress() will return the value you are looking for.
I'm trying to create a dynamic listview. I can add an item but i can't remove it right now. The code actually it's very simple and every guide i saw are too much complicated for me and my code. I want something simple to add in my MainActivity to remove the item selceted. I don't care in which way, swipe like gmail or by click or any other way.. I just want i simple way to remove an element of the list. This is the Activity
public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.addbtn);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert a value");
return false;
} else {
return true;
}
}
}
Is it possible insert some part of code to remove an item inside my activity code? Thanks
try this, While ListView item long ClickListener you can do it
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
YourActivity.this);
adb.setTitle("Are you sure want to delete this item");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
}
});
adb.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
adb.show();
return false;
}
});
This should help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
Put this method in your onCreate:
lvItem .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
});
}
Of course it is possible.
ArrayList.html#remove
Or if you don't know the index just iterate through the list.
Calling remove in foreach loop in Java
Do this way..
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
To delete item from list just do one thing, get onLongClickListener of listView.
Then open the context menu which has two options
Delete
Cancel
When user picks first item delete it from list. Then call listadapter notify datasetChanged method.
Use this library, I used this and it works very fine, if you prefer Swipe try this:
https://github.com/47deg/android-swipelistview
Try below code:
single click:
listview .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
showDialog(int position);
});
}
public void showDialog(int position){
AlertDialog alertDialog;
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
alertDialog = builder.create();
alertDialog.setOnDismissListener(new myOnDismissListener());
alertDialog.setTitle(TITLE OF DIALOG);
alertDialog.setMessage(MESSAGE YOU WANT TO SHOW IN DIALOG);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
YOUR ARRAY.remove(position);
YOUR ADAPTER.notifyDataSetChanged();
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertDialog.show();
}