I have created a List View containing-
"Baby Items"
"Bakery"
"Baking"
"Beverages"
"Canned Goods"
"Cereal Breakfast"
"Condiments"
"Dairy"
"Frozen Foods"
"Miscellaneous"
"Non-Food Items"
"Pasta / Rice"
"Snacks"
Then, I want to create an onClick layout to each list view also.
How can I use intent for the Baby_Items layout if I click on the Baby Items in Shopping Items (ListView)
Shopping Items (JAVA)
public class ShoppingItems extends ActionBarActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] item_category = {"Baby Items", "Bakery", "Baking",
"Beverages", "Canned Goods", "Cereal Breakfast", "Condiments",
"Dairy", "Frozen Foods", "Miscellaneous", "Non-Food Items",
"Pasta / Rice", "Snacks"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_items);
listView = (ListView) findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,item_category);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+ " is selected",Toast.LENGTH_LONG).show();
}
});
}
BABY_ITEMS (JAVA)
public class Baby_Items extends ActionBarActivity {
ArrayList<Products> products = new ArrayList<Products>();
ListAdapter boxAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_baby__items);
ListView lvMain = (ListView) findViewById(R.id.lvbabyitems);
lvMain.setAdapter(boxAdapter);
}
void fillData() {
for (int i = 1; i <= 20; i++) {
products.add(new Products("Products " + i, i * 100, false));
}
}
public void showResult(View v) {
String result = "Selected Product are :";
int totalAmount=0;
for (Products p : boxAdapter.getBox()) {
if (p.box){
result += "\n" + p.name;
totalAmount+=p.price;
}
}
Toast.makeText(this, result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
}
Check this tutorial for understanding basics about ListView implementation.You can use Intent for starting new Activity on ListView item click.
try this in onClick Method
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+ " is selected",Toast.LENGTH_LONG).show();
Intent intent = new Intent(ShoppingItems.this, Baby_Items.class);
intent.putExtra("baby_item", "" + parent.getItemAtPosition(position));
startActivity(intent);
}
});
and in Baby_Items activty get extra data like
if (getIntent().getExtras().containsKey("baby_item")) {
String item = getIntent().getStringExtra("baby_item");
}
Related
i use Retrofit,
item shown but i can't selected.
after clicking item, toast and spinner not show anything (i can't select item on spinner).......
private List<String> spinnerItem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
spinnerItem = new ArrayList<>();
setSpinner();
}
public void displayCities(List<CityResponse.City> cities) {
mainBinding.helloText.setText(cities.get(508).getNama());
for (CityResponse.City city : cities) {
Log.d(TAG, city.getNama());
spinnerItem.add(city.getNama());
}
}
private void setSpinner(){
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainBinding.spinnerCity.setAdapter(adapter);
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "City : " + citySelected, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(CityActivity.this, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}
Current solution:
You set the adapter in the setSpinner() with a list called spinnerItem which is empty for this moment. Then in displayCities() you fill list with values but forget to notify the adapter about new values added.
public void displayCities(List<CityResponse.City> cities) {
for (CityResponse.City city : cities) {
spinnerItem.add(city.getNama());
}
// 2. notify adapter that you have inserted new cities to the list
}
private void setSpinner(){
// 1. set the adapter with spinnerItem which is empty here
ArrayAdapter<String> adapter = new ArrayAdapter<>(..., ..., spinnerItem);
mainBinding.spinnerCity.setAdapter(adapter);
...
}
If adapter is local variable for setSpinner() then displayCities() does not have access to the adapter. Create adapter as global and then you can call adapter.notiftDataSetChanged() in point 2 comment
Your setSpinner() method:
private void setSpinner(final Context context, Spinner spinnerCity, List<Object> spinnerItem) {
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCity.setAdapter(adapter);
spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
//adapter.notifyDataSetChanged();
Toast.makeText(context, "City : " + citySelected, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}
CityActivity.java:
Spinner spinnerCity = findViewById(R.id.spinner);
String[] spinnerItem = {"A", "B", "C", "D", "E"};
setSpinner(CityActivity.this, spinnerCity, Arrays.<Object>asList(spinnerItem));
I have an ArrayList that takes 3 elements each item.
public class Aciklama extends ArrayList<Parcelable> {
String desc;
String title;
int resim;
public Aciklama(String title, String desc, int resim) {
this.desc = desc;
this.title = title;
this.resim = resim;
}
// ... Getters and Setters
}
When I click an item in ListView I want to see just resim and desc part in the other activity. I have ArrayList named elemanalicak in a class named Core.
public class CategoryGoster extends AppCompatActivity {
ListView listView;
OzelAdaptor arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_goster);
listView = (ListView) findViewById(R.id.listView_category_goster);
arrayAdapter=new OzelAdaptor(this, elemanalicak);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent mIntent = new Intent(CategoryGoster.this, DetailActivity.class);
mIntent.putParcelableArrayListExtra("description", elemanalicak.get(i).getResim());
mIntent.putParcelableArrayListExtra("pic", elemanalicak.get(i).getDesc());
startActivity(mIntent);
}
});
}
}
This is the place I want to show.
public class DetailActivity extends AppCompatActivity {
ImageView mImageView;
TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
mImageView = (ImageView) findViewById(R.id.imageViewDetail);
mTextView = (TextView) findViewById(R.id.textViewDetail);
Bundle mBundle = getIntent().getExtras();
if (mBundle != null) {
mImageView.setImageResource(mBundle.getInt("pic"));
mTextView.setText(mBundle.getString("description"));
}
}
}
resim is a pic and the desc is a description. How can I only send resim and desc to the DetailActivity?
The processing in your DetailActivity is fine. You just need to pass the data properly in your DetailActivity. Use the following code segment instead while launching the DetailActivity.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent mIntent = new Intent(CategoryGoster.this, DetailActivity.class);
mIntent.putExtra("description", elemanalicak.get(i).getResim());
mIntent.putExtra("pic", elemanalicak.get(i).getDesc());
startActivity(mIntent);
}
});
Just use putExtra, instead of putParcelableArrayListExtra. putParcelableArrayListExtra is used for passing an array between intents.
I am not able to get the old position of my ListView after filtering, for example I should be getting position 3,5,8 after filtering, but I'm getting the default 0,1,2 position.. Do you guys have any idea why? Here's my code..
public class Application_applicant_list extends AppCompatActivity {
private ListView applicant;
static String applId;
private ArrayAdapter adapter;
SearchView sv;
Bundle b;
Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_application_list);
sv = (SearchView) findViewById(R.id.appSv);
applicant = (ListView) findViewById(R.id.listView_allForms_from_list);
adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1);
applicant.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView < ? > adapterView, View view, int position, long id) {
intent = new Intent(Application_applicant_list.this, Application_form_from_list.class);
b = new Bundle();
b.putInt("position", position);
intent.putExtras(b);
Toast.makeText(getApplicationContext(), "Position:" + position,
Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
}
This is the part where I retrieve from the database, they're in the same class
#Override
protected void onResume() {
DBHelper db = new DBHelper(this);
ArrayList < String > ArrApp = new ArrayList < String > ();
for (int i = 0; i < db.getAll_Appl().size(); i++) {
ArrApp.add(String.valueOf(db.getAll_Appl().get(i).getApplId())); // + '\t' + '\t' + '\t' + db.getAll_IOP().get(i).getId());
}
adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, ArrApp) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView item = (TextView) super.getView(position, convertView, parent);
item.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
item.setGravity(Gravity.CENTER);
item.setPadding(0, 10, 0, 10);
return item;
}
};
applicant.setAdapter(adapter);
super.onResume();
}
}
This is my nextActivity.java where I retrieve the position
Bundle b2 = getIntent().getExtras();
if (b2 != null) {
int position = b2.getInt("position"); // position is from induction and operation page menu item click
form_from_list = db.getAll_Appl().get(position);
formAppId.setText(form_from_list.getApplId());
Because, the position that return in onItemClick is the position of ListView item not the position in list datasource (in your case it is ArrApp).
Therefore, I think you should get the value of ListView item then pass it to another Activity instead of the position.
Like
applicant.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView < ? > adapterView, View view, int position, long id) {
String clickedItemValue = (String) adapterView.getAdapter().getItem(position); // cast to String because your list datasource is a list String
// pass clickedItemValue to another activity
}
});
I have a ListView and I want to run a function according to the clicked value on ListView for now i just want to know only how to get and toast the value I was trying to do it but don't know the proper code... please check my code.
public class SubCategory extends AppCompatActivity implements View.OnClickListener {
private ListView listView;
String buttonType;
ArrayAdapter adapter;
static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana"};
static final String[] NAMES = new String[] { "Sachin", "Brett", "Shane", "Zaheer"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_category);
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
buttonType = bundle.getString("BUTTON_CLICKED");
}
if(buttonType != null && buttonType.equals("A")) {
adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, FRUITS);
} else if(buttonType != null && buttonType.equals("B")) {
adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, NAMES);
}
listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(adapter);
}
public void getList() {
Toast.makeText(listView.getContext(), Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.listview:
getList();
break;
}
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
list.get(position).GET_INFORMATION(); //GET_INFORMATION will be the method in your POJO class
}
});
try this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value="";
if(!TextUtils.isEmpty(buttonType) && buttonType.equals("A")) {
value=FRUITS[position];
} else if(!TextUtils.isEmpty(buttonType) && buttonType.equals("B")) {
value=NAMES[position];
}
// you can get value in "value"
showToast(value);
}
});
public void showToast(String value) {
Toast.makeText(this,value, Toast.LENGTH_LONG).show();
}
To add click listener to listview follow these steps
1.add click listener like this in oncreate method of the activity.
listView.setOnItemClickListener(this);
2.Implement OnItemClickListener in the activity.
public class Main2Activity extends AppCompatActivity implements AdapterView.OnItemClickListener {
3.Override the onItemClick method in the activity.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Call method here
}
I'm having a problem with this. I am using cursor adaptor. What my problem is when the checkbox is checked it will get the value and then when a button is clicked the data will be deleted. By the way I am displaying the checkbox with listview.
public class ListViewAdapter extends CursorAdapter {
SparseBooleanArray sba = new SparseBooleanArray();
public ListViewAdapter (Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.custom_dialog_box, parent, false);
ViewHolder holder = new ViewHolder();
holder.textView = (TextView) retView.findViewById(R.id.number);
holder.cb = (CheckBox) retView.findViewById(R.id.checkBox1);
retView.setTag(holder);
return retView;
}
private static class ViewHolder {
TextView textView;
CheckBox cb;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
final int position = cursor.getPosition();
final CheckBox CheckBoxPersonName = (CheckBox) view.findViewById(R.id.checkBox1);
CheckBoxPersonName.setTag(cursor);
CheckBoxPersonName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
sba.put(position, true);
}
else {
sba.put(position, false);
}
}
});
CheckBoxPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
TextView textViewPersonPIN = (TextView) view.findViewById(R.id.number);
textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
}
}
Here is my mainActivity where the button will be clicked.
public class TemplateActivity extends Activity {
CheckBox cb;
Button btnSort, btnDel;
private ListViewAdapter listAdapter;
private RetailerDatabaseHelper dbHelper;
private ListView listView;
private static final String TAG = TemplateActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_template);
btnSort = (Button) findViewById(R.id.btnSort);
btnDel = (Button) findViewById(R.id.btnDelete);
dbHelper = new RetailerDatabaseHelper(this);
listView = (ListView) findViewById(R.id.listViewData);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Control: " + listView.getCheckedItemPositions());
Cursor c = (Cursor) parent.getAdapter().getItem(position);
String name = c.getString(1);
String number = c.getString(2);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(TemplateActivity.this);
alertDialog.setTitle("RETAILER");
alertDialog.setMessage("Are you sure you want to send " + name + " load to " + number + " ?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//insertData(textVal, value);
dialog.dismiss();
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
btnDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = listView.getAdapter().getCount();
SparseBooleanArray array = listView.getCheckedItemPositions(); /* 11/07/15 */
System.out.println("Count: "+ count);
/* 11/07/15 */
for(int x = 0; x < array.size(); x++)
{
if(array.get(x)) /* 11/07/15 */
{
Log.d(TAG, "Checked: " + listView.getTag());
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
listAdapter.notifyDataSetChanged();
}
}
});
It is working but when the listview data is not clicked the checkbox value is not displaying.
You are declaring SparseBooleanArray as null here:
SparseBooleanArray array = null;
and no assignment to array.. and you are using it in for loop, then it will definitely give you null reference error.