How to make a listview(already created) clickable (Android)? - android

I made a list and now I want when the user clicks an item, it opens a new screen showing the PKMN data. Here's my code:
Kanto.class
public class Kanto extends ActionBarActivity {
//fasendu listaa = making list
ListView listView; //criandu var = making variable
String[] pokemonsKanto = {
"#1 Bulbasaur", "#2 Ivysaur", "#3 Venusaur"
}; //lista = list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kanto);
//continuandu a lista = the other part to the list work
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> array = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, pokemonsKanto);
listView.setAdapter(array);
//lista cabada = finished
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.kanto, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
}
activity_kanto.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Kanto">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
How can I do that? Sorry, I'm a completely newbie .

Now you just have to set an onItemClickListener to your ListView, like this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//create an Intent to your new `Activity` with PKMN data
Intent pkmnActivityIntent = new Intent(Kanto.this, YourPKMNActivity.class);
//pass your pkmn number and name (from your `String` array) in the `Intent`, so it can be shown in the new `Activity`
pkmnActivityIntent.putExtra("name",pokemonsKanto[position] );
//start your new Activity
startActivity(pkmnActivityIntent );
}
});
This listener is activated when the user clicks an item in your list. You can set it right after listview.setAdapter() method.
Edit: Do not forget to declare your new Activity on your manifest.xml file.
Then in your new Activity, just get the pkmn name by using:
String pkmnName = getIntent().getStringExtra("name");
Now you can show your pkmnName in a TextView or something.

You need to add a listener to the items of the list,for example I will give you how to show the text of the item in an alert dialog (you can put the title of the item in a string to pass it in intent rather than display it in an alert dialog) :
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//The title of the Item is recovered in a String
String item = (String) listView.getAdapter().getItem(position);
AlertDialog.Builder adb = new AlertDialog.Builder(kanto.this);
//The title of the alert Dialog
adb.setTitle("Your Item");
//The name of the Item
adb.setMessage("You have selected : "+item);
//the OK button
adb.setPositiveButton("Ok", null);
//show the alert dialog
adb.show();
}
});

Related

showAsDropDown but upwards like spinner

I have used popup listview to work like spinner .I want it to pop upwards like spinner does when its at the bottom of the screen .
I have tried :
popupWindowDogs.showAsDropDown(buttonShowDropDown,5,0);
ALSO,
popupWindowDogs.showAsDropDown(buttonShowDropDown, (int)(Math.round(buttonShowDropDown.getX())),-(totallinear_layouts+buttonShowDropDown.getHeight()));
totallinearlayouts = sum of all heights of linear layouts till the button.
This works properly on a few devices but not like Spinner. How can I make it to work like Spinner? I mean to inflate exactly as the size of the device and the list height. I really appreciate any help. Thanks in Advance.
Reference:https://www.codeofaninja.com/2013/04/show-listview-as-drop-down-android.html
MainActivity.java
public class MainActivity extends Activity {
String TAG = "MainActivity.java";
String popUpContents[];
PopupWindow popupWindowDogs;
Button buttonShowDropDown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize pop up window items list
// add items on the array dynamically
// format is DogName::DogID
List<String> dogsList = new ArrayList<String>();
dogsList.add("Akita Inu::1");
dogsList.add("Alaskan Klee Kai::2");
dogsList.add("Papillon::3");
dogsList.add("Tibetan Spaniel::4");
// convert to simple array
popUpContents = new String[dogsList.size()];
dogsList.toArray(popUpContents);
// initialize pop up window
popupWindowDogs = popupWindowDogs();
// button on click listener
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShowDropDown:
// show the list view as dropdown
popupWindowDogs.showAsDropDown(v, -5, 0);
break;
}
}
};
// our button
buttonShowDropDown = (Button) findViewById(R.id.buttonShowDropDown);
buttonShowDropDown.setOnClickListener(handler);
}
public PopupWindow popupWindowDogs() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewDogs = new ListView(this);
// set our adapter and pass our pop up window contents
listViewDogs.setAdapter(dogsAdapter(popUpContents));
// set the item click listener
listViewDogs.setOnItemClickListener(new DogsDropdownOnItemClickListener());
// some other visual settings
popupWindow.setFocusable(true);
popupWindow.setWidth(250);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
// set the list view as pop up window content
popupWindow.setContentView(listViewDogs);
return popupWindow;
}
/*
* adapter where the list values will be set
*/
private ArrayAdapter<String> dogsAdapter(String dogsArray[]) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dogsArray) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String[] itemArr = item.split("::");
String text = itemArr[0];
String id = itemArr[1];
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
return adapter;
}
}
DogsDropdownOnItemClickListener.java
public class DogsDropdownOnItemClickListener implements OnItemClickListener {
String TAG = "DogsDropdownOnItemClickListener.java";
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
// get the context and main activity to access variables
Context mContext = v.getContext();
MainActivity mainActivity = ((MainActivity) mContext);
// add some animation when a list item was clicked
Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in);
fadeInAnimation.setDuration(10);
v.startAnimation(fadeInAnimation);
// dismiss the pop up
mainActivity.popupWindowDogs.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
mainActivity.buttonShowDropDown.setText(selectedItemText);
// get the id
String selectedItemTag = ((TextView) v).getTag().toString();
Toast.makeText(mContext, "Dog ID is: " + selectedItemTag, Toast.LENGTH_SHORT).show();
}
}

when a spinner item is selected the List doesn't change

I have an activity which has a spinner to select a day and a list that should show the list items according to the item selected from the spinner.
I'm querying the sqlite database and different queries must be used for different items selected on spinner.
I'm using a simple cursor adapter.
I have set onItemSelected(AdapterView<?> parent, View view, int position, long id) for my spinner. In that I check if the selected spinner item equals to today.
If so I need to change the list that is shown.
My problem is that the list stays the same no matter what spinner item is selected. It doesn't change.
Note that my spinner and the list are on same page. Can someone please suggest a solution for this?
public class RecentJobListActivity extends Activity {
ListView listView ;
private Spinner spinner;
private TakenJobDataBaseOpenHelper jobDatabaseHelper;
private Cursor cursor;
SimpleCursorAdapter cursoradapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recent_job_list);
addItemsOnSpinner();
//This is the database helper class
jobDatabaseHelper = new TakenJobDataBaseOpenHelper(this);
String[] fromColumns = {TakenJobDataBaseOpenHelper.TAKENJOBS_COLUMN_RequestID,TakenJobDataBaseOpenHelper.TAKENJOBS_COLUMN_Destination,TakenJobDataBaseOpenHelper.TAKENJOBS_COLUMN_CustomerName};
int[] toViews = {R.id.singleRequestID, R.id.singleDestination,R.id.singleCustomerName};
//when the page first loads the result of queru getAlljobs() will be shown.this works
cursor = jobDatabaseHelper.getAllJobs();
cursoradapter = new SimpleCursorAdapter(this,
R.layout.single_job_activity, cursor, fromColumns, toViews, 0);
listView = (ListView)findViewById(R.id.activities_list);
listView.setAdapter(cursoradapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.recent_job_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addItemsOnSpinner(){
spinner = (Spinner) findViewById(R.id.time_periods_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.time_periods_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String s = parent.getItemAtPosition(position).toString();
//even the log doesn't show.
if(s.equals("Today")){
Log.d("today","today");
cursor = jobDatabaseHelper.getTodayJobs();
cursoradapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
Thank you!!!
Try using CursorAdapter.swapCursor(). That should work.

Android - ListView - Output value in listview to screen

I have a SQLite Database that contains the following information
--------------------------------
Account_Name Account_Balance
--------------------------------
Savings 1000.00
Checking 1000.00
I have the item being output to a Listview. My question is how do I get my OnItemClick to properly tell me the value that was selected? When I click Savings, I want "Savings" to appear through a Toast. When I tried output, I could only output the item position. I don't want the position in the listview, I am more interested in the String value.
public void onItemClick(AdapterView parent, View view, int position, long id)
{
/*What do I need to code here to just have the value outputted*/
//Toast toast = Toast.makeText(getApplicationContext(), temp1, Toast.LENGTH_LONG);
//toast.show();
}
CODE:
main_menu_activity.java
public class main_menu_activity extends Activity implements AdapterView.OnItemClickListener
{
DatabaseHandler db;
ArrayList<Account> account_details;
ListView accountList;
int num;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_activity);
accountList = (ListView)findViewById(R.id.accountListView);
db = new DatabaseHandler(getApplicationContext());
displayListView();
// Empty Account table
//db.deleteFromAccountTable();
accountList.setOnItemClickListener(this);
num = 1;
}
// MENU //
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu_activity, menu);
return super.onCreateOptionsMenu(menu);
}
// MENU //
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// take appropriate action for each action item clicked
switch(item.getItemId())
{
case R.id.action_add_new:
{
// perform add new item action
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Enter account details:");
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Set an EditText view
final EditText input = new EditText(this);
input.setHint("Account Name");
layout.addView(input);
final EditText input2 = new EditText(this);
input2.setHint("Account Balance");
layout.addView(input2);
alert.setView(layout);
alert.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
if (input.getText().toString() != null)
{
// Create empty Account
Account temp_account;
temp_account = new Account();
// Save information to SQLiteDatabase
temp_account.setAccountName(input.getText().toString());
temp_account.setAccountBalance(Double.parseDouble(input2.getText().toString()));
// Add temp account
db.addAccount(temp_account);
displayListView();
}
else
{
dialogInterface.cancel();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
// Output to logcat
/*ArrayList<Account> allAccounts = db.getAllAccounts();
for (Account account: allAccounts)
{
Log.d("Output", Integer.toString(account.getAccountID()));
Log.d("Output", account.getAccountName());
Log.d("Output", Double.toString(account.getAccountBalance()));
}*/
// cancel
dialogInterface.cancel();
}
});
alert.show();
return true;
}
default:
{
return super.onOptionsItemSelected(item);
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
/* CODE TO OUTPUT SELECTED LISTVIEW VALUE */
}
// DISPLAY ACCOUNT LISTVIEW //
public void displayListView()
{
account_details = new ArrayList<Account>();
account_details = db.getAllAccounts();
accountList.setAdapter(new ListViewBaseAdapter(account_details,this));
}
}
listview.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<TextView
android:id="#+id/account_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textColor="#00628B"
android:textSize="22dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/account_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textColor="#00628B"
android:textSize="22dp"/>
</RelativeLayout>
You're going to need to have a custom adapter (and layout file) for the row and then add handler for each View in that row.
Vogella has some awesome tutorials so instead of regurgitating them I will point you there.
If you just want to get the name, then why don't you try something like this:
Define an XML layout that contains a row, probably a TextView for each.
Put this code in a custom adapter.
Set the id for the value that contains the savings/checking name, let's say android:id="#+id/accountType
Find that view in the onItemClicked, and get the text.
The code looks like:
String type=((TextView) view.findViewById(R.id.accountType)).getText();
I assume you have your own custom adapter for that. So you can just attach OnClickListeners at the getView() method to every needed View (TextView in your case). Then inside this listener do the following:
View.OnClickListener() {
#Override
public void onClick(View v) {
TextView myView = (TextView) v;
Toast.makeText(context, myView.getText(),Toast.LENGTH_SHORT).show();
}
}

Generate background colour in listView from database

I have a listView generated from a database, is there a way to make a background colour or a picture to each "section" in the list:
if the first symbol in "Tip" is "W" the background should be Green, and if its "L" it should be red
Im thinking something like this, but i have no idea where to put it since it have to be done in every section:
tipvalue = BetsDbAdapter.KEY_TIP;
//Here to split the value to gain only "W" or "L"
String arrtip[] = tipvalue.split(" ", 2);
temptip = arrtip[0];
//then set background
if (temptip.equals("W")) {
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
To the left is my listView and right is the xml file to make each "section" in the listview
Here is my database:
This is code generating the listView
public class StoredBets extends Activity {
private BetsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
dbHelper = new BetsDbAdapter(this);
dbHelper.open();
}
#Override
public void onStart(){
super.onStart();
displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.results, menu);
return true;
}
public void testknap1(View v) {
Intent myIntent = new Intent(StoredBets.this, Overview.class);
startActivity(myIntent);
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllStats();
String[] columns = new String[] {
BetsDbAdapter.KEY_SMATCH,
BetsDbAdapter.KEY_TIP,
BetsDbAdapter.KEY_BETAMOUNT,
BetsDbAdapter.KEY_BODDS
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.smatch,
R.id.tip,
R.id.bodds,
R.id.betamount,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.storedbets,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView2);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String betMatch =
cursor.getString(cursor.getColumnIndexOrThrow("smatch"));
Toast.makeText(getApplicationContext(),
betMatch, Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(StoredBets.this, SetWinVoidLoss.class);
myIntent.putExtra("id", id);
startActivity(myIntent);
}
});
}
}
EDIT 2:
#amal
This is the layout(results.xml) with the listview
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".StoredBets" >
<ListView
android:id="#+id/listView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/button1" >
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="180dp"
android:onClick="testknap1"
android:text="Button" />
</RelativeLayout>
you can get a fair idea from my code,
code snippet for displaying ListViews where the "curSelected" item has a different background:
final ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new BaseAdapter()
{
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = new TextView(ListHighlightTestActivity.this);
convertView.setPadding(10, 10, 10, 10);
((TextView)convertView).setTextColor(Color.WHITE);
}
convertView.setBackgroundColor((position == curSelected) ?
Color.argb(0x80, 0x20, 0xa0, 0x40) : Color.argb(0, 0, 0, 0));
((TextView)convertView).setText((String)getItem(position));
return convertView;
}
public long getItemId(int position)
{
return position;
}
public Object getItem(int position)
{
return "item " + position;
}
public int getCount()
{
return 20;
}
});
This is a tutorial of how to write an adapter for a list view. amal is right, you can change the separate items in the list view in the getView() method.

Using variable value with R.array

I have an activity with list view. On click of an item of the list view an intent is send to the next list containing the value of the clicked item. The list is being generated using an xml file.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Selected item
String cat = ((TextView) view).getText().toString();
// Launching new Activity on selecting single Item List
Intent intent = new Intent(getApplicationContext(), ContentListing.class);
// Sending data to new activity
intent.putExtra("cat", cat);
startActivity(intent);
}
On the next activity I again have to read an xml file but this file will vary with respect to the item clicked on previous list.
// Creating a handle to capture data sent from previous activity
Intent intent = getIntent();
// Storing the category into a variable
String cat = intent.getStringExtra("cat");
// Storing string resources into Array
String[] itemList = getResources().getStringArray(R.array.itemList);
I wanted to do something like String[] itemList = getResources().getStringArray(R.array.cat); i.e. R.array.variable which doesn't work for me. I am new to java and android so any kind of help(that is easy to understand and implement) is welcome.
Also, I wanted the name of this second activity to be different each time with respect to the item clicked. What should I be doing for this?
EDIT:
This is my updated code which give the error about getContext()
public class ContentListing extends ListActivity {
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_listing);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
// Creating a handle to capture data sent from previous activity
Intent intent = getIntent();
// Storing the category into a variable
String cat = intent.getStringExtra("cat");
setTitle(cat);
// Line that shows error
int resourceId = Resources.getSystem().getIdentifier(cat, "array", getContext().getPackageName());
Log.d("Print message1: ", String.valueOf(resourceId)+"\n");
if(resourceId != 0) {
Log.d("Print message: ", String.valueOf(resourceId)+"\n");
// Storing string resources into Array
//String[] itemList = getResources().getStringArray(R.array.itemList);
String[] itemList = getResources().getStringArray(resourceId);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item2, R.id.label, itemList));
ListView lv = getListView();
// Listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single Item List
Intent intent = new Intent(getApplicationContext(), ContentListing.class);
// Sending data to new activity
intent.putExtra("product", product);
startActivity(intent);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_content_listing, menu);
return true;
}
}
You can use variables to load the arrays from resources like this:
int resourceId=Resources.getSystem().getIdentifier(cat, "array", getContext().getPackageName());
if(resourceId != 0){
getResources().getStringArray(resourceId);
}
To set the title of the activity,
setTitle(cat);
I would consider instead though, checking the value of the extra you passed in, then having a if else statement that loads the resource. You have a better guarantee that things will work correctly.
int resId = R.array.defaultValue;
if(cat.equals("category1"){
resId = R.array.categoryOneValues;
} else if(cat.equals("category2"){
resId = R.array.categoryTwoValues;
}
getResources().getStringArray(resId);

Categories

Resources