Creating a TextView for the first 46 Fibonacci numbers on Android - android

I have this so far, and the result is a blank screen. What might I do to achieve the desired effect of listing the first 46 Fibonacci numbers?
TextView fibNum;
static int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static int fib(int n) {
int prev1=0, prev2=1;
for( i=0; i<n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
public void main(String[] args) {
for (int i=0; i<=46; i++)
fibNum = new TextView(this);
fibNum.setText(String.valueOf(fib(i)+", "));
}
}

First, just creating a TextView doesn't make it part of the view hierarchy being displayed. Second, Android will never call your main method. Third, I don't see how your code even compiles; the loop inside main only covers the assignment to fibNum, so at the call to setText, the variable i is not even in scope.
Putting all that aside, let's assume your activity_main.xml layout file already has a TextView in it with id #+id/text where you want to display the numbers. I suggest something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.text);
text.setText(getFib(46));
}
public static int fib(int n) {
int prev1 = 0, prev2 = 1;
for(int i = 0; i < n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
public static String getFib(int n) {
StringBuilder sb = new StringBuilder(fib(0));
for (int i = 1; i < n; ++i) {
sb.append(", ");
sb.append(fib(i));
}
return sb.toString();
}
This assumes that calculating 46 Fibonacci numbers doesn't take an inordinate amount of time. If it does, you'll have to move the calculation to a worker thread (probably easiest to do using an AsyncTask).

Related

Android-SharedPreferences with EditText which created with For Loop

I created EditTexts with "for loop" and I want to save datas from EditText with using SharedPreferences. I can manage this with creating EditTexts via xml but this takes lots of time and efforts. Below you can see codes.With second "for loop" i have been creating 15 EditTexts (numbers will increase) and I want to store datas from those EditTexts for some calculations. How can I use SharedPreferences with "for loop" for those EditTexts?
public class MainActivity extends AppCompatActivity {
private ScrollView sV;
private LinearLayout pnl;
private GridLayout gL;
private TextView tV;
private Button btn;
private EditText eT;
private void init() {
sV = new ScrollView(this);
hsV = new HorizontalScrollView(this);
pnl = new LinearLayout(this);
pnl.setOrientation(LinearLayout.VERTICAL);
gL = new GridLayout(this);
gL.setColumnCount(2);
final String[] title = getResources().getStringArray(R.array.title);
final String[] info = getResources().getStringArray(R.array.info);
for (int j = 0; j < 2; j++) {
tV = new TextView(this);
tV.setText(title[j]);
tV.setTextSize(20);
tV.setTypeface(Typeface.DEFAULT_BOLD);
tV.setTextColor(getResources().getColor(R.color.colorText));
gL.addView(tV);
}
for (int i = 0; i < 15; i++) {
tV = new TextView(this);
tV.setText(info[i]);
tV.setTextSize(20);
tV.setTextColor(getResources().getColor(R.color.colorText));
gL.addView(tV);
eT = new EditText(this);
eT.setTextSize(20);
eT.setInputType(InputType.TYPE_CLASS_NUMBER);
gL.addView(eT);
}
btn = new Button(this);
btn.setText("Save");
gL.addView(btn);
pnl.addView(gL);
sV.addView(pnl);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
setContentView(sV);
}
}
You can add tags on your EditTexts to identify them.
You can then use these tags as keys in your SharedPreferences, something like that :
for (int i = 0; i < 15; i++) {
eT = new EditText(this);
eT.setTextSize(20);
eT.setInputType(InputType.TYPE_CLASS_NUMBER);
// adding a tag to identify the EditText
String tag = "edit" + i;
eT.setTag(tag);
gL.addView(eT);
}
How to store
#Override
public void afterTextChanged(Editable editable) {
// get values
String key = (String)editable.getTag()
String value = editable.getText().toString()
// save in SharedPreferences
sharedPreferencesEditor.putString(key, values)
sharedPreferencesEditor.commit()
}

Recycler view with multiple layout items duplicate radio buttons on scroll

RecyclerView containing multiple layouts such as one row containing Edittext, radioButtons another row containing checkbox etc
Now when I input in first edit text and scroll the list then same inputed value gets copied in the last edit text visible on the screen.
Also if there are two radio buttons visible say radio1 and radio 2 then on scroll this becomes
radio1
radio2
radio1
radio2
i.e. radio1 and radio 2 are duplicated on scroll.
Can any one suggest some solution for the same?
Code for dynamic Edit Text
private void configureViewHolderText(final ViewHolderText holderText, final int position) {
if (questionsArrayList != null && questionsArrayList.size() > 0) {
String hint = questionsArrayList.get(position).getHelperText();
int characterLength = questionsArrayList.get(position).getCharLimit();
boolean isQuestionRequired = questionsArrayList.get(position).isRequired();
if (isQuestionRequired) {
holderText.getTv_dynamic_star().setVisibility(View.VISIBLE);
}
holderText.getTv_dynamic_text_view().setText(questionsArrayList.get(position).getQuestionText());
if (characterLength > 0) {
holderText.getEt_dynamic_edit_text().setFilters(new InputFilter[]{new InputFilter.LengthFilter(characterLength)});
}
if (hint != null && hint.equals("null") == false && hint.equals("") == false) {
holderText.getEt_dynamic_edit_text().setHint(hint);
} else {
holderText.getEt_dynamic_edit_text().setHint("Enter Answer");
}
holderText.getEt_dynamic_edit_text().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) {
editTextInput = holderText.getEt_dynamic_edit_text().getText().toString();
// SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
// SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
// hashAnswerInput.put(questionsArrayList.get(position).get_id(), editTextInput);
/*hashQuestionText.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).getQuestionText()) ;
hashQuestionId.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).get_id()) ;
hashAnswerType.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).getAnswerType());*/
/* for(Map.Entry map : hashAnswerInput.entrySet() )
{
dynamicEditTextAnswer = String.valueOf(map.getValue());
//answers.setAnswerText(inputAnswer);
}*/
/*if(dynamicEditTextAnswer!= null)
{*/
SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
answers.setQuestionId(questionsArrayList.get(position).get_id());
answers.setAnswerText(editTextInput);
answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
answersArrayList.put(questionsArrayList.get(position).get_id(),answers);
/* }*/
/*for(Map.Entry map : hashQuestionText.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setQuestionText(inputAnswer);
}
for(Map.Entry map : hashQuestionId.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setQuestionId(inputAnswer);
}
for(Map.Entry map : hashAnswerType.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setAnswerType(inputAnswer);
}*/
// SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
// SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
// answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
// answers.setQuestionId(questionsArrayList.get(position).get_id());
// answers.setAnswerText(editTextInput);
// answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
// answersArrayList.add(answers);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
Code for dynamic radio button
private void configureViewHolderRadioGroup(final ViewHolderRadioGroup holderRadioGroup, final int position) {
if (questionsArrayList != null && questionsArrayList.size() > 0) {
ArrayList<String> radioOptionsList = new ArrayList<String>();
for (int j = 0; j < questionsArrayList.get(position).getOptions().size(); j++) {
String radioItemName = questionsArrayList.get(position).getOptions().get(j).getOptionText();
radioOptionsList.add(radioItemName);
}
holderRadioGroup.getTv_dynamic_text_view().setText(questionsArrayList.get(position).getQuestionText());
boolean isQuestionRequired = questionsArrayList.get(position).isRequired();
if (isQuestionRequired) {
holderRadioGroup.getTv_dynamic_star().setVisibility(View.VISIBLE);
}
int totalCount = questionsArrayList.get(position).getOptions().size();
final RadioButton[] rb = new RadioButton[totalCount];
for (int i = 0; i < totalCount; i++) {
rb[i] = new RadioButton(context);
rb[i].setText(radioOptionsList.get(i));
rb[i].setId(i);
holderRadioGroup.getRg_dynamic_radio_group().addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
holderRadioGroup.getRg_dynamic_radio_group().setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i = 0; i < group.getChildCount(); i++) {
RadioButton rg = (RadioButton) group.getChildAt(i);
if (rg.getId() == checkedId) {
radioInput = rg.getText().toString();
Toast.makeText(context, radioInput, Toast.LENGTH_SHORT).show();
SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
answers.setQuestionId(questionsArrayList.get(position).get_id());
answers.setAnswerText(radioInput);
answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
// answersArrayList.add(answers);
answersArrayList.put(questionsArrayList.get(position).get_id(),answers);
ArrayList<String> relatedQuestionsId = new ArrayList<String>();
relatedQuestionsId = questionsArrayList.get(position).getOptions().get(i).getRelatedQuestionIds();
if (relatedQuestionsId != null && relatedQuestionsId.size() > 0) {
for (int k = 0; k < relatedQuestionsId.size(); k++) {
((LinearLayout) holderRadioGroup.getLl_parent_radio_child()).removeAllViews();
getRadioChildQuestions(relatedQuestionsId, holderRadioGroup, k);
}
}
return;
}
else if(rg.getId() != checkedId) {
ArrayList<String> relatedQuestionsId = new ArrayList<String>();
/*for (int j = 0; j < questionsArrayList.get(position).getOptions().size(); j++) {*/
relatedQuestionsId = questionsArrayList.get(position).getOptions().get(i).getRelatedQuestionIds();
if (relatedQuestionsId != null && relatedQuestionsId.size() > 0) {
for (int k = 0; k < relatedQuestionsId.size(); k++) {
((LinearLayout) holderRadioGroup.getLl_parent_radio_child()).removeAllViews();
}
}
}
}
}
});
}
}
}
The recycler view reuses your view holders instances.
So if you are scrolling and a layout is leaving the screen at the top, it gets reused, when the same layout should be used for a new item at the bottom.
You need to reset all dynamic attribues in the onBindViewHolder-method.
For a better understanding set two debug points inside your recycler view adapter:
One inside the onCreateViewHolder-method and one inside the onBindViewHolder-method.
EDIT:
A sample for a working Recycler View Adapter can be found here: https://github.com/olLenz/Movies-with-Kotlin/blob/master/base/src/main/java/com/lenz/oliver/movieswithkotlin/ui/home/HomeAdapter.kt
The onCreateViewHolder-method creates a new instance of the ViewHolder.
The onBindViewHolder-method just calls the bind-method on a created ViewHolder instance. This bind-method sets all dynamic information to the given layout on every call.

Android: Save the activity state after a screen rotation

we are working on project in order to create an application to help autits to communicate.
In fact, after moving the ImageViews, all of them are getting back in place after my tablet's rotation.
We tried a lot of things and we finally have made this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.repas);
area1 = (LinearLayout) findViewById(R.id.area1);
area2 = (LinearLayout) findViewById(R.id.area2);
TypedArray arrayResources = getResources().obtainTypedArray(
R.array.resicon);
if( savedInstanceState != null ) {
int count_item = savedInstanceState.getInt("number_of_item");
int tab_item[] = new int[count_item];
for (int i = 0; i < count_item; i++) {
tab_item[i]=savedInstanceState.getInt("Sauvegarde_repas" +i);
}
for (int i = 0; i < arrayResources.length(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageDrawable(arrayResources.getDrawable(i));
imageView.setOnTouchListener(myOnTouchListener);
imageView.setId(i);
if (check(tab_item,i)){
area1.addView(imageView);
}
else{
area2.addView(imageView);
}
}
}
else {
for (int i = 0; i < arrayResources.length(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageDrawable(arrayResources.getDrawable(i));
imageView.setOnTouchListener(myOnTouchListener);
imageView.setId(i);
area2.addView(imageView);
}
arrayResources.recycle();
}
area1.setOnDragListener(myOnDragListener);
area2.setOnDragListener(myOnDragListener);
}
#Override
public void onSaveInstanceState(Bundle outState)
{
int count = area1.getChildCount();
View v = null;
outState.putInt("number_of_item", count);
for(int i=0; i<count; i++) {
v = area1.getChildAt(i);
outState.putInt("Sauvegarde_repas" + i, v.getId());
}
super.onSaveInstanceState(outState);
}
Here are my interrogations:
When I set an id, it's just "i", a very simple number. It doesn't seem very unique like a string "R.id.String_here" (even if I know that is converted in Integer), so how can I be sure to do a unique ID?
Do I have to save, one by one, the child of my layout? It's not possible to save the whole layout?
Do you have any advice to improve my code? (Because it looks dirty, isn't it ?)
Thank you very much for your help !

Store seekbar values in array

I want to store seek bar values that user selects by dragging thumb, in an array
You can do something like this:
private ArrayList<Seekbar> mSeekbars = new ArrayList<Seekbar>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// Your code where you set the content view
mSeekbars.add(((Seekbar) findViewById(R.id.seekbar1));
mSeekbars.add(((Seekbar) findViewById(R.id.seekbar2));
mSeekbars.add(((Seekbar) findViewById(R.id.seekbar3));
}
// To enable seekbars
private void onRadioButtonSelected() {
for (Seekbar seekbar : mSeekbars) {
seekbar.setEnabled(true);
}
}
// To get seekbar values
private ArrayList<Integer> saveSeekbarValues() {
ArrayList<Integer> values = new ArrayList<Integer>();
for (Seekbar seekbar : mSeekbars) {
values.add(seekbar.getProgress())
}
return values;
}
}
One other solution is to have a parent layout that holds all seekbars and enable/disable that layout instead of enabling/disable the individual seekbars. However, for the values, you will have to manually retrieve each seekbar's value.
You can put all seekbars in single view and get one by one child using iteration, and setEnable() them:-
// to enable seekbars
public void enableAllSeekBars()
{
int childcount = containerView.getChildCount();
for (int i=0; i < childcount; i++){
if(containerView.getChildAt(i) instanceof SeekBar)
{
SeekBar sb = (SeekBar)containerView.getChildAt(i);
sb.setEnabled(true);
}
}
}
// to get seekbar values
public ArrayList<Integer> getSeekBarValues()
{
ArrayList<Integer> values = new ArrayList<Integer>();
int childcount = containerView.getChildCount();
for (int i=0; i < childcount; i++){
if(containerView.getChildAt(i) instanceof SeekBar)
{
SeekBar sb = (SeekBar)containerView.getChildAt(i);
values.add(sb.getProgress())
}
}
return values;
}

ListView Pagination with NEXT and PREVIOUS buttons

I have a listview which loads 200 items using webservice. Where all 200 items are displaying in single listview.
I want to load first 1-20 items first and when i click NEXT button i need to load 21-40 items and so on. And vice-verse, when i click PREVIOUS button i need to load 1-20 items.
How to implement Pagination for this?
I tried :
static ArrayList<String> Code = new ArrayList<String>();
//Code is ArrayList where i get 200 items from Service
int rowSize = 20;
// rowSize is number of items i want per page
static ArrayList<String> TempCode = new ArrayList<String>();
//TempCode is temporary ArrayList where iam trying to store items per page
Button NextButton;
NextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int size = Code.size() / rowSize;
for (int j = 0; j < size; j++) {
final int k;
k = j;
addItem(k);
}
}
});
public void addItem(int count) {
TempCode.clear();
count = count * rowSize;
/**
* fill temp array list to set on page change
*/
for (int j = 0; j < rowSize; j++) {
TempCode.add(j, Code.get(count));
count = count + 1;
}
Adapter adapter=new Adapter(getApplicationContext(),TempCode);
listView.setAdapter(adapter);
}
Please help.
Thanks in advance.
int _currentPage = 1;
public int FeedCountPerPage = 20;
//Call the below code in one function on click of your next button
//And do the reverse on click of previous button
_currentPage += 1;
try {
int _feedCount = _currentPage * FeedCountPerPage;
if (_feedCount <= arrPhotoData.size()) {
tmpList = arrPhotoData.subList(_feedCount - FeedCountPerPage, _feedCount);
adderList.addAll(arrPhotoData.subList(0, FeedCountPerPage));
adderList.addAll(tmpList);
}
} catch (Exception e) {
e.printStackTrace();
}
if (adderList == null || adderList.size() == 0)
adapter = new InstagramListAdapter(_myActivity, arrPhotoData);
else
adapter = new InstagramListAdapter(_myActivity, adderList);
I have posted this answer as a context of my project. I hope you'll have some understanding from this.

Categories

Resources