How to get string from resources strings into a fragment - android

I tried reading a number of solutions on Stack Overflow and have found they either don't work for my scenario or I simply don't understand their explanation (I am very new to Java and Android.
I have strings set up under res/values/strings.xml that I wish to use in the class:-
public class AttractionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.word_list, container, false);
// create an array list of details
final ArrayList<Details> details = new ArrayList<>();
// Details details
details.add(new Details(getActivity().getString(R.string.fun_bigsplash_name), getString(R.string.fun_bigsplash_addr), R.string.fun_bigsplash_num, R.drawable.bigsplash));
I've tried a number of variants (the reason they are different is just to show what I tried) but can't work it out. The R.drawable.bigsplash works fine (when I'm using literal strings for the others).
The error message states an int, which I assume means it's getting the reference and not the actual string.
How do I get the string from within the fragment?
Thanks.

You can use:
getResources().getString(R.string.my_string);
or just:
getString(R.string.my_string);

Read String value or String Array In Java Code.
Define a string array in strings.xml use string-array xml element.
Show Selection
<string name="auto_complete_text_view_car">Input Favorite Car Name</string>
<string-array name="car_array">
<item>Audi</item>
<item>BMW</item>
<item>Benz</item>
<item>Ford</item>
<item>Toyota</item>
<item>Tesla</item>
<item>Honda</item>
<item>Hyundai</item>
</string-array>
Read String Value In Java Code. Only string name
Inside Activity::
String defaultInputText = getResources().getString(R.string.auto_complete_text_view_car);
Inside Fragment::
String defaultInputText = getActivity().getResources().getString(R.string.auto_complete_text_view_car);
Read the string array in java source code. Please note car_array is just the string array name defined in strings.xml.
Inside Activity::
String carArr[] = getResources().getStringArray(R.array.car_array);
Inside Fragment::
String carArr[] = getActivity().getResources().getStringArray(R.array.car_array);

Simplest way to get string from resource in any part of your code is to override Application class and create static method to obtain "Application context".
For example, check out the application class for my app AB Music.
https://github.com/amit-bhandari/AB-Music-Player/blob/master/app/src/main/java/com/music/player/bhandari/m/MyApp.java
Refer method
public static Context getContext(){
return instance;
}
Now you can get string from resource anywhere in your code by simply calling.
MyApp.getContext().getString(R.string.mystring)
Hope it helps!

try this one
getActivity().getResources().getString(R.string.app_name)

Related

How can I get String in String[]?

String[] string = {getResourse().getString(R.string.girl), getResourse().getString(R.string.boy), getResourse().getString(R.string.child)};// Why is this code not working
And I tried do like this
String[] string = {getString(R.string.girk)....};
And also I tried do like
String[] string = {R.string.girl...};
Everything is not working, or it is impossible?
First of all, R.string.girl is int type.
If you really want to define it programatically like below,
String[] string2 = {getString(R.string.app_name)};
You should define it when your Activity/fragment's context is avaliable. For example, you can define it inside onCreate method but it is impossible to define it as a global variable (Because getString is the method of Context class).
You can do like in this example.
For more info https://developer.android.com/guide/topics/resources/string-resource.html#StringArray

SharedPreferences - Android (different data types)

I have a problem with with sharing data between two different activities. I have data like :
int number
String name
int number_2
int time
int total
I'm trying to make something like order list with this set of data . So it will take one set of data , then back to previous activity , move forward and again add data to it .
I have an idea of making it in array of object - but data inside was cleared after changing activity.
How can I make it ?
I don't know if and how to add Array of object to SharedPreferences , and get value of one element from there.
You should have a look at the documentation of the Intent(s) if you want to do that on the fly associating a key to the value(s) that you want to pass to your second activity.
Anyway, you can think any(sharedpref, database,...) way to pass your parameters but for those kind of things it's a convention and a good practice to follow that.
Don't used share preferences for this...Use the singleton pattern, extend Application, or just make a class with static variables and update them...
You can use .putExtra but since you are communicating with more than one activity the above suggestions are probably the best.
public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}
public static ShareData getInstance(){ return shareData}
//create getters and setters;
}
Why not to use Intents
Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);
in the second activity
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");
EDIT if you want to read more about adding array to shared preferences check this
Is it possible to add an array or object to SharedPreferences on Android
also this
http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html

How do I store multiple values in an array in Android?

For this example I have an array:
String[] books = new String[x];
I would like to store the id and title in each location:
books[0]=>id:0, title:"book title1"
books[0]=>id:1, title:"book title2"
books[0]=>id:2, title:"book title3"
books[0]=>id:3, title:"book title4"
I want to store the id since it may change. I'm getting the id and title from a database. Getting the info isn't the issue. I want to store it this way so in my other functions this returns to I can use something like:
btn.setText(regions[i].title)
Any suggestion on how to handle this would be great.
Do one thing, first create a bean class like BookBean.
Under this declare two variables ID and Title. and declare getters and setters (If u are using eclipse u can easily do this by (Source -> generate getters and setters.. option)
and then declare a ArrayList to store BookBean vale as of follow.
ArrayList<BookBean> bookArrayList=new ArrayList<BookBean>();
for(int i=0;i<=urSize;i++)
{
// create a object for BookBean
BookBean book =new BookBean();
book.setID("what ever");
book.setTitle("what ever");
bookArrayList.ass(book)
}
It is better to use Arraylist with custom class.
see this
class Book
{
String id,title;
/* Cunstructor to store data */
public Book(String id,String title)
{
this.id = id;
this.title = title;
}
}
//declare arraylist
ArrayList<Book> bookList = new ArrayList<Book>();
bookList.add("1","book1");
bookList.add("2","book2");
bookList.add("3","book3");
bookList.add("4","book4");
btn.setText(bookList.get(i).title)
I think you have several options
Use a HashMap where you can use your id as key and value title
Define a class and keep id and title as attributes , define get and set methods.
Keep the objects of the class in a ArrayList

using foreach in onSaveInstanceState throws nullpointerexception

I am trying to save the tags for all fragments in an activity that are currently visible.
So I defined these:
// Fragment TAGS
private final static String EDIT_COLLECTIONS_TAG = "edit collection";
public final static String EDIT_IMAGE_TAG = "edit image";
public final static String ADD_IMAGE_TAG = "add image";
// Collection of Frag Tags
private final static String[] FRAG_TAGS = {EDIT_COLLECTIONS_TAG, EDIT_IMAGE_TAG, ADD_IMAGE_TAG};
And in onSaveInstanceState(Bundle outState) I did:
for(String tag : FRAG_TAGS){
if(getFragmentManager().findFragmentByTag(tag).isVisible()){
outState.putString(tag, tag);
}
}
...but LogCat informed me that the if line was throwing the null pointer exception.
So not knowing why I tried:
if(getFragmentManager().findFragmentByTag(FRAG_TAGS[1]).isVisible()){
outState.putString(EDIT_IMAGE_TAG, EDIT_IMAGE_TAG);
}
...and that worked.
So it seems there isn't a problem with accessing the array. On a lark I changed the array's contents to actually strings: {"EDIT_COLLECTIONS_TAG", "EDIT_IMAGE_TAG", "ADD_IMAGE_TAG"} but that didn't change the outcome.
So what's going on here?
Given the input by Marko Lazic I discovered two errors:
Not all added fragments were given tags, this resulted in nulls. This has been rectified.
Cannot use a static list of all fragment tags because, obviously, some will not have been added yet and as Marko indicated, can't find a fragment that isn't there yet, so this was also throwing null.
Solution:
I needed to find a way to create a dynamic list of tags for added fragments. This was accomplished with:
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
// add attached fragment's tag to set of tags for attached fragments
AddedFragmentTagsSet.add(fragment.getTag());
// if when adding the fragment another fragment has become detached, remove its tag from the set
for(String tag : AddedFragmentTagsSet){
if(getFragmentManager().findFragmentByTag(tag).isDetached()){ // or isVisible() probably
AddedFragmentTagsSet.remove(tag);
}
Log.d(TAG, SCOPE +"contents of AddedFragmentTagsSet: " +tag);
}
}
Thank your for the help, folks.

Passing Bundle into an AsyncTask

I'm struggling with bundles in an AsyncTask. I have two Strings that I want to pass to a AsyncTask, I want to use bundles to accomplish this task.
The code in the MainActivity:
Bundle adresses = new Bundle();
adresses.putString("to", textField1.getText().toString());
adresses.putString("from", textField2.getText().toString());
new PriceTask(getApplicationContext()).execute(adresses);
And in my AsycTask I do it like this:
protected Integer doInBackground(Bundle... b) {
Bundle result = b[0];
String to = result.getString("to");
String from = result.getString("from");
}
It's worth mentioning that my two strings contains something like this
"Sometext here, and sometext here 1234"
Put I can't retrieve the text, my debugger says that the Bundle contains the right information but my String will not contain the right information. When I debug and set breakpoints where my Strings are, it will just have the value:
[t, o]
What am I doing wrong here? Thanks in advance.
In MAin activity replace the below lines::
Bundle adresses = new Bundle();
adresses.putString("to", textField1.getText().toString());
adresses.putString("from", textField2.getText().toString());
new PriceTask(getApplicationContext()).execute(adresses);
with
new PriceTask(getApplicationContext(),textField1.getText().toString(),textField2.getText().toString()).execute();
And in your AsycTask add constructor like below::
String to;
String from;
Context context;
public YourAsyncTask(Context context, String to,String from) {
// TODO Auto-generated constructor stub
this._activity = _activity;
this.to = to;
this.from = from;
}
What you are doing wrong is the way you retrieve the data in the doInBackground method. The argument that method having is a Array type. Please concern the ... What you are doing in the line Bundle result = b[0]; is only getting the 0th element of that Array and pass it to a Bundle reference.
Your given code and details is not enough to give a perfect answer. If all your given codes in the same Java class, you no need to use a Bundle. Instead you can create a ArrayList of type String to contains your values witch you are getting from the TextFields. Then doInBackground also contains a ArrayList as the method argument. Then get all the List items and separate your "to" and "from" values.
If you are stick with the existing code, first try to find out what is inside the result variable.

Categories

Resources