which code set is easier to read/maintain? [closed] - android

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Both of the codes below give me the same exact answers. I was just wondering which would be better programming practice for readability and maintainability. Would less lines of code be best? Would one affect the functionality of the program more than the other? any suggestions would be very much appreciated as I just want to learn the best practices for programming.
Here are the codes:
for (int i = 0; i < db.getAllDecks().size(); i++)
{
String CardCount = String.format("(%s)",db.getCardsForDeck(i+1).size());
adapter2.add(db.getAllDecks().get(i).getDeck_name());
adapter3.add(CardCount);
}
or
for (Deck deck: deckList) {
String deckName = deck.getDeck_name();
adapter2.add(deckName);
int count = db.getCardIds(deck).length;
String strCount = Integer.toString(count);
adapter3.add(strCount);
}

Overall, I think the second code is clearer, and more readable.
It contains moe variable names that is able to tell what exactly it is used for, such as deckName, count and strCount. I can clearly see that you are getting every deck's name and card count and put them in different (list?) adapters.
For the first one, I apparently needed more time to comprehend what it is doing. So IMO, the second one!
Also if you could just rename getDeck_name to getDeckName that would be better for people to read. getDeckName follows the naming convention for naming Java methods i.e. camelCase.

if you want to get data from simple list thnn foreach loop is good to use but,,, if you want to data from exact position or to store from id than for-loop is better ..
and there is NO difference by performance wise both are same as well, as i know.
as my suggestion use for loop :)

As per this book Code Complete - Steve McConnell's
for loop is good choice when you need a loop that executes a specified number of times.
foreach loop is useful for performing an operation on each member of an array or the container.
for more visit : Google books - Code Complete

Related

How to insert multiple data in firebase using loop [closed]

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 4 years ago.
Improve this question
Is there any way to insert multiple data in firebase using loop in android studio.
As
for (DataSnapshot ds : dataSnapshot.getChildren())
{
String Name = ds.child("Name").getValue().toString();
list.add(Name);
}
DataSnapshot loop is used to get the multiple children. How can i insert multiple data using loop.
I am guessing you want to update various children of your database at once and for that you do not need to actually use a loop to insert multiple data at once in Firebase.
You may use maps for that, which can update multiple fields of your database in one go. The code for using maps, looks something like this:
Map<String,Object> taskMap = new HashMap<>();
taskMap.put("age", "12");
taskMap.put("gender", "male");
taskMap.put("name", "Someone");
taskMap.put("surname", "no-one");
reference.updateChildren(taskMap);
This depends a lot on your database structure, and you can edit it for your need, according to your database structure.
To know more about, how to update database using maps, go through the following links:
Link1
and
Link2.
Also, if you could make the question a bit more precise, you can get more help from here.

Sorting a ListView by date? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
As you can see down here I have a ListView populated by a JSON but I want to sort the list by date and to have the same items down the corresponding title.
In the image down the the row third and fourth have the same date but in different row.
I do not know what code should I show if the adapter or where I populate the list.
I think U need to sort the populated data date wise in hashmap
hashmap<date,list<other Object>>like this and then use expandable listview to show the populated data..
In the spirit of having less computation processes into the Android client, I suggest you create a new method called findServicesByDate from the server, which should give you the right order based on dates.
However, if this is not possible, the only thing you have to do is order the array based on date, you should check this answer.
Is a basic. Have you ever try to Google it ?
Use a comparator.
Collections.sort(yourList, new Comparator<YourObjectInYourList>() {
public int compare(YourObjectInYourList o1, YourObjectInYourList o2) {
if (o1.getDate() == null || o2.getDate() == null)
return 0;
return o1.getDate().compareTo(o2.getDate());
}
});

What is a concrete example of Android app functionality that uses HashMap? [closed]

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 8 years ago.
Improve this question
I am a beginner in Android, and understand only very basically that HashMap class enables key/value pairs. But how does this translate into actually using this in an Android app? Could someone provide a simple, plain English example of what case you might want to use HashMap in an app? I cannot imagine a case where I might need it. Make up an Android app idea, if needed. Thanks in advance.
I am looking for a "big picture" analysis that will give some examples where you might use HashMap with certain Android functionalities you are trying to implement.
HashMap or Map interface is not new on android, This is Java Collections framework.
Java collection are meant to be used in several cases to hold data and contain 3 interfaces:
List - Basically simple list,or linked list implementations
Set - The same as list but won't hold 2 equal obejcts(You need to implement you own equals and hashcode)
Map - as you said key value pair.
Uses:
List - For anything, just to hold data
Set - For list of data that we want that all of the items will be unique.
Map - Key value and the most common example is the use for DB items, or something with ids.. for example:
bookId, Book.. I that case you can take the object by id.. This is the most common
I attached link for Java collection tutorial.. It is very important framework that you have to know if you are going to develop java/android
http://tutorials.jenkov.com/java-collections/index.html
Hope that helps
We could use HashMap to keep a list of employess together with their respective salaries.
We can do:
HashMap<String, Float> emplMap = new HashMap<String, Float>();
emplMap.put("fred", 1.000);
for(String name : emplMap.keySet()) {
System.out.print(name + "'s salary is" + emplMap.get(name));
}
Should print
"fred's salary 1.000"

Searching a string from large text file of 10 Mb [closed]

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
I have a large file of about 10 MB, I want to search a specific string, and this specific string may be used a lot of times in 10 Mb text file. I need results where this specific string is used. I want to do search like Google. For example when i write a string then google comes with matching Patterns . Your suggestions will be appreciated.
file formate
he is going to school.
we should do best deeds.
we should work hard.
.
.
.
.
Always speak truth.
i have search edit field in my application.
user write "should" in search edit field.and press search button.
a list should be opened in which searched words come with it's complete line.
for example result should be
we should do best deeds.
we should work hard.
A simple way to search a file and get a match "with context" is to use grep. For example, to match every line with "hello", and print one line before and three lines after, you would do
grep -b1 -a3 'hello' myBigFile.txt
You can use grep -E to allow for a wide range of PCRE regex syntax.
Without more detail it would be hard to give you a better answer.
EDIT 2
Now that you have explained your problem more clearly, here is a possible approach:
InputStream fileIn;
BufferedReader bufRd;
String line, pattern;
pattern = "should"; // get the pattern from the user, do not hard code. Example only
fileIn = new FileInputStream("myBigTextfile.txt");
bufRd = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
while ((line = bufRd.readLine()) != null) {
if(line.contains(pattern)) {
System.out.println(line); // echo matching line to output
}
}
// Done with the file
br.close();
If you need to match with wildcards, then you might replace the line.contains with something that is a little more "hard core regex" - for example
matchPattern = Pattern.compile("/should.+not/");
(only need to do that once - after getting input, and before opening file) and change the condition to
if (matchPattern.matcher(line).find())
Note - code adapted from / inspired by https://stackoverflow.com/a/7413900/1967396 but not tested.
Note there are no for loops... maybe the boss will be happy now.
By the way - if you edit your original question with all the information you provided in the comments (both to this answer and to the original question) I think the question can be re-opened.
If you expect the user to do many searches it may be faster to read the entire file into memory once. But that's outside of the scope of your question, I think.

Questions of 'Designing for Performance' document at Android Developer site [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In the Avoid Creating Objects section of the page Designing for Performance in the Android Developer documentation I read some paragraphs for which I am not able to visualize a code representation:
An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive types.
How would these 'parallel arrays of ints' look like? Would it be something like instead of having a method with a signature such as getData():int[][] returning
[a][b]
[c][d]
[e][f]
... it would be better to have two methods, each returning one of the 'columns' of data? as in:
getFirstDimensionData():int[]
[a]
[c]
[e]
and a second one getSecondDimensionData():int[]
[b]
[d]
[f]
What is an 'array of (int,int) objects? ... something like an array of objects of a-type-not-yet-defined that has two int member instances defining its state?
The immediate next paragraph:
If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects.
... makes me think that the author is making up some sort of notation. I guess my key question is: is the author of the page using this (somethingX, somethingY) notation to refer to an arbitrary class that 'wraps' the elements inside the parentheses?
Finally, is this a standard notation or just something the author of the page created by himself and omitted to explain?
Can anyone, please, shed some light? :)
Thanks in advance,
Y
What they're saying is that
class foo {
int a;
int b;
}
foo[] bar;
Is slower than
int[] foo;
With foo[row*2] being a and foo[row*2+1] being b.
The notation (foo, bar) is trying to symbolize a class that contains foo and bar (like (a,b) in my above example).
I don't believe it's a standard notation, but it wouldn't be the first time I've been proven wrong.
The author of that document is using a sort of loose mathematical notation. (x, y, z) is the way tuples are represented in mathematics. (It also happens to be the case that Python uses this notation, and given that this document came out of Google there is a reasonably high chance that the authors are fluent in Python. Python didn't invent the notation, however.)
The approach EboMike mentions is probably equally efficient, but it's not exactly what that doc is talking about. The doc is talking about parallel arrays, which is an approach where you use n arrays in place of a single array of records/structs/tuples/objects that have n fields.
More concretely, it's saying that if you want "a container that stores tuples of (Foo,Bar) objects", like this:
class FooBar {
Foo foo;
Bar bar;
}
...
FooBar[] array = new FooBar[n];
you could instead use "two parallel Foo[] and Bar[] arrays", like this:
Foo[] foos = new Foo[n];
Bar[] bars = new Foo[n];
This means that wherever you would have said array[x].foo you'd now say foos[x].
With parallel arrays the garbage collector only has to deal with 2 + 2 * n objects (2 arrays, n Foos and n Bars) rather than 1 + 3 * n objects (1 array, n FooBars, n Foos and n Bars). So the bigger n is, the more significant the difference.
The downside is that you can't easily pass around the Foo and Bar together and it potentially makes the intent of your code less clear.

Categories

Resources