Working with multiple ID's - java

I am creating a project in which I prompt the user with a table. And he has to fill in the values. And when he clicks on submit, at the back end I have to check all those values are correct or not.
Here is a sample pick of the table and code
As you can see i have given the id's as "fcfs_p1_ct" for p1 and "fcfs_p2_ct" for p2. Now at the back end when I have to check the values entered by the user. I have to create objects of the respective Edit Texts.
Now one way is to create n number of if else conditions and create the objects for each edited text manually. Can this process be done through loops?
For example for p1
String str = findViewById(R.id.fcfs_p1_ct).getText().toString;
similarly for p2
String str = findViewById(R.id.fcfs_p2_ct).getText().toString;
and so on for n number of processes.
As the only changing variable in the statements is the process number. Please suggest me a way to do the same for a loop

This kind of situations in android are not handled by loops, once you realize that your layout (XML) requires lots of View id assignments, it's recommended to use an Adapter. There are many ready-to-go Adapters available in android SDK, such as ArrayAdapter, BaseAdapter, CursorAdapter etc.
Which Adapter to choose depends entirely on your choice of View/layout you wish to inflate and the data type and source you're willing to use.
In your situation, I'd recommend starting with a simple ListView, and using a custom Adapter (class that extends BaseAdapter). There are many tutorials out there on how to implement this, which are by the way quite easy to follow.

You can simply keep these ids in an ArrayList of Integer like;
ArrayList<Integer> ids = new ArrayList<>();
ids.add(R.id.editText1);
ids.add(R.id.editText2);
When the user presses submit, you can go through that array and do what you want. If you would like to change the corresponding value at the end, you can keep a Map instead of ArrayList.
But my personal suggestion is that using a ListView or RecyclerView. You can repeat views with an Adapter and keep your data as instances of a class so that you can avoid these kind of codes.

Related

Is there a way to create an ArrayList under certain circumstances?

I'm sorry if the question is phrased weirdly, but I wasn't quite sure how to fit it into the title space. I'm making a mini messaging program in which users create and log into accounts and send and receive messages. Is there a way to create an ArrayList of the user's messages when they create an account? All of the usernames are in another ArrayList, so maybe it can create one for every addition? I have the passwords and usernames in two different lists linked by position, so that could work too if it's even possible.
PS - I also need to be able to pull out and match the ArrayList to usernames, but that will come later.
I can clarify in the comments and show my code if you need it.
Thanks!
It sounds like you are looking for a data structure to store a list of messages per user. You can use a Map<User, List<Message> for this. When loading/adding a User, you can create an empty ArrayList<Message> and put it into the map for later use.
// Create map.
Map<User, List<Message>> userMessageMap = new HashMap<>();
// Insert new list for new user.
userMessageMap.put(user, new ArrayList<>());
// Insert message for existing user.
userMessageMap.get(user).add(message);
// Get all messages for an existing user.
List<Message> messages = userMessageMap.get(user);
The Answer by Pieter12345 is correct and smart.
Here is a table graphic I made to assist you in choosing an implementation of Map from among those bundled with Java. All of these support the operations seen in that other Answer.
Third-parties produce may produce Map implementations as well, such as Eclipse Collections or Google Guava.

What is the best way to store data in an app, that will not be updated by the user?

I am making an activity where the user inputs their weight into an EditText field. Based on the value they write, a GridView with around 20 numeric values will be updated.
I already have all the numbers I need in an Excel file. The weight could be used as a key and the values can be Array of doubles that are returned for each key.
Can you give me an advice what's the best way to store this information for the app and to fetch it to the screen?
So far the options I have looked at are sqlite database and SharedPreferences, but maybe there's a better way? I don't want the user to be able delete these values by clearing data / cache, yet it doesn't seem like a good idea to hard-code them into the source code.
If they don't change, then hardcoding is exactly what you want. Even if you did put them in SharedPreferences or a DB, they need to come from somewhere.
To be neater, you could make your arrays as XML resources. Each item in a resource array can also reference a resource value. It'll be easier to change in updates if needed, but in the end, there won't be any functional difference from just making arrays in code.

Extracting keywords from text in Android

Let us say, a user is typing text in an EditText. Now, as the user is typing, I want to extract the keywords from those texts.
For example, if user types- "I am having headache". It should extract "headache" as a keyword.
Please let me know how I can do this efficiently in Android.
Update: I do not know what the keywords are. They have to be extracted from the text which user enters.
First of all you should define what you will consider as keywords.
a. A limited list of words which are the keywords.
Or b. A limited list of words which are not the keywords.
That list can be in an ArrayList<String> in your code.
When the user changes the text in the EditText (see EditText.addTextChangedListener(new TextWatcher(){...}), you get the text and split() it into a String [] using space character as a delimiter. Next search each word in the array in your list (a or b options on top) either to check if they are or not there. When you get a hit you have found a keyword entered by the user.
The resulting keywords can be kept temporarily in another ArrayList<String> for you to use them after finishing the scanning of the input.
Note: I have proposed an ArrayList, to keep the list, considering that it won't be a long list. Fo more complex scenarios the list can be kept in HashMap or a TreeMap in the lines of what #Deepakkaku commented for the search to be quicker.
There can be two approaches to this problem:
Hardcoding the keywords or non-keywords you are interested in. #Juan's answer is the way to go here.
Second option is using some machine learnt model, which is what you are looking at, I guess given your machine-learning tag.
Option 1 requires a set of keywords defined ahead of time, which you say you don't have in your question. So this won't work in such a case. So here's a solution for Option 2.
Create a model.
You have to create a dataset of labeled examples.
You have to define a vocabulary for your entire dataset.
You have to define and train a model. If you have enough data, you can start from scratch. Otherwise, it is recommended to use transfer learning. For example, you can look up NLP models such as word2vec or sentiment analysis online and look up transfer learning. TF Hub makes it easy to do transfer learning.
Once you have trained the model, you have to workout how to convert that model so as to run efficiently on Android for inference. You have choices in Tensorflow-lite, Caffe2, etc. If you use Tensorflow, it is recommended that you convert to Tensorflow Lite for inference for efficiency.
You have to build your Android app with the appropriate runtime (TFLite, Caffe2, etc.) and bundle the model in. You can use ML Kit to take care of the download for you if you don't want to bundle.
Add the hooks to model in your activity by listening to changes in your EditText and calling the model inference. You likely want the model interpreter to be loaded ahead of time before the first inference call for efficiency.

ANDROID: Saving User Data For Itemized ListView in Another Activity

I'm working on an app that allows you to rate Pro Golfers and type what you think the pros and cons of this particular Golfer is. There is an EditText which saves the String data to an Arraylist, and a Ratingbar which saves int values to it's own Arraylist.
I would like to allow the user to input their data, and then on another activity, have buttons or a view of some kind that allows the user to tap and open one of their finalized sessions for viewing. How can this be done?
There are several ways, depending on how long you need to keep information, and how complicated you want to get with it. If you just want to pass this one ArrayList this one time, then add it to the intent when you start the new activity:
Intent myIntent = new Intent(this, someOtherActivity.class);
intent.putStringArrayListExtra("values",myList);
and then in onCreate of the new activity, retrieve the data:
myList = getIntent().getStringArrayListExtra("values");
// Do stuff
If you have one set of data that you want to keep even when the user restarts their phone, then you could use SharedPreferences, which is pretty easy. You can read more on that here.
If you have multiple sets of data, and those data are guaranteed to remain small, performance is not an issue, and you are willing to load the whole data set into memory every time you interact with it, then you could save it to a flat file either internally or on the SD card. More on that here.
If you have multiple sets of data, and the above criteria are not true, then you'll probably want to store it in a database. There are two basic approaches to this: Directly interfacing with a SQLite database, or building a content provider. The former is easier to get set up, but difficult to maintain. The latter is significantly more annoying to get working right, but it is easier to maintain, and comes with significant advantages like easy integration with listviews and the ability to share that data with other apps. Either way these are not trivial problems and I advise you look at the developer guides for databases and content providers and looking up tutorials on both. Implementing them is much more suitable to blog posts or chapters in a textbook than a Stack Overflow answer.

Methods of Data Storage - Opinion

I have been working on an app and have encountered some limitations relating to my lack of experience in Java IO and data persistence. Basically I need to store information on a few Spinner objects. So far I have saved information on each Spinner into a text file using the format of:
//Blank Line
Name //the first drop-down entry of the spinner
Type //an enum value
Entries //a semicolon-separated list of the drop-down entry String values
//Blank line
And then, assuming this rigid syntax is followed always, I've extracted this information from the saved .txt whenever the app is started. But things such as editing these entries and working with certain aspects of the Scanner have been an absolute nightmare. If anything is off by even one line or space of blankness BAM! everything is ruined. There must be a better way to store information for easy access, something with some search-eability, something that won't be erased the moment the app closes and that isn't completely laxed in its layout to the extent that the most minor of changes destroys everything.
Any recommendations for how to save a simple String, a simple int, and an array of String outside the app? I am looking for a recommendation from an experienced developer here. I have seen the storage options, but am unsure which would be best for just a few simple things. Everything I need could be represented in a 3 X n table wherein n is the number of spinners.
Since your requirements are so minimal, I think the shared preferences approach is probably the best option. If your requirements were more complicated, then a using a database would start to make more sense.
Using shared preferences for simple data like yours really is as simple as the example shown on the storage options page.

Categories