how to read items from string-array on android - android

I got a problem with reading items from string-array one by one. For example, i got string-array with 10 items:
<string-array name="arr">
<item>First</item>
<item>Second</item>
<item>...</item>
<item>Tenth</item>
</string-array>
So i know how to display items randomly, im using this code
Resources res = getResources();
myString = res.getStringArray(R.array.arr);
int length=myString.length;
int index=rgenerator.nextInt(length);
String q = myString[index];
tv = (TextView) findViewById(R.id.text);
tv.setText(q);
And in TextView on every button click it displays random item from array.
Problem is, how to make display item from string-array not randomly. Like, it starts from displaying First, then on click it displays Second, and so on untill end of array.
Please help!

You can't initialize your testArray field this way, because the application resources still aren't ready.
Change the code to:
package com.xtensivearts.episode.seven;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class Episode7 extends ListActivity {
String[] mTestArray;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
mTestArray = = getResources().getStringArray(R.array.testArray);
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}

Declare a variable
int currentIndex=0;
outside this onClick method.
In the
onClick(View v)
{
//Verify if only that btn is clicked
{
tv.setText(myString[(currentIndex++)%(myString.length)]);
}
}
Hope it works.

try
int i=0;
String q = myString[i];
i++;

strings.xml
<string-array name="month">
<item>Jan</item>
<item>Feb</item>
<item>Mar</item>
<item>Apr</item>
<item>May</item>
<item>Jun</item>
<item>Jul</item>
<item>Aug</item>
<item>Sep</item>
<item>Oct</item>
<item>Nov</item>
<item>Dec</item>
</string-array>
java
for (int i = 0; i < getResources().getStringArray(R.array.month).length; i++) {
Log.e("Array",""+getResources().getStringArray(R.array.month)[i]);
}

Related

spinner key and value

I am creating a translater app in which user need to choose the target language if suppose he choose marathi from the spinner then value for the marathi should be 'mr' so i can pass that value in url.
I have created a spinner and assigned languages from strings.xml but I want to use it's short form like for hindi the value should be hi, how can I achieve that?
<string-array name="languages">
<item>Marathi</item>
<item>Hindi</item>
<item>Japanese</item>
<item>Russian</item>
<item>Bengali</item>
<item>Greek</item>
<item>Gujarati</item>
<item>Italian</item>
<item>Malayalam</item>
<item>German</item>
<item>Punjabi</item>
<item>Tamil</item>
<item>Telugu</item>
<item>French</item>
<item>Urdu</item>
</string-array>
I would go for map instead.
1-create the languages map
Map<String, String> languages = new HashMap<>();
languages.put("hindi", "hi");
languages.put("arabic", "ar");
languages.put("english", "en");
2-get the selected item
String selectedLanguage = mySpinner.getSelectedItem().toString();
String languageToSend=languages.get(selectedLanguage); //send it to url
You can create a Map object for your above functionality. You can create something like this.
Map<String, String> map = new HashMap<String, String>();
map.put("Hindi", "Hi");
map.put("Marathi", "Mi");
You can reverse the order of the key and value according to your need. For populating your spinner you can get all the keys and put in a list and then add it to your spinner. You can do it like this
List<String> l = new ArrayList<String>(map.keySet());
One way to achieve that is by using Map as suggested by #Vivek Mishra (in comments) where key will be your language name to be displayed in spinner and value will be the language code you want to pass in URL.
Map will look something like below
languageMap.put ("Marathi","mr");
languageMap.put ("Hindi","hi");
Now when you want to use, get the String from the spinner, selected by User and get language code value by
languageMap.get("Marathi")
Another option to integrate with your current implementation, is to add language code array in String.xml in same order as language name array and get the same index from language code array as per the selected index of spinner.
<string-array name="languages_code">
<item>mr</item>
<item>hi</item>
<!-- Add entries for other languages -->
</string-array>
you can create tow list like
List fullname= new ArrayList();
fullname.add("hindia");
fullname.add("persian");
fullname.add("english");
List urlName= new ArrayList();
urlName.add("hin");
urlName.add("per");
urlName.add("eng");
then add first one to spiner
ArrayAdapter dataAdapter = new ArrayAdapter(context, R.layout.spinner_dropdown, fullname);
// Drop down layout style - list view with radio button
// dataAdapter.setDropDownViewResource(R.layout.spinner_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
finally with implements AdapterView.OnItemSelectedListener and andspinner.setOnItemSelectedListener(this);
to get equivalent value use below code:
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i,
long l) {
String url=urlName.get(i);
}
You can add one string array with short names corresponding to languages array you already have, and fetched short language name by using position in "onItemSelected".
Following is a simplest way to achieve desired output:
Strings.xml
<string-array name="languages">
<item name="">Marathi</item>
<item>Hindi</item>
<item>Japanese</item>
<item>Russian</item>
<item>Bengali</item>
<item>Greek</item>
<item>Gujarati</item>
<item>Italian</item>
<item>Malayalam</item>
<item>German</item>
<item>Punjabi</item>
<item>Tamil</item>
<item>Telugu</item>
<item>French</item>
<item>Urdu</item>
</string-array>
<string-array name="sr_languages">
<item name="">Ma</item>
<item>Hi</item>
<item>Ja</item>
<item>Ru</item>
<item>Be</item>
<item>Gr</item>
<item>Gu</item>
<item>It</item>
<item>Ma</item>
<item>Ge</item>
<item>Pu</item>
<item>Ta</item>
<item>Te</item>
<item>Fr</item>
<item>Ur</item>
</string-array>
SpinnerActivity.java
package com.example.sonias.stackoverflowdemos;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
public class SpinnerActivity extends AppCompatActivity {
private Spinner spLanguage;
private ArrayAdapter<String> spAdapter;
private String mSelectedLanguage = "";
private ArrayList<String> LanguagesList;
private ArrayList<String> srLanguagesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
spLanguage = (Spinner) findViewById(R.id.spLanguage);
LanguagesList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.languages)));
srLanguagesList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sr_languages)));
spAdapter = new ArrayAdapter<>(SpinnerActivity.this, android.R.layout.simple_list_item_1, LanguagesList);
spLanguage.setAdapter(spAdapter);
spLanguage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String mSelectedTExt = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
mSelectedLanguage = srLanguagesList.get(position);
Toast.makeText(SpinnerActivity.this, "You have selected " + mSelectedTExt + " ( " + mSelectedLanguage + " )", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}

how to display a listview based on the text inside the edittext with a clickable image button to search the listviews data?

I have written a program to display a ListView. The Activity contains an EditText with a search button and ListView below. I have defined the items inside string.xml to be displayed inside the ListView:
<string-array name="Name2">
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
</string-array>
<string-array name="Name3">
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
</string-array>
I have put it 6 times because inside my ListView I want to display the same name 6 times.
What my program does is, when I write "ar" inside my EditText and when I write "ro" or any timmed letter inside my EditText and click on search button, the results are displayed for the item which I have passed inside my custom adapter means for any case Arjun Narahari is only displayed and if I pass the rohit array, then for any case rohit is only displayed inside my ListView.
What I want my program to do is, when I write A or Ar inside my EditText and click on search button I want the results inside my ListView to be only starting from A or Ar and when I write R or Ro only those results should be displayed inside my ListView.
Please, need some help.
Will post my code here:
Result_Name.java
public class Result_Name extends Activity {
ImageView iv;
EditText etSearch;
private TextView txtNoResult;
ImageView imgSearch;
ResultsNameAdapter adapter;
ListView lv;
String[] name1, name2; // name3, name4, name5, name6;
String[] mobile0, mobile1; // mobile2, mobile3, mobile4, mobile5;
String[] age1, age2; // age3, age4, age5, age6;
String[] gender;
String[] diagname;
String[] year;
String PassedData;
int[] images = {
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.date,
R.drawable.b_list,
R.drawable.v_list,
R.drawable.g_list
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_listr_name);
iv = (ImageView) findViewById(R.id.imgBackReuslt);
etSearch = (EditText) findViewById(R.id.edtSearchName);
imgSearch = (ImageView) findViewById(R.id.imgSearchlist);
Resources res = getResources();
name1 = res.getStringArray(R.array.Name1);
name2 = res.getStringArray(R.array.Name2);
mobile0 = res.getStringArray(R.array.Mobile0);
mobile1 = res.getStringArray(R.array.Mobile1);
age1 = res.getStringArray(R.array.Age1);
age2 = res.getStringArray(R.array.Age2);
diagname = res.getStringArray(R.array.DiagnosisName);
gender = res.getStringArray(R.array.Gender);
year = res.getStringArray(R.array.year_array);
etSearch = (EditText) findViewById(R.id.edtSearchName);
etSearch = (EditText) findViewById(R.id.edtSearchName);
imgSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (etSearch.getText().toString().trim().length() < 0) {
lv.setVisibility(View.GONE);
}
if (etSearch.getText().toString().trim().length() > 0) {
lv = (ListView) findViewById(R.id.lstResult);
adapter = new ResultsNameAdapter(getBaseContext(), name1,
name2, mobile0, mobile1, age1, age2, images, year,
diagname, gender);
lv.setAdapter(adapter);
}
}
});
The imgsearch is the image which I am using as a ClickListener and etsearch is my EditText. If my EditText is empty, my ListView is not visible and when my EditText has text with length > 0, my ListView is visible. This is where I want to change my things which I mentioned up.
I hope the requirements are clear.
Any suggestions are welcome.
What i want my program to do is , when i write A or Ar inside my edittext and click on search button i want the results inside my listview to be only starting from A or Ar and when i write R or Ro only those results should be displayed inside my listview
A good way for you to achieve this and make it efficient is to use a Trie data structure and you should look into that because explaining it is too broad for my SO answer.
Another way to reach to a simple solution would be to use the String.startsWith method:
String text = etSearch.getText().toString().trim();
// check for "Rohit Kumar" array
for(String name : name2) {
String nameWithoutLabel = name.substring(5); // skip the "Name:" part
if(nameWithoutLabel.startsWith(text)) {
// you will reach this point only if current nameWithoutLabel starts with the text from your EditText
// add nameWithoutLabel to your list view or where you need it
}
}
// same check for name3 which is the "Arjun Narahari" array
Another way you could check for Strings that start with a certain sequence is to use a regular expression:
// ...
if (nameWithoutLabel.matches("(" + text + ").*")) {
// ...
How you want to use the code above depends on how your ResultsNameAdapter is used and how you want to organize your data.
For example, what you can do is create a method out of the code above that finds Strings inside an array that starts with a certain text. Something like:
ArrayList<String> getMatches(String text, String[] names) {
ArrayList<String> list = new ArrayList<String>();
for(String name : names) {
String nameWithoutLabel = name.substring(5); // skip the "Name:" part
if(nameWithoutLabel.startsWith(text)) {
list.add(nameWithoutLabel);
}
}
return list;
}
Then you can call this method to find matches from whichever array you need to and store the matches in an ArrayList:
ArrayList<String> allMatches = new ArrayList<String>();
// ...
String text = etSearch.getText().toString().trim();
allMatches.addAll(getMatches(text, name2)); // add all matches from name2
allMatches.addAll(getMatches(text, name3)); // add all matches from name3
// now ArrayList allMatches contains all matches from arrays name2 and name3
Now you can use the ArrayList<String> allMatches to populate your ListView inside your ResultsNameAdapter...

Android - programatically adding text from strings.xml to TextView

OK, so I've been following a tutorial (http://javatechig.com/android/android-spinner-example) which is about creating Spinners and dynamically adding images (the locations of which are defined in the strings.xml file) to the view. Well that works fine but I'd like to extend the project so that I can include text arrays, again defined in the strings.xml file, to appear both before and after the image.
My code follows and, as you can see I'd like to substitute the 2 setText lines with references to the spinner item that I've already selected.
Any ideas? Thanks for your interest.
Thanks all for your input and I've now solved the problem and am showing some commented code below on how I resolved it...
public class MainActivity extends Activity {
private ImageView image;
private String[] states;
private Spinner spinner1;
private TypedArray imgs;
private String[] leaders;
private String[] descrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
states = getResources().getStringArray(R.array.countries);
imgs = getResources().obtainTypedArray(R.array.leader_photos);
// --- The following lines grab the problematic string arrays defined in
// strings.xml
leaders = getResources().getStringArray(R.array.leaders);
descrip = getResources().getStringArray(R.array.descrip);
image = (ImageView) findViewById(R.id.leaderPhoto);
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// The variable index identifies what position the selected
// spinner is. TextView text... locks to the TextView defined in
// the activity_main.xml layout file. text.setText... loads the
// appropriate value from the leaders string array
int index = parent.getSelectedItemPosition();
TextView text = (TextView) findViewById(R.id.tv1);
text.setText(leaders[index]);
image.setImageResource(imgs.getResourceId(
spinner1.getSelectedItemPosition(), -1));
// See earlier comments above TextView tv1 for how this works
TextView text2 = (TextView) findViewById(R.id.tv2);
text2.setText(descrip[index]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Android - programatically adding text from strings.xml to TextView -
If I understood you right?
Resources resources = context.getResources();
String[] textString = resources.getStringArray(R.array.mytext);
Then you have the text in a string-vector - easy to put in a textView
Then in the xml-file
<string-array name = "mytext">
<item> ... text </item>
<item> ... text</item>
<item> ... text</item>
</string-array>
And in the textView-object
text.setText(textString[i]); // at position i
You can use the position you get into the OnClickListener of Spinner to get the particular Leader and Description of the that states as follows.
text.setText(leader[position]);
text2.setText(descrip[position]);

Extracting values from strings.xml

I have a doubt.I have an activity which contains an autocompletetextview.The contents for autocompletetextview have been declared in strings.xml file as a string array.I hav one more string array in my strings.xml file.What i want is that when i select an item from autocompletetextview it should display a value from the second string array in the form of a toast.Is it possible.Plz help me
For Array::
String[] myarray =getResources().getStringArray(R.array.array);
For String::
String myString =getResources().getString(R.string.str);
Check with this,
package mytest.projects;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class example extends ListActivity {
String[] mTestArray;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
mTestArray = = getResources().getStringArray(R.array.testArray);
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}

Setting TextView with string from string array chosen in a ListView in Android

Alright, a quick summary. The app opens with a listView (populated by a string array), when you tap one of the items in the list it takes you to another listView (populated by a string array) with items associated with the first item you tapped. In the second listView, i'd like to tap on an item and have it display a textView with associated items from another string array. I have the first two listViews working so far, but can't get the textView to work. I've banged my head over this for two days now and am getting very frustrated. Could you please help?!
Here is my strings xml file:
<string-array name="topics">
<item>Idioms</item>
<item>Travel</item>
<item>Small Talk</item>
<item>Tips</item>
<item>App Data</item>
</string-array>
<string-array name="idioms">
<item>Cash Chow</item>
<item>No Spring chicken</item>
</string-array>
<string-array name="travel">
<item>Asking for Change</item>
<item>Bus and Train Schedule</item>
</string-array>
<string-array name="idioms_description">
<item>A cash cow is a blah blah blah</item>
<item>No spring chicken means blah blah blah</item>
</string-array>
<string-array name="travel_description">
<item>This is a test for Asking for change</item>
<item>This is a test for Bus and train schedules</item>
</string-array>
And here is my getIntent and place where I should setText. I left it blank because everything I have tried until now has failed miserably, I just don't know how to get the proper string from the array that was selected.
public class DetailLanguagePoints extends Activity{
private int position;
private TextView mLanguagePoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_view);
mLanguagePoint = (TextView) findViewById(R.detail.languagepoints);
Bundle extras = getIntent().getExtras();
//int[] arrayIds = new int[]{R.array.idioms, R.array.travel};
position = extras.getInt("listposition");
int[] stringarrayIds = new int[]{R.array.idioms_description, R.array.travel_description};
String[] subTopics = getResources().getStringArray(stringarrayIds[position]);
String description = subTopics[position];
final String TAG = "MyActivity";
Log.d(TAG,description);
mLanguagePoint.setText(description);
}
}
I found what the problem was with the null exception error, I didn't call findViewById() after setcontentView(). I did that and it solved the problem, it is now working!! Thank you to all those who provided suggestions!!
use this code mPosition = i.getIntExtra("listposition");
instead of this mPosition = i.getIntExtra("listposition", 0);
So you only want to set subTopics into a ListView?
ListView listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, subTopics);
listView.setAdapter(adapter);
Otherwise please post how you are failing with any logcat errors.
What do you want to display in the TextView? The two sub-items separated by a new line? If so then just change mLanguagePoint.setText() to mLanguagePoint.setText(subTopics[0] + "\n" + subTopics[1])
first initialize mLanguagePoint. try something like
then on second listview add onItemClickListener()
public void onItemClick(AdapterView<?> arg, View view, int position,long id) {
mLanguagePoint.setText(subTopics[position]);
}

Categories

Resources