Setting ListView - java

I am having trouble with listview and spinners. I am using a list view to display items and using a spinner to filter between categories and a button to refresh the view. My problem is that after selecting a different category it does not change the listView and reverts the spinner to the original category. I have tried using .clear() and an onClickListener() but my problem persists. Is there a way to make the spinner change the items in the listView after clicking the button?
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.content.ContentValues.TAG;
public class MenuFragment extends Fragment {
private ListView menuList;
private Spinner menuSpinner;
private Button buttonRefresh;
//private ArrayList<Menu> menuArrayList ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
Log.i(TAG, "onCreateView of MenuFragment has loaded");
//menuApps=(TextView)rootView.findViewById(R.id.menuApps);
//menuTitle=(TextView)rootView.findViewById(R.id.menuTitle);
menuList=(ListView)rootView.findViewById(R.id.menuList);
menuSpinner=(Spinner)rootView.findViewById(R.id.menuSpinner);
buttonRefresh=(Button)rootView.findViewById(R.id.buttonRefresh);
//menuSpinner.setOnItemClickListener(new View.OnItemClickListener());
//menuViewingMethod();
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
menuViewingMethod();
Log.i(TAG,"Refresh has been clicked");
}
});
return rootView;
}
public ListView menuViewingMethod(){
List<String> list=new ArrayList<>();
list.add("Appetizers");
list.add("Salads");
list.add("Soups");
list.add("Side Items");
list.add("Entrees");
list.add("Desserts");
//sets up the spinner
ArrayAdapter<String>dataAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
menuSpinner.setAdapter(dataAdapter);
String input= menuSpinner.getSelectedItem().toString();
Log.d(TAG,input);
if (input=="Appetizers"){
//menuList.clear();
/*menuList.setAdapter(arrayAdapter);
menuArrayList.add("Gerst Sampler – $12.99");
menuArrayList.add("Fried Oyster Basket – $11.99");
menuArrayList.add("Gerst Ham Rolls - $11.99");
menuArrayList.add("Bavarian Kraut Balls – $8.99");
Log.i(TAG,"Spinner item Appetizers has been selected");*/
String[] apps = new String[]{"Gerst Sampler – $12.99",
"Fried Oyster Basket – $11.99",
"Gerst Ham Rolls - $11.99",
"Bavarian Kraut Balls – $8.99"};
ArrayList<String> menuArrayList= new ArrayList<String>(Arrays.asList(apps));
ArrayAdapter<String>arrayAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,menuArrayList);
menuList.setAdapter(arrayAdapter);
}
//https://android--code.blogspot.com/2015/08/android-listview-add-items.html
else if (input=="Salads"){
/*menuArrayList.clear();
menuList.setAdapter(arrayAdapter);
menuArrayList.add("Salad1");*/
String[] salads = new String[]{"Salad1", "Salad 2", "Salad 3"};
List<String> menuArrayList= new ArrayList<String>(Arrays.asList(salads));
ArrayAdapter<String>arrayAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_2,menuArrayList);
menuList.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
else if(input=="Soups"){
/*menuList.setAdapter(arrayAdapter);
menuArrayList.clear();*/
String[] soups = new String[] {"Soup 1", "Soup 2", "Soup 3"};
List<String> menuArrayList= new ArrayList<String>(Arrays.asList(soups));
ArrayAdapter<String>arrayAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,menuArrayList);
menuArrayList.clear();
menuList.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
String[] apps = new String[]{"Gerst Sampler – $12.99",
"Fried Oyster Basket – $11.99",
"Gerst Ham Rolls - $11.99",
"Bavarian Kraut Balls – $8.99"};
List<String> menuArrayList= new ArrayList<String>(Arrays.asList(apps));
ArrayAdapter<String>arrayAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,menuArrayList);
menuList.setAdapter(arrayAdapter);
// menuSpinner.setOnTouchListener((View.OnTouchListener) this);
arrayAdapter.notifyDataSetChanged();
return menuList;
}
}

Would suggest two things:
Relocate your spinner setup from 'menuViewingMethod()' to 'onCreateView()'. This is probably the cause of your spinner resetting to 0 every time the 'menuViewingMethod()' is triggered.
In 'menuViewingMethod()', make 'menuArrayList' and 'arrayAdapter' class variable and reload the list with new contents instead.
String[] salads = new String[]{"Salad1", "Salad 2", "Salad 3"};
menuArrayList.clear();
menuArrayList.addAll(Arrays.asList(salads));
arrayAdapter.notifyDataSetChanged();

Related

how to display listview items, when a user enter some number in textbox?

how to display listview items in android, when a user enter some number in edittext and click on a button to display the specified number of list items on the next activity ?
I have one EditText and a Button on MainActivity1 and a ListView and TextView on MainActivity2. TextView is just for letting me know tht value is passing on next screen.
MainActivity.java
package com.populatelist;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edt = (EditText)findViewById(R.id.editText1);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myin = new Intent(MainActivity.this,MainActivity2.class);
myin.putExtra("textbox", edt.getText().toString());
startActivity(myin);
}
});
}
}
MainActivity2.java
package com.populatelist;
import android.support.v7.app.ActionBarActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity2 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
TextView tv = (TextView)findViewById(R.id.textView1);
Intent myin2 = getIntent();
String str = myin2.getStringExtra("textbox");
tv.setText(str);
final ListView lv = (ListView) findViewById(R.id.listView1);
String[] arrStr = new String[] {
"Hello World",
"Hello India",
"Hello Rajasthan",
"Hello Jodhpur",
"Hello Mujeeb"
};
final List<String> hello_list = new ArrayList<String>(Arrays.asList(arrStr));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hello_list);
int n = Integer.parseInt(str);
lv.setAdapter(arrayAdapter);
}
}
You can simply add the coming value at last of your string array like
String[] arrStr = new String[] {
"Hello World",
"Hello India",
"Hello Rajasthan",
"Hello Jodhpur",
"Hello Mujeeb",
str
};
It will show your input value to last position of your listview.
And if you want to add new items and show old as well then you have to pass whole string array to previous activity and add new value to last position, pass it when start next activity. By using this you can see all data on listview.
Whenever you get value in second activity create a new array "b" with required no of values.
String str = myin2.getStringExtra("textbox");
int noOfNames = Integer.parseInt(str);
String[] b = new String[StringnoOfNames];
Then copy the items from the original array
b = Arrays.copyOf(arrStr, noOfNames);
final List<String> hello_list = new ArrayList<String>(Arrays.asList(b));
First, validate if your EditText isn't null, here your app may crash
if (edt.getText().length() > 0) {
Intent myin = new Intent(MainActivity.this,MainActivity2.class);
myin.putExtra("textbox", Integer.parseInt(edt.getText().toString()));
startActivity(myin);
}
Then handle your intent
ListView lv = (ListView) findViewById(R.id.listview1);
ArrayAdapter<String> arrayAdapter = null;
int number = intent.getIntExtra("textbox", 0);
switch (number) {
case 0:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrStr);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
case 1:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, AnotherSourceArray);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
case 2:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, AnotherSourceArray);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
...
default:
break;
}
Note - this is just sample. You can resolve this on many another ways. Each switch case may contain another data to display. Using default layouts for listviews may be frustrating, better way is to create custom class which extends ArrayAdapter<String>

Unable to get list items correct code using Java

I am trying to create a list view in Java that allows each list item to open a web url address but I can not seem to get the code right. Please can some one show me where IO going wrong.
package com.sasquatchapps.hydraquip10.bestofmonsterquest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Season1Activity extends Activity{
private String episodes[] = {"America's Loch Ness Monster","Sasquatch Attack",
"Giant Squid Found","Birdzilla","Bigfoot","“Mutant K9","Lions in the Backyard","Gigantic Killer Fish","Swamp Beast","Russia's Killer Apemen","Unidentified Flying Creatures","The Real Hobbit",
"Giganto: The Real King Kong","American Werewolf"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new
ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, episodes);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "Item clicked;" + episodes[position], Toast.LENGTH_SHORT).show();
if (position == 0) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=o7-RdxrCFAg"));
startActivity(intent);
}
}
}
You have some errors - Where is your listview? Modify your code
1) create listview -
ListView myList;
2) In your onCreate assign this list:
myList = (ListView) findViewById(R.id.my_list);
3) Set adapter to your list:
myList.setAdapter(adapter);

SimpleCursorAdapter in android

This is my first time creating android app. and what i want to create now is to make a list and when a user click a name in the list the detail of the click name will show. I am trying to create simple cursor adapter. But an error occur
The constructor SimpleCursorAdapter(QuestionsNew, int, Cursor, String[], int[]) is undefined.
What do you think is the possible reason for this. Below is some part of my code
package tk.wew.wew;
import info.androidhive.sqlite.model.LocalStorage;
import info.androidhive.sqlite.model.Message;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import static tk.askd.askd.CommonUtilities.*;
public class QuestionsNew extends Fragment {
Cursor cursor;
ListView nameList;
protected ListAdapter adapter;
// TextView tvCompany = (TextView)
// findViewById(R.id.tvContactListCompany);
private static final String TAG = "Question";
private ListView list;
private static List questions;
ArrayList<String> senders = new ArrayList<String>();
ArrayList<String> shortMsg = new ArrayList<String>();
ArrayList<Integer> imageId = new ArrayList<Integer>();
SimpleCursorAdapter myCursorAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
//CommonUtilities.sendAQuestion(getActivity(), "msg123Kjjj11", "richmund_10023", "lofrancs1231", "Apil ka?");
questions = CommonUtilities.getAllQuestions(getActivity(), "N", null);
if(questions.size() > 0){
view = inflater.inflate(R.layout.questions_main_layout, container, false);
AskdDatabaseHelper msg_db = new AskdDatabaseHelper(getActivity());
List<Message> messages = msg_db.getAllQuestions("N", "lofrancs1231");
Cursor cursor = msg_db.getAllQuestions3();
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { "KEY_MSG_MESSAGE_ID","KEY_MSG_MESSAGE" };
int[] toViewIDs = new int[] { R.id.KEY_MSG_MESSAGE_ID, R.id.KEY_MSG_MESSAGE_ID };
/* SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.message_list_item, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);*/
myCursorAdapter = new SimpleCursorAdapter(QuestionsNew.this,
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
ListView contactList = (ListView) getView().findViewById(R.id.lvContacts);
contactList.setAdapter(myCursorAdapter);
for(int m=0; m<questions.size(); m++){
senders.add(messages.get(m).getFromUser());
shortMsg.add(messages.get(m).getMessage());
imageId.add(R.drawable.ic_launcher);
}
} else {
view = inflater.inflate(R.layout.fragments_question_new, container, false);
((TextView)view.findViewById(R.id.textView)).setText("No New Questions");
}
return view;
}
#Override
public void onStart(){
super.onStart();
Log.v(TAG, ": New onStart");
if(questions.size() > 0){
list = (ListView) getView().findViewById(R.id.list);
CustomLst adapter = new CustomLst(getActivity(), senders, imageId, shortMsg);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// Cursor listCursor = (Cursor) parent.getItemAtPosition(position);
// Cursor listCursor = (Cursor) parent.getAdapter().getItem(position);
// Log.d("TAG", (String) parent.getItemAtPosition(id));
Toast.makeText(getActivity(),
"Position:"+ parent.getItemIdAtPosition((int) id), Toast.LENGTH_LONG)
.show();
// int message = listCursor.getInt(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID));
/*
Intent intent = new Intent(getActivity(), QuestionDetail.class);
intent.putExtra("Message_ID", listCursor.getString(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID)));
startActivity(intent);
// ListView clicked item index
int Position = position;
// ListView clicked item value
String itemValue = (String) list.getItemAtPosition(Position);
// show alert
// Toast.makeText(getActivity(),
// "Position:" + Position + " Listitem:" + itemValue, Toast.LENGTH_LONG)
// .show();
*/
}
});
} else {
Log.e(TAG, "No new question");
}
}
}
Change your constructor as below
myCursorAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
The first param is a Context. This QuestionsNew.this is not a valid context. Fragment does not extend Context.
Activity
java.lang.Object
↳ android.content.Context // check this
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity // check this
Fragment
java.lang.Object
↳ android.app.Fragment // check this
So get context in fragment use getActivity()
public final Activity getActivity ()
Added in API level 11 Return the Activity this fragment is currently
associated with.
Also
SimpleCursorAdapter(Context context, int layout, Cursor c, String[]
from, int[] to) This constructor was deprecated in API level 11. This
option is discouraged, as it results in Cursor queries being performed
on the application's UI thread and thus can cause poor responsiveness
or even Application Not Responding errors. As an alternative, use
LoaderManager with a CursorLoader.
It is same when you use ArrayAdapter in Fragment class. The first param to the constructor of ArrayAdapter is a valid context. So even in that case you need to use getActivity() instead of FragmentName.this.

Android: Layout cannot be resolved or is not a field

I have this mainactivity:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
//Array of options --> ArrayAdapter --> ListView
//List view: {views: list_items.xml}
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateListView();
}
private void populateListView() {
//Create list of items
String[] myItems = {"Blue", "Green", "Purple", "Red"};
//Build Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this //Context for the activity
R.layout.list_items, //Layout to use (Create)
myItems); //Items to be displayed
//Configure the ListView
ListView list = (ListView) findViewById(R.id.listViewMain);
list.setAdapter(adapter);
ViewPager myViewPager = (ViewPager) findViewById(R.id.viewPager);
myViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
myViewPager.setCurrentItem(1, false);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 2: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 3;
}
{}}}
I am trying to add a listview, i have created a xml file called: list_items.xml, but on this line: "R.layout.list_items," i get an error: "layout cannot be resolved or is not a field" and i also get "syntax error on token "R", delete this token". Why is that?
The list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
I believe that you misunderstood the constructor for ArrayAdapter.
What you basically need to do is change the R.layout.list_items to a single element layout, just like one you would find in android.R.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
Here you can see that first parameter is context, second one is single item layout, third (optional) is the ID of the text view you want to target with your collection of strings and the last one is the collection.
You can use your own layouts just like you tried earlier.
If you have any questions I will be happy to answer them, and also supply some code if needed.
It look error in your xml.You can also use the simple list item if you need to display only myItems strings.
String[] myItems = {"Blue", "Green", "Purple", "Red"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myItems);

How to Call Activity using ListView [duplicate]

This question already has answers here:
How to Call Activity using ListView Array
(2 answers)
Closed 9 years ago.
Iam using Sherlock fragment to make a Action Bar. and I have ListView in action bar, but I will my listview can call activity .. Please help me Thanks.. :)
in this code have a listview using array list . and i want to mylist can call same activity.
So it can Like menu in action bar. and when we clik listview ..he can call activity
thank.. please help me !
Please correct my code ..how to call activity with each option in listview.. thanks..
AppleFragment.java
package iqbal.apps.visitkuningan;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockListFragment;
public class AppleFragment extends SherlockListFragment{
/** An array of items to display*/
String apple_versions[] = new String[]{
"Mountain Lion",
"Lion",
"Snow Leopard",
"Leopard",
"Tiger",
"Panther"
};
/** An array of images to display*/
int apple_images[] = new int[]{
R.drawable.mountainlion,
R.drawable.lion,
R.drawable.snowleopard,
R.drawable.leopard,
R.drawable.tiger,
R.drawable.panther
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<5;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", apple_versions[i]);
hm.put("img", Integer.toString(apple_images[i] ) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "img","txt" };
// Ids of views in listview_layout
int[] to = { R.id.img,R.id.txt};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listview = AppleFragment.this.getListView();
listview.setAdapter(adapter);
// Setting the adapter to the listView
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position,long id) {
// ?? please add code in here to call activity from each option in listview.. T_T or correct my code
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Edit the setOnItemClickListener and insert a condition which checks for position of the item and starts and activity depending on the item clicked.
Should look something like this
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,View arg1, int position, long arg3) {
Intent n = null;
switch (position){
case 0:
n = new Intent(getActivity(), Class0.class);
break;
case 1:
n = new Intent(getActivity(), Class1.class);
break;
}
if(null!=n)
startActivity(n);
}
});

Categories