I have this piece of code;
Scanner s = new Scanner(getResources().openRawResource(R.raw.game));
try {
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
} finally {
s.close();
}
How can I make to load a random line from this piece of code?
Thanks.
You could load the lines into another data structure such as an ArrayList and then use Random to generate a random index number.
Here's some code to put it into an ArrayList:
Scanner s = new Scanner(getResources().openRawResource(R.raw.game));
ArrayList<String> list = new ArrayList<String>();
try {
while (s.hasNextLine()) {
list.add(s.nextLine());
}
} finally {
s.close();
}
This code will return a random line:
public static String randomLine(ArrayList list) {
return list.get(new Random().nextInt(list.size()));
}
First load all of them from file into a String array then randomly pick one of them from that String array.
lets supose that you did the collecting to the String array lines:
int randomLine = (int)(Math.random()*lines.length);
there you got your random line.
Edit: oh well, you could use just String[]
Related
Trying to convert a Arraylist of strings into one big comma separated string.
However when I use the
String joined = TextUtils.join(", ", participants);
Debugger shows me size of 4 for participants however the joined value as "" therefore empty
private ArrayList<String> participants;
Not sure what is going wrong?
UPDATE:
List<String> list = new ArrayList<>();
list.add("Philip");
list.add("Paul Smith");
list.add("Raja");
list.add("Ez");
String s = TextUtils.join(", ", list);
This works when I have a list that I manually populate however below is how the code is working right now.
In the onCreate()
callApi(type);
String s = TextUtils.join(", ", participants);
getSupportActionBar().setTitle(s);
In callAPI():
JSONArray participantsR = sub.getJSONArray("referralParticipants");
Log.e("Participants length ", String.valueOf(participantsR.length()));
for (int i = 0; i < participantsR.length(); i++)
{
JSONObject object = participantsR.getJSONObject(i);
String firstname = (String) object.get("fullName");
participants.add(firstname);
Log.e("Times", String.valueOf(i));
}
I'm trying to reproduce your error and am unable to. Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp);
List<String> list = new ArrayList<>();
list.add("Philip Johnson");
list.add("Paul Smith");
list.add("Raja P");
list.add("Ezhu Malai");
String s = TextUtils.join(", ", list);
Log.d(LOGTAG, s);
}
My output is Philip Johnson, Paul Smith, Raja P, Ezhu Malai as expected.
Are you importing the correct TextUtils class?
android.text.TextUtils;
Given the new information, here is my approach:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp);
callApi(type, new OnResponseListener<List<String>>() {
#Override public void onResponse(List<String> list) {
getSupportActionBar().setTitle(TextUtils.join(", ", list));
}
});
}
I don't know what networking library you're using, but you may have to define OnResponseListener as an interface. It's very easy:
public interface OnResponseListener<T> {
public void onResponse(T response);
}
You will then need to modify your callApi function to take an instance of OnResponseListener> and call it's onResponse method after completing the call.
I would recommend looking into the Volley library, and reading the Android documentation about simple network calls.
I use StringUtils.join from Apache Common Utilities.
The code is super-simple just the way you wanted,
StringUtils.join(participants,", ");
Works flawlessly for me.
EDIT
As requested, here is the StringUtils.java file for those who just want to use this single utility class and not the entire library.
I don't know what TextUtils does. This will do it.
StringBuffer sb = new StringBuffer();
for (String x : participants) {
sb.append(x);
sb.append(", ");
}
return sb.toString();
Easy enough, just use that.
Try with kotlin
val commaSeperatedString = listOfStringColumn.joinToString { it ->
"\'${it.nameOfStringVariable}\'" }
// output: 'One', 'Two', 'Three', 'Four', 'Five'
I searched for related questions but didn´t find a solution (at least i don´t know if i named it correctly)
So, i have two ArrayLists and i would like to randomize all of them to get a value:
public class ListBox {
public static ArrayList listOne(){
ArrayList<Lists> listOne = new ArrayList<>();
listOne.add(new Item("Text One"));
listOne.add(new Item("Text Two"));
return listOne;
}
public static ArrayList listTwo(){
ArrayList<Lists> listTwo = new ArrayList<>();
listTwo.add(new Item("Text Three"));
listTwo.add(new Item("Text Four"));
return listTwo;
}
}
in other activity:
public void buttonClick(View view){
ArrayList<Lists> algumasListas = ListBox.listOne();
...
}
This is where i shuffle it
public class ListMixer extends ListBox{
public ArrayList<Lists> listas = null;
public ListMixer(ArrayList<Lists> listas ) {
this.listas = listas;
}
protected String mixList(){
Double randomNumber = new Double(Math.random() * listas.size());
int randomNum = randomNumber.intValue();
Lista lista= listas.get(randomNum);
String listaString2 = String.valueOf(lista);
String message = ("This is your list: " + listas);
return message;
}
}
my desired output would be one of the four listItems.
Appreciate the help!
Merge arrays into single one of size N.
Choose a random number in range 0..N-1.
Choose an element by index.
The first bug I'm seeing in your code is that listOne() returns object listTwo when called, which doesn't exist. It probably shouldn't even compile, unless something funky is going on with global scope variables.
The following code should do what you want by merging the two lists into one and then returning a random object from them.
public Object randomFromList(List<Object> listOne, List<Object> listTwo){
List<Object> bigList = new ArrayList<Object>(listOne.size() + listTwo.size());
bigList.addAll(listOne);
bigList.addAll(listTwo);
return bigList.get(new Random().nextInt(bigList.size()));
}
For optimization, if you call this a lot, I would save the Random() object outside of the method to avoid instantiating it every time you make the call.
i have a problem with format arrayList.I have one parameter it have value
Licence_car:[[คย1453 กรุงเทพมหานคร], [รง2344 กรุงเทพมหานคร], [รน4679 กรุงเทพมหานคร]] (Data is a ThaiLanguage)
I use this parameter to set entry of list preference but it will show like this
I want to delete character is "[" and "]" to make a variable like this Licence_car:[คย1453 กรุงเทพมหานคร, รง2344 กรุงเทพมหานคร, รน4679 กรุงเทพมหานคร] how can i do that?
This is my code set entry to list preference.
#SuppressWarnings("unchecked")
public void showCar(Context context,ArrayList<String> currentCars){
SharedPreferences MYprefs = context.getSharedPreferences(PREFERENCES, PREFERENCE_MODE);
if (null == currentCars) {
currentCars = new ArrayList<String>();
}
try {
currentCars = (ArrayList<String>) ObjectSerializer.deserialize(MYprefs.getString("car_licence_", ObjectSerializer.serialize(new ArrayList<String>())));
//String[] car_list = currentCars.toCharArray;
Log.d(TAG,"Licence_car:"+currentCars);
final CharSequence[] charSequenceCarEntry = currentCars.toArray(new CharSequence[currentCars.size()]);
mCarDefault.setEntries(charSequenceCarEntry);
mCarDefault.setEntryValues(charSequenceCarEntry);
mCarDelete.setEntries(charSequenceCarEntry);
mCarDelete.setEntryValues(charSequenceCarEntry);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I get a preference value in arrayList and format to CharSequence[] for set entry to list preference i think that i do format from this point but i don't know how can do it.
Thank for any answer and sorry for my English.
Hello Developer,
You can foramt your charsequence before storing into array list ,hete i am giving the sample code please use it so here it is-
CharSequence[] charSequenceCarEntry = new CharSequence[10];
int startindex=charSequenceCarEntry.toString().indexOf("[");
int endindex=charSequenceCarEntry.toString().indexOf("]");
CharSequence cs =charSequenceCarEntry.toString().substring(startindex, endindex);
so in your case use it like-
currentCars = (ArrayList<String>) ObjectSerializer.deserialize(MYprefs.getString("car_licence_", ObjectSerializer.serialize(new ArrayList<String>())));
final CharSequence[] charSequenceCarEntry = currentCars.toArray(new CharSequence[currentCars.size()]);
int startindex=charSequenceCarEntry.toString().indexOf("[");
int endindex=charSequenceCarEntry.toString().indexOf("]");
CharSequence cs =charSequenceCarEntry.toString().substring(startindex, endindex);
mCarDefault.setEntries(cs);
mCarDefault.setEntryValues(cs);
mCarDelete.setEntries(cs);
mCarDelete.setEntryValues(cs);
I have solve this problem. I create input variable is type list<string> car_entry; to input a car_licence and output result is [คย1453 กรุงเทพมหานคร] so i will try to change type variable to String and the output is คย1453 กรุงเทพมหานคร as a result of charSequenceCarEntry is Licence_car:[คย1453 กรุงเทพมหานคร, รง2344 กรุงเทพมหานคร, รน4679 กรุงเทพมหานคร].Ok now It is done thank for any answer again. :)
I am a new developer on android application. I would like to get the ISO Country code when I pass the mobile number with country code. If I pass the mobile number as 1-319-491-6338, can I get country ISO code as US / USA in android?
I have written the code as follows:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
String mobileno="1-319-491-6338";
Here, where can I pass the mobile number?
Can anybody please help me ?
Thanks in advance
You may not be able to query the country code programmatically via the standard API but you could include a table in your app. Such a table is easily found via Google (e.g. http://countrycode.org/).
Danger Will Robinson!: However, one should ask yourself what question you are trying to answer. Implicit in your question is that assumption that there is a one-to-one mapping between international dialling codes and ISO country codes. This is not true. For example, both the USA and Canada have the international dialling code '1'.
Perhaps think about re-structuring your app's interface. Allow the user to select a country to associate with the phone number but use the table from http://countrycode.org/ to order the most likely candidates at the top?
Had the same problem. Eventually I put all the data in excel and read the excel sheet.
Here is the implementation:
copy-past the country code table from http://countrycode.org/ to Microsoft Excel file.
Save the Excel file as 97-2003 compatible (.xls) in \res\raw\countrycode_org.xls
Download JExcelApi from here
Use the following class to read the file:
public class CountryCodes {
private HashMap mCountryByName = new HashMap();
private HashMap mCountryByCode = new HashMap();;
private ArrayList mCountries = new ArrayList();
public void addCountry(String countryName,String ISO_code,String countryCode){
countryCode = PhoneNumberUtil.normalizeDigitsOnly(countryCode);
Country country = new Country();
country.Name = countryName;
country.Code = countryCode;
country.ISO_code = ISO_code;
mCountryByName.put(countryName, country);
mCountryByCode.put(countryCode, country);
mCountries.add(country);
return;
}
public Country getCountryByCode(String countryCode){
countryCode = PhoneNumberUtil.normalizeDigitsOnly(countryCode);
return mCountryByCode.get(countryCode);
}
public Country getCountryByName(String countryName){
return mCountryByName.get(countryName);
}
public Country getCountryByIsoCode(String ISO_code){
ISO_code = ISO_code.toUpperCase();
for (Country country:mCountries){
String [] strArr = country.ISO_code.split("/| ");
for (String s:strArr){
if (ISO_code.equals(s))
return country;
}
}
return null;
}
public String[] getCountryNamesList(){
String[] res = new String [mCountries.size()];
int i=0;
for (Country c:mCountries){
res[i] = c.Name;
i++;
}
return res;
}
public void readCountryCodesFromExcelWorkbook()
{
Context context = GlobalData.getInstance().getApp();
Workbook mWorkbook;
InputStream myRawResource = context.getResources().openRawResource(R.raw.countrycode_org);
if (myRawResource == null)
Toast.makeText(context,"XML file not found",Toast.LENGTH_LONG).show();
else
try {
WorkbookSettings ws = new WorkbookSettings();
ws.setEncoding("Cp1252");
mWorkbook = Workbook.getWorkbook(myRawResource);
//ArrayList<String[]> currentSheet = new ArrayList<String[]>();
Sheet sheet = mWorkbook.getSheet(0);
int rowsNum = sheet.getRows();
for (int rowNum = 1; rowNum < rowsNum; rowNum++) {
//Log.d("RowNum", ""+rowNum);
int colsNum = sheet.getColumns();
String[] strArr = new String[colsNum];
boolean rowIsFull = true;
for (int colNum = 0; colNum < colsNum; colNum++) {
strArr[colNum] = sheet.getCell(colNum, rowNum).getContents();
if (strArr[colNum].length() == 0)
rowIsFull = false;
}
if (rowIsFull)
addCountry(strArr[0],strArr[1],strArr[2]);
}
} catch (BiffException e) {
Toast.makeText(context,"Error Reading xml file: BiffException",Toast.LENGTH_LONG).show();
e.printStackTrace();
return ;
} catch (IOException e) {
Toast.makeText(context,"Error Reading xml file: IOException",Toast.LENGTH_LONG).show();
e.printStackTrace();
return ;
}
}
public Country[] getCountries(){
return mCountries.toArray(new Country[0]);
}
public class Country {
public String Name;
public String Code;
public String ISO_code;
}
}
Step-1
You can get country calling code as well as its ISO name in the following URL
http://en.wikipedia.org/wiki/List_of_country_calling_codes
or
http://www.unc.edu/~rowlett/units/codes/country.htm
Step-2 You can get page source of that file using java program. You will get file in HTMl format
Step-3 you can convert those HTML files into XML format using any of available parsers. see Open Source HTML Parsers in Java
Step-4 Form the phone number you can get the calling code. Example if the number is "1-319-491-6338" then calling code is 1
Step-5 Match this calling code against the calling code and country name list that you have got from XML parser. In this way you can get iso country
I'm writing an app for android that needs to parse data from an XML file. I've never come across an error like this that is so impossibly hard to track down. Or maybe my brain just stopped working. That happens. XML file is of the form:
<?xml version="1.0" encoding="iso-8859-1"?>
<memberRoster>
<agent>
<agentInfo1>...</agentInfo1>
<agentInfo2>...</agentInfo2>
...
</agent>
<agent>
...
</agent>
...
</memberRoster>
So far it's working well, except for some random bits of fun!
Every now and then it will throw a NullPointerException. I did some more digging and found out that there are THREE "agents" (out of 800) with "supposedly" null data. I checked the XML file and the data is there, there are no illegal characters, etc. It is the same three "agents" every time. The program parses other entries before and after these "null" "agents". Also of note is that not all "agentInfo" fields in the ArrayList come up null; example, one of the entries has 7 of the 8 entries as null, with the 8th one non-null, another has only one null with the last 7 non-null.
I'm parsing the data in to an ArrayList from the XML file, and like I mentioned before, it works flawlessly until it comes to those three specific entries in the XML file.
I'm sorry I can't give much more info than that, the data is sensitive to our members.
EDIT:
Sorry! I knew I was forgetting something! :)
Some code from my XMLHandler.java class:
public void characters(char[] ch, int start, int length)
if(this.in_mr_agentNrdsId) {
agent[0] = ch.toString();
}
else if(this.in_mr_agentFirstName) {
agent[1] = ch.toString();
}
else if(this.in_mr_agentLastName) {
agent[2] = ch.toString();
}
else if(this.in_mr_agentPhone) {
agent[3] = ch.toString();
}
else if(this.in_mr_agentEmail) {
agent[4] = ch.toString();
}
else if(this.in_mr_agentOfficeName) {
agent[5] = ch.toString();
}
else if(this.in_mr_agentOfficePhone) {
agent[6] = ch.toString();
}
else if(this.in_mr_agentType) {
agent[7] = ch.toString();
pds.setMemberRoster(agent);
agent = new String[8];
}
PDS is an object of type ParsedDataSet, which is just a simple class containing the ArrayList objects and a few getter and setter methods:
public class ParsedDataSet {
private ArrayList agentOpenHouses = new ArrayList();
private ArrayList calendarOfEvents = new ArrayList();
private ArrayList latestStatistics = new ArrayList();
private ArrayList memberRoster = new ArrayList();
public ArrayList<String[]> getAgentOpenHouses() {
return agentOpenHouses;
}
public ArrayList<String[]> getCalendarOfEvents() {
return calendarOfEvents;
}
public ArrayList<String[]> getLatestStatistics() {
return latestStatistics;
}
public ArrayList<String[]> getMemberRoster() {
return memberRoster;
}
public void setAgentOpenHouses(String[] agentOpenHousesItem) {
this.agentOpenHouses.add(agentOpenHousesItem);
}
public void setCalendarOfEvents(String[] calendarOfEventsItem) {
this.calendarOfEvents.add(calendarOfEventsItem);
}
public void setLatestStatistics(String[] latestStatisticsItem) {
this.latestStatistics.add(latestStatisticsItem);
}
public void setMemberRoster(String[] memberRosterItem) {
this.memberRoster.add(memberRosterItem);
}
} // end class ParsedDataSet
You could throw an if statement into your assignements and reassign any caught 'NULL' or empty strings into a zero value or just reassign as variable = "" in your code.
For example:
if (agentInfo1 == NULL) {
agentInfo1 = "" || agentInfo1 = 0; //Depending on what your variables are
}
Try putting try catch loop in code to find where the error is happening, then, pinpoint the exact part of code that is giving this error, there do null checks before proceeding. This is based on best practices of software development, rather than a fix for you.
Alternatively, you can makes sure on server side that there are no "null" values, maybe by giving dummy value like "EMPTY_STRING". This is especially relevant if your app is already shipped and you cant make any client code changes.