Using variable value with R.array - android

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);

Related

SQLite row IDs do not match the ListView row IDs

I have an SQLite database and a ListView displaying in the main activity. In the ListView, I display the details of each list number and upon pressing the list item, a new activity opens up which displays the details in a TextView.
I have a delete function for each of these ListViews and they are not working properly. Essentially, a unique ID is given to each created ListView, which is how the SQLite databases should work. However, upon deleting a row within the ListView, the unique ID increases but the row ID deletes that number and moves everything up. This means that after you delete an item, the row IDs and the database IDs no longer match up and when trying to select an item within the ListView, it crashes. This is an extract from my database adapter class:
public Integer deleteStat(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(STATS_TABLE, "id = ? ", new String[]{Integer.toString(id)});
}
This is my first attempt in the main activity. I got some information from this post but a failed to get the correct integer and received syntax errors:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView pos = (TextView) findViewById(R.id.editTitle);
displayText(Integer.parseInt(pos.getText().toString()));
}
});
}
public void displayText(int pos)
{
pos++;
String s = "";
s += pos;
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtra("id", s);
startActivity(intent);
}
This is my second attempt in the main activity. I used this tutorial to help me. The code I used from that website ruined the entire delete functionality:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int id_To_Search = arg2 + 1;
int id_To_Search = arg0.getCount() - arg2;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
How do I get the database IDs to match up with the row IDs? Any suggestions on how to do that?
EDIT: Added in Hashmap Code. When I press on a ListView Item, nothing happens
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mydb = new StatisticsDbAdapter(this);
ArrayList array_list = mydb.getAllStats();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
obj = (ListView) findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
/*
New code starts here
*/
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
//means this is the view part not the add contact part
Cursor cursor = mydb.getData(Value);
hashMap.put(cursor.getString(1), cursor.getInt(0));
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int arg2, long arg3) {
TextView textView = (TextView) view.findViewById(R.id.editTitle);
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", hashMap.get(textView.getText().toString()));
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
}
}
You should never pass a ListView position to delete a row in a database. I have done that many times before. First of all, within the class you are managing the click events, create a new HashMap. This HashMap will be used to store our row IDs from the database and we'll refer to that rather than the ListView item position. To create it, type this code:
public HashMap<String, Integer> hashMap = new HashMap<>();
Once you have done that, in the function where you display all of the rows in the ListView, you must also load up the same items into the HashMap like this:
hashMap.put(cursor.getString(1), cursor.getInt(0));
Please note that cursor.getString(1) might not be what you used. Please replace the 1 with your appropriate column number that has the name stored within it. cursor.getInt(0) gets the row ID from the database and the column number might be different for you, too. Now, within our OnClickListener function, we can type:
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view) {
TextView textView = (TextView) view.findViewById(R.id.editTitle);
Bundle bundle = new Bundle();
bundle.putInt("id", hashMap.get(textView.getText().toString()));
Intent intent = new Intent(getApplicationContext(), DisplayStatsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
Please note that the hashMap variable needs to be within the same class where you manage the click events of your ListView or you will get mistakes. Some of the parametres that you originally passed were removed since you don't need them. Also, I found this to work much better using a RecyclerView but that's now up to you. If you're having problems, please don't hesitate to comment below and I'll try to answer as soon as possible.

get value display in spinner

How can i display selected item in spinner A show in spinner B..?
<string-array name="type_report">
<item>Emergency</item>
<item>Sponsor</item>
<item>House</item>
</string-array>
Both of spinner used same "type_report" ..spinner A and B will show Emergency in first position. My question is when i choose "House" in spinner A in activity home , then spinner B in other activity will show "House" in first position ..
spinner A list
<item>Emergency</item>
<item>Sponsor</item>
<item>House</item>
after choose "House"
spinner B list will show
<item>House</item>
<item>Emergency</item>
<item>Sponsor</item>
spinnerA.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item is selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Intent intent=new Intent(this,SecondaActivity.class);
intent.putExtra("index",pos);
startActivity(intent);
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing, just another required interface callback
}
});
Now in your secondActivity you have to place the selected index's item on first position like this
Intent mIntent = getIntent();
int pos= mIntent.getIntExtra("index", 0);
String valueAtIndex = yourArray[pos];
for(int i = pos; i > 0; i--){
yourArray[i] = yourArray[i-1];
}
yourArray[0] = valueAtIndex;
//now set this array to second Spinner
ArrayAdapter spinnerBArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
yourArray);
spinnerB.setAdapter(spinnerArrayAdapter);
Tested and working code

How do I replace an item in a listview?

I have a listview which is populated by an array adpater. A user starts on activity a and after clicking an item in the listview is taken to activity b where they can edit the item they clicked. The edited item from B is sent back to A through an intent after the user returns to A. I want the original item clicked in A to be replaced with the data received from the intent from B.
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
// setListAdapter(adapter);
final ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
//intent receiving data from Activity B; I want to add in statement to change the original item clicked to this new String, edit;
Bundle fromedit = getIntent().getExtras();
if (fromedit != null) {
String edit = fromedit.getString("BENG");
int ps = fromedit.getInt("POSITION");
}
//onclicklistener for the listview
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Notes.this, EditNote.class);
intent.putExtra("KEY", values.get(position).toString());
intent.putExtra("POSITION", position);
startActivity(intent);
}
});
Thanks!
In your original activity you need to keep an int variable referring to the selected item index on the list. So your onItemClick() would look like that:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentSelected = position;
Intent intent = new Intent(Notes.this, EditNote.class);
intent.putExtra("KEY", values.get(position).toString());
intent.putExtra("POSITION", position);
startActivity(intent);
}
When you return from the activity where you modify the data you need to update the item of your values list and call adapter.notifyDataSetChanged().
Have you tried to update your list by calling mList.set(index, Object); and then refreshing the Adapter to update ListView displayed data?
You can use the ArrayList#set() method, thus if your 'values' dataset is an ArrayList.
The java.util.ArrayList.set(int index, E element) replaces the element at the specified position in this list with the specified element.
modify your code as follows:
//intent receiving data from Activity B; I want to add in statement to change the original item clicked to this new String, edit;
Bundle fromedit = getIntent().getExtras();
if (fromedit != null) {
String edit = fromedit.getString("BENG");
int ps = fromedit.getInt("POSITION");
values.set(ps, edit);
adapter.notifyDataSetChanged();
}

Android how simple remove list item from listview?

i have a list of folder in directory, on onListItemClick event calling show alert dialog and after click on yes button i processing delete of the file. I would like after successful delete of the file also remove selected item from list or refresh view with new values.
How can i do it most simple?
Code of Package activity:
public class PackageListActivity extends ListActivity
{
// create instance of App helper class
AppHelper helper = new AppHelper();
String folderNameToDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get arrayListOf folders
ArrayList<String> folderArrayList = helper.getListOfFileInDirectory(null);
// convert array listo to simple array
String[] arr = folderArrayList.toArray(new String[folderArrayList.size()]);
// set to aray adapter
setListAdapter(new PackageArrayAdapter(this, arr));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//get selected items
String selectedValue = (String) getListAdapter().getItem(position);
//Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
this.showAlerDialog(selectedValue);
}
remove the arraylist item by giving the position to be removed and then call notifyDataSetChanged() method by using your adapter
folderArrayList.remove(<index of element to remove>);
PackageArrayAdapter.notifyDataSetChanged();

Adding multiple event to listview

I searched stackoverflow but couldnt find a answer(sure there is one somewhere) but I am trying to add a activity for each listview input. I can manage it with one intent but how do I give each listview input a seperate activity. So to be clear, I want to make every item have a serperate activity.
Currently use this code to initiate a activity but want individual activities for each item.
public class ListviewActivityActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.list_products);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
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 List Item
Intent i = new Intent(getApplicationContext(), BMICalculatorActivity.class);
startActivity(i);
}
});
}
Have tried adding this but it failed to work
private static final int ACTIVITY_0 = 0;
private static final int ACTIVITY_1 = 1;
private static final int ACTIVITY_2 = 2;
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
final Intent intent = new Intent();
// Set up different intents based on the item clicked:
switch (position)
{
case ACTIVITY_0:
intent.setClass(this, listview.activty.BMICalculatorActivity.class);
break;
case ACTIVITY_1:
intent.setClass(this, listview.activty.BodyLog.class);
break;
I know its probally simple to sort so any help would be amazing. Thanks
I think you want something like this :
Intent i = null;
switch (position)
{
case ACTIVITY_0:
i = new Intent(getApplicationContext(), BMICalculatorActivity.class);
break;
case ACTIVITY_1:
i = new Intent(getApplicationContext(), BodyLog.class);
break;
}
if(i != null)
{
startActivity(i);
}
Try something like this:
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i;
// selected item
String product = (String) lv.getItem(position);
if(product.equals("photoshop"))
i = new Intent(ListviewActivity.this, Photoshop.class);
else if (product.equals("final cut pro"))
i = new Intent(ListviewActivity.this, FinalCutPro.class);
else
i = new Intent(ListviewActivity.this, Generic.class);
startActivity(i);
}
});
Another option would be to make a POJO that held the name of the listview entry and the class to call. And add an array of those instead of an array of Strings. This will require using an ArrayAdapter of some kind. Then when you get the Item, you simply call startActivity(new Intent(listviewActivity.this, myPojo.classToCall); You should be able to find a good example of that somewhere on SO...

Categories

Resources