save .class name in a listview through sharedpreferences [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hi i am making a dictionary app and i want that when i open a word from a listview , then in the word page (word.class) (where the word meaning is explained), i want to add that word into a favorite.class activity in a listview shape and later on i can retrive that word from the listview.
i want to hit the favorite button in one java class and to save that word(string which is class name for that word) in anathor activity of favorite.class. the favorite button is actually is the menu item visible on the action bar. please explain me all the code and the way how can i do this..please give some code so to acomplish it.
public class Atherosclerosis extends Activity {
// declare variables for the table of content and paragraph heading here//
ScrollView scrollView;
TextView sign_atherosclerosis;
TextView sign_id;
TextView def_id;
TextView def_atherosclerosis;
TextView riskfac_id;
TextView riskfac_atherosclerosis;
TextView pathophy_id;
TextView pathophy_atherosclerosis;
TextView Dx_id;
TextView Dx_atherosclerosis;
TextView Rx_id;
TextView Rx_atherosclerosis;
TextView prevent_id;
TextView prevent_atherosclerosis;
TextView compl_id;
TextView compl_atherosclerosis;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atherosclerosis);
//here relate the variable for clickonlistener activity and direct scrolldown activity //
final ScrollView scrollView=(ScrollView)findViewById(R.id.scrollatherosclerosis);
TextView sign_id=(TextView)findViewById(R.id.Signandsymptomps_id);
final TextView sign_atherosclerosis=(TextView)findViewById(R.id.Signandsymptoms_atherosclerosis);
TextView def_id=(TextView)findViewById(R.id.definition_id);
final TextView def_atherosclerosis=(TextView)findViewById(R.id.definition_atherosclerosis);
TextView riskfac_id=(TextView)findViewById(R.id.riskfactor_id);
final TextView riskfac_atherosclerosis=(TextView)findViewById(R.id.riskfactor_atherosclerosis);
TextView pathophy_id=(TextView)findViewById(R.id.pathophysiology_id);
final TextView pathophy_atherosclerosis=(TextView)findViewById(R.id.pathophysiology_atherosclerosis);
TextView Dx_id=(TextView)findViewById(R.id.Diagnosis_id);
final TextView Dx_atherosclerosis=(TextView)findViewById(R.id.diagnosis_atherosclerosis);
TextView Rx_id=(TextView)findViewById(R.id.treatment_id);
final TextView Rx_atherosclerosis=(TextView)findViewById(R.id.treatment_atherosclerosis);
TextView prevent_id=(TextView)findViewById(R.id.prevention_id);
final TextView prevent_atherosclerosis=(TextView)findViewById(R.id.prevention_atherosclerosis);
TextView compl_id=(TextView)findViewById(R.id.complication_id);
final TextView compl_atherosclerosis=(TextView)findViewById(R.id.complication_atherosclerosis);
// this code is used for the action bar color change//
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#6B8E23")));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// this is the code for jumping from the table of content to the paragraph//
sign_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (sign_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
def_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (def_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
riskfac_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (riskfac_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
pathophy_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (pathophy_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
Dx_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (Dx_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
Rx_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (Rx_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
prevent_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (prevent_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
compl_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (compl_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
}
// this is for the options selected from the menu button of mobile//
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.atherosclerosis, menu);
return true;
}
// for starting activity from the option or menu//
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.id_search:
Intent newActivity0 = new Intent(this,Search.class);
startActivity(newActivity0);
return true;
case R.id.id_favorit:
SharedPreferences sp = this.getSharedPreferences("bookmarks", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("favorite", "com.kmcpesh.shortreviewofcardiology.Favorite");
editor.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is my favorite.class activity
public class Favorite extends Activity {
private TextView mEmptyText;
private LinearLayout mBookmarkLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite);
mEmptyText = (TextView) findViewById(R.id.empty_textview);
mBookmarkLayout = (LinearLayout) findViewById(R.id.bookmark_insert_point);
getAllKeys();
}
private void getAllKeys()
{
SharedPreferences sp = this.getSharedPreferences("bookmarks", MODE_PRIVATE);
Map<String,?> keys = sp.getAll();
int count = 0;
for(Map.Entry<String,?> entry : keys.entrySet())
{
String value = entry.getValue().toString();
System.out.println("!!!!!!!!!!!!!!!!!value = "+value);
String delimiter = ",";
String[] values_array = value.split(delimiter);
addBookmark(values_array);
count++; //keep track of the number of bookmarks
}
//if there are no bookmarks, display a text view saying so. Otherwise, make the text view go away
if (count == 0)
{
mEmptyText.setVisibility(View.VISIBLE);
mEmptyText.setText(getString(R.string.no_bookmark));
}
else
mEmptyText.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
private void addBookmark(String[] values_array)
{
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.favorite, null);
TextView text = (TextView) v.findViewById(R.id.bookmark_text);
text.setText(values_array[1]);
// insert into main view
mBookmarkLayout.addView(v, 0, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
System.out.println("!!!!!!!!!!!!!!!!!!!!Just added a view");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favorite, menu);
return true;
}
}

SharedPreferences in Android is generally used to store key=value pairs, not lists such as the one you describe. To store a value into SharedPreferences, you can do this:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor ed = sp.edit();
ed.putString("myKey", "myValue");
And then to retrieve a string key from SharedPreferences, you would do this:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String value = sp.getString("myKey", "");
You could have a comma-delimited list of favorite words stored in here, and just parse the list:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor ed = sp.edit();
ed.putString("favorites", "dog,cat,bird,fish");
And then to retrieve them:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String favorites = sp.getString("myKey", "");
String[] words = values.split(",");
System.out.println(Arrays.toString(words));
Then you have an array containing all of your favorite words.
[dog, cat, bird, fish]

Related

NullPointerException when using Handler for updating progressBar [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainActivity extends Activity {
Button button = (Button)findViewById(R.id.btn);
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateHandler.post(updateThread);
}
});
}
#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);
}
Handler updateHandler = new Handler(){
public void handleMessage(Message msg) {
bar.setProgress(msg.arg1);
updateHandler.post(updateThread);
};
};
Runnable updateThread = new Runnable() {
int i = 0;
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("------------");
i = i+10;
Message msg = updateHandler.obtainMessage();
msg.arg1 = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateHandler.sendMessage(msg);
if (i==100) {
updateHandler.removeCallbacks(updateThread);
}
}
};
}
Logcat:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.zxy.handlerpbtest/com.zxy.handlerpbtest.MainActivity}: java.lang.NullPointerException
You can rewrite this code of lines:
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
Button button = (Button)findViewById(R.id.btn);
As:
public class MainActivity extends Activity {
Button button ;
ProgressBar bar ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar = (ProgressBar)findViewById(R.id.pbar);
button = (Button)findViewById(R.id.btn);
.....
}}
Then you will not get null pointer exception.
This line
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
Button button = (Button)findViewById(R.id.btn);
should be in your onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
Button button = (Button)findViewById(R.id.btn);
}
Here is Complete Solution :
public class MainActivity extends Activity {
Button button;
ProgressBar bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button = (Button) findViewById(R.id.btn);
bar = (ProgressBar) findViewById(R.id.pbar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateHandler.post(updateThread);
}
});
}
Handler updateHandler = new Handler() {
public void handleMessage(Message msg) {
bar.setProgress(msg.arg1);
updateHandler.post(updateThread);
}
};
Runnable updateThread = new Runnable() {
int i = 0;
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("------------");
i = i + 10;
Message msg = updateHandler.obtainMessage();
msg.arg1 = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateHandler.sendMessage(msg);
if (i == 100) {
updateHandler.removeCallbacks(updateThread);
}
}
};
}

How to Reference Buttons in the same Activity from a Custom View

I am trying to make a simple drawing application, but am running into problems switching the paint color.Here is the tutorial I used to get to the point I am at. Here is my code:
Drawing_View.java
public class Drawing_View extends View {
private Path path = new Path();
private Paint paint = new Paint();
public String paint_color = "#FFBB00";
public Drawing_View(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5f);
paint.setColor(Color.parseColor(paint_color));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventY = event.getY();
float eventX = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Set a new starting point
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// Connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
invalidate();
return true;
}
}
Here is the code for the activity the custom view sits inside.
Drawing_Main.java
public class Drawing_Main extends ActionBarActivity {
Button green_light,green_dark,blue_light,blue_dark,blue_verydark,purple,magenta,red,orange_dark,orange_light,orange_lightest,yellow,black;
String btn_color_hex;
SharedPreferences.Editor editor = getSharedPreferences("paint_color", MODE_PRIVATE).edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_creation);
green_light = (Button)findViewById(R.id.button1);
green_dark = (Button)findViewById(R.id.button2);
blue_light = (Button)findViewById(R.id.button3);
blue_dark = (Button)findViewById(R.id.button4);
blue_verydark = (Button)findViewById(R.id.button5);
purple = (Button)findViewById(R.id.button6);
magenta = (Button)findViewById(R.id.button7);
red = (Button)findViewById(R.id.button8);
orange_dark = (Button)findViewById(R.id.button9);
orange_light = (Button)findViewById(R.id.button10);
orange_lightest = (Button)findViewById(R.id.button11);
yellow = (Button)findViewById(R.id.button12);
black = (Button)findViewById(R.id.button13);
green_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn_color_hex="#0fad00";
editor.putString("paint_color_hex", btn_color_hex);
editor.commit();
}
});
green_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_verydark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
purple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
magenta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_lightest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
yellow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
black.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#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_emojicreation, 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);
}
}
As you can see I started exploring the sharedPreferences option, after my attempt to create a service failed. If a Service is the best option, how can I make Drawing_View.java constantly listen for color changes? Thanks everyone!
You could add a setPaintColor method to your Drawing_View class. That way, you would not need to use SharedPreferences
and you could just change the paint color in your onClickListeners.
Something like this should work:
In your Drawing_View class, add:
public void setPaintColor (String color) {
paint.setColor(Color.parseColor(color));
}
In your onClickListener, call the setPaintColor method:
drawingView.setPaintColor(color);
I assume that your Drawing_View is already instantiated.
Update
You need to instantiate your Drawing_View the same way you instantiated the Buttons in your activity's onCreate method.
public class Drawing_Main extends ActionBarActivity {
...
Drawing_View drawingView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_creation);
drawingView = (Drawing_View)findViewById(R.id.drawing_view);
green_light = (Button)findViewById(R.id.button1);
...
I hope this helps.

How do I disable my Seekbar in Android with a Switch?

I want to disable my Seekbar and buttons with a switch which is Powerswitch
Here is a code snippet:
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
String sval = String.valueOf(i);
speakerVal.setText(sval);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// button - Favorite Channel ABC
cabc = (Button) findViewById(R.id.buttonABC);
cabc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set Favorite
curChannel.setText("007");
}
});
and here is my switch code:
final Switch switch1 = (Switch) findViewById(R.id.switch1);
switch1.setOnCheckedChangeListener(this);
more switch code:
public void onSwitchClicked(View view) {
final TextView PowerSwitch = (TextView) findViewById(R.id.PwrSwitchVal);
Switch sw = (Switch) view;
if (sw.isChecked()) {
PowerSwitch.setText("ON");
pwr = true;
} else {
PowerSwitch.setText("OFF");
pwr = false;
}
}
I know I can use the switch.isChecked(), but when I change the seekba1.setEnabled(false), I can't seem to get it to turn back on.
I haven't even tried to disable the buttons yet.
any help would be appreciated.
In your onSwitchClicked method, you should be calling seekbar.setEnabled in the if checked if-else statement. If checked seekbar.setEnabled(true) else seekbar.setEnabled(false)
try this.
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
if (arg1) {
seekbar1.setEnabled(true);
}
else{
seekbar1.setEnabled(false);
}
}
});

Convert Editable to Edittext

I have set a tag to An Edittext variable.i want get that tag inside text TextWatcher afterTextChanged method.but there is a Editable parameter not Edittext.
here is my code.....
EditText filled = new EditText(DamageCount.this);
filled.setId(100);
filled.setTag(5);
and i want get that tag in
#Override
public void afterTextChanged(Editable s) {
}
this method
------Edited----------------
my whole java class
public class DamageCount extends Activity {
private Button button_next;
static TableLayout tl = null;
private DbWorker dbworker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_damage_count);
DamageCount.this
.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
button_next = (Button) findViewById(R.id.button_next);
tl = (TableLayout) findViewById(R.id.show_competitor_product);
dbworker = new DbWorker(this);
Static_Values.arrayListdam_no = new ArrayList<DamegeItemSerialNoModel>();
button_next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*Intent new_one = new Intent(DamageCount.this,
Invoice_or_prev.class);
startActivity(new_one);
finish();*/
for(DamegeItemSerialNoModel dmmm :Static_Values.arrayListdam_no)
{
System.out.println("Item id is "+dmmm.getItem_id()+" serial no is "+dmmm.getSerial_no());
}
}
});
Cursor cur_products= dbworker.getAllProduct();
int i=0;
if(cur_products.moveToFirst())
{
do{
i++;
// Static_Values.item.put(, value)
add_tbl_row(i,cur_products.getString(3),cur_products.getString(1));
}
while(cur_products.moveToNext());
}
else {
}
cur_products.close();
}
public void add_tbl_row(int value, String name, String tag) {
Static_Values.damaged_id=tag;
TableRow new_row = new TableRow(DamageCount.this);
System.out.println(Static_Values.damaged_id+" id bbb");
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher);
new_row.addView(imageView);
TextView size = new TextView(DamageCount.this);
size.setId(1);
size.setText(name);
size.setPadding(5, 5, 5, 5);
new_row.addView(size);
EditText filled = new EditText(DamageCount.this);
filled.setId(100 * value);
filled.setTag(tag);
filled.setHint("Enter Damaged");
filled.setInputType(InputType.TYPE_CLASS_NUMBER);
new_row.addView(filled);
filled.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
// Toast.makeText(DamageCount.this, s.toString(), Toast.LENGTH_SHORT).show();
if(s.toString().equals("")==false)
{
final LinearLayout layout = new LinearLayout(DamageCount.this);
layout.setOrientation(LinearLayout.VERTICAL);
Button dialogButton = new Button(DamageCount.this);
dialogButton.setText("Add");
// dialogButton.setBackgroundColor(R.drawable.yellobutton);
Static_Values.num_of_serials=Integer.parseInt(s.toString());
for(int i=1;i<Integer.parseInt(s.toString())+1;i++)
{
EditText serial = new EditText(DamageCount.this);
serial.setId(33*i);
serial.setHint("Enter serial");
layout.addView(serial);
}
layout.addView(dialogButton);
final Dialog dialog = new Dialog(DamageCount.this);
dialog.setContentView(layout);
dialog.setTitle("Serial Numbers");
dialog.getWindow().setTitleColor(Color.BLUE);
// set the custom dialog components - text, image and button
// dialog.setContentView(filled);
// dialog.getOwnerActivity().setContentView(filled);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 1; i < Static_Values.num_of_serials+1; i++) {
View vv = dialog.findViewById(33*i);
EditText et=(EditText)vv;
System.out.println(et.getText().toString());
DamegeItemSerialNoModel dism = new DamegeItemSerialNoModel();
dism.setItem_id(Static_Values.damaged_id);
System.out.println(Static_Values.damaged_id);
dism.setSerial_no(et.getText().toString());
Static_Values.arrayListdam_no.add(dism);
}
Static_Values.num_of_serials = 0;
dialog.dismiss();
}
});
dialog.show();
}
}
});
tl.addView(new_row, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
}
Create a constructor in yout Textwatcher class and pass the editext to it.
public class MyTextWatcher implements TextWatcher
{
private transient EditText editText = null;
public MyTextWatcher(EditText editText)
{
super();
this.editText = editText;
}
#Override
public void afterTextChanged(Editable arg0)
{
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
}
If you want to convert Editable to simple text line (String), use this in your method:
#Override
public void afterTextChanged(Editable s) {
String str = s.toString();
}

Viewpager setCurrentItem() doesn't update onPageSelected()

When I swipe between questions, it loads current page number correctly
BUT when I use next button, first click doesnt loads pagenumber ( I mean onPageSelected() doesnt work.) second and other clicks loads content but it loads 1 page previous.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
mPager = (ViewPager)findViewById(R.id.pager);
QuestionPagerAdapter mAdapter = new QuestionPagerAdapter();
mPager.setAdapter(mAdapter);
OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
tv.setText( mPager.getCurrentItem()+"");
}
};
mPager.setOnPageChangeListener(pageChangeListener);
Question.next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(getItem(+1));
}
}
private int getItem(int i) {
int a = mPager.getCurrentItem();
i += a;
return i;
}
});
Why not just doing this in your listener:
mPager.setCurrentItem(mPager.getCurrentItem() + 1);

Categories

Resources