How to sort numbers in TextViews and display them? - android

Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}

to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());

public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}

Related

Realm not update existing data in ONE-MANY Relationship Android

I have been using realm about more than a years, in many cases realm is good choice to construct Android database instead using SQLite. I have been using realm for one-one, one-many relationship and good for it. But, a moment a good. I discover realm NOT update my existing data in ONE-MANY relationship. This what i have done.
This code for populate skeleton data or a unit test
private void initData() {
List<PackModel> packs = new ArrayList<>();
for (int i = 0; i < 1; i++) {
PackModel packModel = new PackModel();
packModel.id = i;
packModel.name = "Pack " + new Random().nextInt(100);
List<FoodModel> foods = new ArrayList<>();
for (int j = 0; j < 3; j++) {
FoodModel foodModel = new FoodModel();
foodModel.id = 0; // i set primary key 0, so in list should be 3 but when insert should be JUST one
foodModel.packId = i;
foodModel.name = "Food " + new Random().nextInt(100);
foodModel.stock = new Random().nextInt(100);
foodModel.price = new Random().nextInt(100);
foodModel.image = "hrrp";
foodModel.calorie = new Random().nextInt(100);
foodModel.createTime = System.nanoTime();
foods.add(foodModel);
}
packModel.foods.addAll(foods);
packs.add(packModel);
}
insertdb(packs);
}
As you see a List of PackModel, and each PackModel have their food items.
So, i write in Realm like below code.
private void insertdb(final List<PackModel> items) {
new AsyncTask<Void, Void, List<PackObject>>() {
#Override
protected List<PackObject> doInBackground(Void... params) {
final List<PackObject> packsObject = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
PackObject packObject = new PackObject();
packObject.id = items.get(i).id;
packObject.name = items.get(i).name;
List<FoodObject> foodsObject = new ArrayList<>();
for (int j = 0; j < items.get(i).foods.size(); j++) {
FoodObject foodObject = new FoodObject();
foodObject.id = items.get(i).foods.get(j).id;
foodObject.name = items.get(i).foods.get(j).name;
foodObject.createdTime = items.get(i).foods.get(j).createTime;
foodsObject.add(foodObject);
}
packObject.foods.addAll(foodsObject);
packsObject.add(packObject);
}
Realm realm = Realm.getInstance(RealmApplication.getRealmConfiguration());
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(packsObject);
}
});
return realm.copyFromRealm(realm.where(PackObject.class).findAll());
}
#Override
protected void onPostExecute(List<PackObject> items) {
super.onPostExecute(items);
Log.d("Test", "");
}
}.execute();
}
I got multiple FoodObject in each PackObject, what i am wrong here? i also use realm.beginTransaction. realm.beginTransaction is just a same like execute*, the difference just execute* are thread safe.
i also use realm.insertOrUpdate(obj), but just have same result.
NOTE: I have read realm documentation about it. So dont judge me not read their documentation.
this my repot for the code https://github.com/radityagumay/realm-bug
Thanks

MPAndroidChart: getColors() is now deprecated for 'Legend'. What should I use instead?

I'm displaying a custom legend for a PieChart in MPAndroidChart however, .getColors() and .getLabels() are now deprecated.
I've been using them to get an int array and string array respectively but I can't seem to find a direct alternative. Am I missing something obvious? What should I now use instead? Thanks!
Legend legend = mChart.getLegend();
legend.setEnabled(false);
if (legend.getColors() != null) {
int colorCodes[] = legend.getColors();
String labels[] = legend.getLabels();
ArrayList<LegendItem> legendItems = new ArrayList<>();
for (int i = 0; i < legend.getColors().length-1; i++) {
legendItems.add(new LegendItem(colorCodes[i], labels[i]));
}
showLegend(legendItems);
// entry label styling
mChart.setDrawEntryLabels(false);
}
The Legend class now follows better OOP practices and is composed of an array of LegendEntry. You can iterate through each and extract the colors or the labels as you wish.
private int [] getColors(Legend legend) {
LegendEntry [] legendEntries = legend.getEntries();
int [] colors = new int[legendEntries.length];
for (int i = 0; i < legendEntries.length; i++) {
colors[i] = legendEntries[i].formColor;
}
return colors;
}
private String [] getLabels(Legend legend) {
LegendEntry [] legendEntries = legend.getEntries();
String [] labels = new String[legendEntries.length];
for (int i = 0; i < legendEntries.length; i++) {
labels[i] = legendEntries[i].label;
}
return labels;
}

How to add data in array on button click?

int size = mcq.size();
String arr[] = null;
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr[i] = tv1.getText().toString();
// Log.e("Array",arr[i]);
} else if (op2.isPressed()) {
arr[i] = tv2.getText().toString();
//Log.e("Array",arr[i]);
} else if (op3.isPressed()) {
arr[i] = tv3.getText().toString();
// Log.e("Array",arr[i]);
} else if (op4.isPressed()) {
arr[i] = tv4.getText().toString();
//Log.e("Array",arr[i]);
}
I am trying to store the data in an array when the button is pressed,but it always shows null.And when the for loop is over I want to display my array.
here , Arrays in Java have a size so u cannot do like this. Instead of this
use list,
ArrayList<String> arr = new ArrayList<String>();
Inorder to do using String array :
String[] arr = new String[SIZEDEFNE HERE];
For ur answer :
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr.add(tv1.getText().toString());
} else if (op2.isPressed()) {
arr.add(tv2.getText().toString());
} else if (op3.isPressed()) {
arr.add(tv3.getText().toString());
} else if (op4.isPressed()) {
arr.add(tv4.getText().toString());
}
Retrive value using
String s = arr.get(0);
This is because your string array is null. Declare it with the size as
String[] arr = new String[size];
Try Array List. use the following code in your main java
final ArrayList<String> list = new ArrayList<String>();
Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(editText.getText().toString());
}
});
To avoid duplication in arraylist .You can use arraylist for faster then String array
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);

use eratosthenes sieve to find prime

hello i want my app find prime between two number with sieve algorithm i am use this code but its not working well what can i do for improve this code to my goal please help me
public int[] GetPrimes() {
int[] primesData = new int[maxValue+1];
int[] results = new int[maxValue];
int i;
int result_count = 0;
for (i=MIN_VALUE; i<=maxValue; i++) {
primesData[i] = PRIME_UNKNOWN;
}
for (i=MIN_VALUE; i<=maxValue; i++) {
if (primesData[i] == PRIME_UNKNOWN) {
primesData[i] = PRIME_YES;
results[result_count++] = i;
int j;
for (j=i; j<=maxValue; j = j + i) {
primesData[j] = PRIME_NO;
}
}
}
int[] retval = new int[result_count];
for (i=0; i<result_count; i++) {
retval[i] = results[i];
}
tvresult.setText(retval.toString());
return retval;
}
}
The algorithm is correct. Likely you are launching it with wrong values as input.
Ensure to have MIN_VALUE set to value 2 and prepopulate retval with 1 i.e.:
int[] retval = new int[result_count+1];
retval[0] = 1;
for (i=0; i<result_count; i++) {
retval[i+1] = results[i];
For the printing issue:
tvresult.setText(Arrays.toString(retval));
Because retval.toString() just returns the object reference not the content. This is true for any Java array. Instead use Arrays.toString().

How to generate random number with out duplicates using JSON array in android

I am new to android. I am doing quize app.I have one JSON array text file.how to generate random number with out repetation using JSON array in android..please help me
Thank you adv..
this is my sample code
public static JSONArray getQuesList()throws JSONException{
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(i =size - 1; i >= 0; i--) {
//index = rnd.nextInt(list.size());
list.add(i);
}
Random rand = new Random();
while(list.size() > 0) {
index = rand.nextInt(list.size());
Object object = quesList.get(index);
quesList.put(index, quesList.get(i));
quesList.put(i, object);
Log.d("","Selected: "+list.remove(index));
}
return quesList;
Edited
QuestionActivity.java
Global variable
int[] quizarray = null;
Add two functions
private void createQuizIndex() {
int[] array = new int[QuizFunActivity.getQuesList().length()];
quizarray = new int[QuizFunActivity.getQuesList().length()];
for(int i = 0 ; i < QuizFunActivity.getQuesList().length() ; i++){
array[i] = i;
}
Random random = new Random();
int m = 0;
for (int n = array.length ; n > 0; n--){
int r = random.nextInt(n);
quizarray[m++] = array[r];
array[r] = array[n-1];
}
}
private int getIndexNum(int quesIndex2) {
return quizarray[quesIndex2];
}
Change every showQuestion
showQuestion(getIndexNum(quesIndex),review);
Call createQuizIndex() in line 80, and line 194 if "Retake" means another random quiz

Categories

Resources