I was thinking that I could take in the user inputs which I get from the two AutoCompleteTextView and show it in as a result for which there is a TableLayout.
The two inputs that the AutoCompleteTextView takes is My Location and Destination from the users. The complexity comes from the type of input that the AutoCompleteTextView generates. The AutoCompleteTextView uses the PlacesAutoComplete from Google, therefore I am working with an inputs like Jamal, Kathmandu, Central Region, Nepal and maybe Kalanki, Kathmandu, Central Region, Nepal. What I would want the TableLayout to reflect is Results: From ... To ...
My question is how can I just take in the first part of the string in Jamal, Kathmandu, Central Region, Nepal which is just Jamal for the TableLayout to display a the results like Results: From Jamal to Kalanki. Being very new to android I sort of have a vague idea, the code that I tried looks like this.
String[] from;
String[] to;
//pulling the auto complete text view
from = location.getString().toText();
to = destination.getString().toText();
//referencing the text view inside the table layout
results.setText(new StringBuilder().append("Results from"+from[0]).append(" to"+to[0]));
This code obviously does not work as it prompts me to change from to a String. I really do not know what is going on. Please help ?
Do this:
String[] from = new String[]{location.getString().toText()};
String[] to = new String[]{destination.getString().toText()};
results.setText(new StringBuilder().append("Results from"+from[0]).append(" to"+to[0]));
Or
String from;
String to;
from = location.getString().toText();
to = destination.getString().toText();
results.setText(new StringBuilder().append("Results from"+from).append(" to"+to));
Hope its help.
You're assigning a String to a String[]. That will not work.
from = location.getString().toText();
Assign them to a String and execute this.
results.setText(new StringBuilder().append("Results from"+from).append(" to"+to));
You cannot assign String to String[] (String and String array are not the same!)
Use them as a String:
String from = location.getString().toText();
results.setText(new StringBuilder().append("Results from"+from).append(" to"+to));
String from_split = location.getText().toString();
String to_split = destination.getText().toString();
if(from_split.contains(","))
{
from = from_split.split(",");
}
else
{
from = from_split.split(" ");
}
if(to_split.contains(","))
{
to = to_split.split(",");
}
else
{
to = to_split.split(" ");
}
results.setText(new StringBuffer().append(from[0]).append(" to "+to[0]));
I guess I found the answer to displaying the result the way I wanted to.
Related
I’m developing an android app that gets objects from a server and shows them in a simple list.
I’m trying to figure out how to deal with long object’s titles :
Every title populates a designated multi-line TextView.
If a title is longer than 16 characters, it messes with my desired UI.
There are two scenarios I need to solve -
1). If the title is longer than 16 characters & contains more than one word, I need to split the words into different lines (I tried to .split("") and .trim(), but I don’t want to use another view, just break a line in the same one, and the use in ("") seems unreliable to me).
2). If the title is longer than 16 characters and contains only one long word, I only need to change font size specifically.
Any ideas for a good and reliable solution?
Thanks a lot in advance.
use SpannableString for a single view
For title:
SpannableString titleSpan = new SpannableString("title String");
titleSpan.setSpan(new RelativeSizeSpan(1.3f), 0, titleSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
for Message
SpannableString messageSpan = new SpannableString("Message String");
messageSpan.setSpan(new RelativeSizeSpan(1.0f), 0, messageSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
set in TextView
tvTermsPolicyHeading.setText(TextUtils.concat(titleSpan, messageSpan));
Code like below it will work as you need
String title; //your title
//find length of your title
int length = title.length();
if (length>16){
string[] titles = myString.split("\\s+");
int size = titles.length;
if (size < 2){
yourTextview.setText(title);
// reduce the text size of your textview
}else {
String newTitle= "";
for (int i=0;i<titles.length;i++){
newTitle = titles[i]+"\n"
}
yourTextview.setText(newTitle);
}
}
You can split and then concatenate the words using "\n" if there are more than one words.
In case of long word
You can see this question here
Auto-fit TextView for Android
try this:
if(title.split(" ").size > 1){
String line1 = title.substring(0, 16);
int end = line1.lastIndexOf(" ");
titleTextView.setText(title.substring(0,end) + "\n" +
title.substring(end+1,title.size-1);
}else{
titleTextView.setText(title);
titleTextView.setTextSize(yourTextSize);
}
this code should work perfectly for your case.
i am getting error while using the values in my code.It says can not resolve the symbol setText.
protected void showRecords() {
if(c!=null && c.moveToFirst()){
do{
String Starter = c.getString(1);
Starter.setText=c.getString(1);
String MainCourse = c.getString(1);
MainCource.setText(MainCourse);
String Dessert = c.getString(1);
Dessert.setText=c.getString(1);
}while(c.moveToNext());
}
if Starter is a string then you would assign to it directly:
Starter = c.getString(1);
Also, you should follow Java naming conventions. Variables should not start with an Uppercase in order to distinguish them easily from a Type. So you should declare it like this:
String starter = c.getString(1);
Once you do that. There's not reason to call setText() on it. Unless you have some component (that is not a string) where you want to set the value on.
Well, I see you don´t get what we suggest you. So let me explain it step by step. This is your code:
String Starter = c.getString(1);
Starter.setText=c.getString(1);
String MainCourse = c.getString(1);
MainCource.setText(MainCourse);
String Dessert = c.getString(1);
Dessert.setText=c.getString(1);
These lines are wrong:
Starter.setText=c.getString(1);
MainCource.setText(MainCourse);
Dessert.setText=c.getString(1);
Starter, MainCourse and Dessert are objects of type String. Strings are texts and you can´t set text on a text. I guess, what you want to do is to set a text on a TextView.
So what you need is a TextView. This must be in your layout xml file. For example, it can look like this:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/dessertView"/>
Then, in your activity, you have to make a global object:
private TextView mDessertTextView;
initialize it in onCreate():
mDessertTextView = (TextView)findViewById(R.id.dessertView);
Then you retrieve the text like you did here:
String Dessert = c.getString(1);
and this String called Dessert, you have to set to that TextView:
mDessertView.setText(Dessert);
That´s the way it works. You really need some basics on programming, you should start by zero:
Basic Example
I have items in a JList that I can't get to format correctly.
I've created this method in order to do so:
private String formatString(String string){
string = string.trim();
int SEPERATOR = 20 - string.length();
for(int i = 0; i<SEPERATOR; i++){
string = string + " ";
}
return string;
}
When I output the items in my JList into the output window using a system out print it formats fine, but in my GUI it does not:
I'm not sure if this will help you help me better but here is how I am loading my data into the list:
DefaultListModel m = new DefaultListModel();
while (rs.next()){
String Expense = rs.getString("Expense");
String Cost = "£"+rs.getString("Cost");
String PurchaseDate = rs.getString("Purchase_Date");
String Description = rs.getString("Description");
Expense = formatString(Expense);
Cost = formatString(Cost);
PurchaseDate = formatString(PurchaseDate);
Description = formatString(Description);
String Row = Expense+Cost+PurchaseDate+Description;
m.addElement(Row);
System.out.println(Row);
}
The best solution, as has already been suggested, is to use a JTable. Read the section from the Swing tutorial on How to Use Tables for more information and working examples.
When i output the items in my jlist into the output window using a system out print it formats fine, but in my GUI it does not:
To answer your question you need to use a monospaced font.
list.setFont( new Font("monospaced", Font.PLAIN, 10) );
Also, use standard Java variable names. Variable name (Expense, Cost...) should NOT start with an upper case character.
You can use \t (you might have to use /t/t if the the text of a field is too long) instead of using spaces OR use a JTable
I need pass a string parameter that contains many params. When receive the parameter, I use String.split() to split it to get all the params.
But one promblem accured. How to design my string decollator so that any ASCII CODE on keyboard can be passed correctly.
Hope for any advice.
Maybe you could have a look at variadic arguments instead of splitting a string. For example:
public void method(String... strings) {
// strings is actually an array
String firstParam = strings[0];
String secondParam = strings[1];
// ...
}
Calling:
method("string1");
method("string1", "string2", "string3");
// as many string args as you want
If I understood correctly - you need to encode set of parameters to one string. You can use some sequence of characters for this purpose, E.g.
final String delimiter = "###"
String value = "param1###param2###param3";
String[] parameters = value.split(delimiter);
Choose a character which is easy to enter and unlikely to appear in the input. Let's assume that character is #.
Normal input would like like Item 1#Item 2#Item 3. Actually, you can .trim() every item and let the user enter Item 1 # Item 2 # Item 3 if s/he prefers.
However, like you describe, say the user would like to enter Item #1, Item #2, etc.. There are a few ways to let him/her do this, but the easier is to let them escape the delimiter. For example, instead of Item #1 # Item #2 # Item #3, which would result in 6 different items being found normally, let the user enter, for example Item ##1 # Item ##2 # Item ##3. Then in your parsing, make sure to handle the case when two or more #'s have been entered in a row. split likely won't be good enough, you'll have to go through the string yourself.
Here's a sketch of a method which would split the input string for you:
private static List<String> parseArguments(String input) {
ArrayList<String> arguments = new ArrayList<String>();
String[] prelArguments = input.split("#");
for (int i = 0; i < prelArguments.length; i++) {
String argument = prelArguments[i];
if (argument.equals("")) {
// We will enter here if there were two or more #'s in a row
StringBuilder combinedArgument = new StringBuilder(arguments.remove(arguments.size() - 1));
int inARow = 0;
while (prelArguments[i+inARow].equals("")) {
inARow++;
combinedArgument.append('#');
}
i += inARow;
combinedArgument.append(prelArguments[i]);
arguments.add(combinedArgument.toString());
} else {
arguments.add(argument);
}
}
return arguments;
}
Error handling, edge-case handling and some performance improvement is missing from the above, but I think the idea comes through.
I would eliminate the problem, which is the misuse of String as an argument container. If you need to pass more parameters, pass more parameters. If this gets out of hand, consider passing a map, or a custom object that can contain all the parameters.
i am facing a problem which is:
I have map containing string and string. When i print that map i can see that there is a key
"0-8166-3835-7". But when i am trying to get it, there is nothing to get returned, like no matching found...
My code:
//Open a stream to read from file with isbn's AND titles
Scanner IsbnTitle = new Scanner(new FileReader("C:/Users/Proskopos/Documents/NetBeansProjects/ReadUrl/IsbnTitle.txt"));
//Create a Map to save both ISBN's and Titles
Map <String,String> IsbnTitleMap = new HashMap();
while(IsbnTitle.hasNext()){
String recordIsbnTitle = IsbnTitle.nextLine();
UrlFunctions.AddToMap(Recognised , recordIsbnTitle, IsbnTitleMap);
}
.....
.....
Set IsbnSet = new HashSet();
while (IsbnFile.hasNextLine()) {
String isbn = IsbnFile.nextLine();
IsbnSet.add(isbn);
}
//Create an Iterator for IsbnSet
Iterator IsbnIt =IsbnSet.iterator();
String suffix = IsbnIt.next().toString();
String OPACIALtitle = UrlFunctions.GetOpacTitle(suffix, IsbnTitleMap);
The code above is the only part in main about MAP and below are the functions i call:
static String GetOpacTitle(String opIsbn, Map IsbnTitle) {
String OpacTitle = null;
String isbn = opIsbn;
Map isbnMap = IsbnTitle;
System.out.println(isbn);
if ( isbnMap.containsKey(isbn)){
System.out.println("AAAAAAAAAAAAAAAA");
}
//String tade = isbnMap.get(isbn).toString();
//System.out.println("*************" + tade);
return OpacTitle;
}
static void AddToMap(int Recognise, String recordIsbnfollowed, Map IsbnfollowedMap) {
Map isbnsth = IsbnfollowedMap;
String records = recordIsbnfollowed;
int recs= Recognise;
if (recs == 0 || recs == 3) {
String isbn = records.substring(0, 10);
String title = records.substring(10);
isbnsth.put(isbn, title);
// System.out.println(isbn);
}else if (recs == 1) {
String isbn = records.substring(0, 14);
String title = records.substring(14);
isbnsth.put(isbn, title);
// System.out.println(isbn);
}
}
I cant understand where the problem is.. Maybe it is something like encoding of the suffix cames from a set, and the key from a map? they are both string.. dont think so..!!!
So? Can you help?
EDIT: I am trully sorry if you find the code difficult to read :\ I will follow your advices!!
BUT in case that anyone else has the same problem the solution was what Brand said below.. (I re-post it)
You probably have some whitespace in the Strings that you are reading form the file and storing in the Map. If this is the case use String.trim() before storing the value in the Map, and also before querying for the same string. – Brad 3 hours ago
Thank you all
Just to add to my comment that identified the problem. When comparing Keys in a Map you must be very careful about white space and case sensitivity. These types of issues commonly occure when reading data from Files because it's not always obvious what characters are being read. Even looking in your debugger whitepsace cna be an issue.
Always try to "normalize" your data by trimming leading and trailing whitespace before storing it in a Map.