Android: Layout cannot be resolved or is not a field - java

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

Related

Setting ListView

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

Put the cardview inside the fragment

I made a tab menu using several fragments. And I'm going to put a cardview in each of the Fragment.
I tried Googling, but all I had to do was put a cardview in activity.
I'd like to put a cardview in the Fragment, and then I'd like to implement initiation of a predefined set activity when I click on the card.
How can I do?
I referred to https://www.codingdemos.com/android-tablayout-example-viewpager to tab menu.
I attach my fragment layout(xml file) code
<FrameLayout 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"
tools:context="com.aeyoung.csw.CommunityFragment">
<!-- TODO: Update blank fragment layout -->
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.aeyoung.csw.CommunityFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
</FrameLayout>
Also I add fragment code(java file)
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class CommunityFragment extends AppCompatActivity {
//Create parameter
List<Product> productList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_community);
// initialize parameter "productList"
setInitialData();
//Find RecyclerView from fragment_community.xml
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
// Create LinearLayoutManager and set it to RecyclerView
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
//Create MyAdapter object with the parameters and set to RecyclerView
MyAdapter myAdapter = new MyAdapter(this, productList);
recyclerView.setAdapter(myAdapter);
}
private void setInitialData() {
productList.add(new Product("text1", "text1", R.mipmap.ic_launcher));
productList.add(new Product("text2", "text2", R.mipmap.ic_launcher));
productList.add(new Product("text3", "text3", R.mipmap.ic_launcher));
productList.add(new Product("text4", "text4", R.mipmap.ic_launcher));
productList.add(new Product("text5", "text5", R.mipmap.ic_launcher));
productList.add(new Product("text6", "text6", R.mipmap.ic_launcher));
productList.add(new Product("text7", "text7", R.mipmap.ic_launcher));
productList.add(new Product("text8", "text8", R.mipmap.ic_launcher));
productList.add(new Product("text9", "text9", R.mipmap.ic_launcher));
productList.add(new Product("text10", "text10", R.mipmap.ic_launcher));
}
}
PageAdapter.java code
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by abdalla on 2/18/18.
*/
public class PageAdapter extends FragmentPagerAdapter {
private int numOfTabs;
PageAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MajorFragment();
case 1:
return new FresherFragment();
case 2:
return new CommunityFragment();
case 3:
return new SettingsFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
And the following error occurs when building.
"error: incompatible types: CommunityFragment cannot be converted to Fragment"
as the error is telling you "error: incompatible types: CommunityFragment cannot be converted to Fragment"
you CommunityFragment extends AppCompatActivity and it's not a fragment.

ArrayAdapter in an onClickListner is not working

What I am trying to do here is to display a list of strings using ArrayList<String> and ArrayAdapter<String> when a user clicks a button. I want to declare all the members i.e. adapter, ArrayList and the list layout as global because I want to add more buttons later with the same feature of displaying a list of strings.
This code has no error but it's not working. I put the Toast in the onClick to make sure the onClick is working. I can see the toast but not the listView I want to see.
class file
R.id.button_news is the button id. R.layout.activity_primary_content is the layout that I'm using in this class PrimaryContent
R.layout.list_view_secondary is the layout where the listView R.id.list_view is located.
R.layout.list_view_secondary layout and the PrimaryContent class are not related but I want to use the listView which is in the list_view_secondary layout to display from the PrimaryContent.
In this line of code
arrayAdapter = new ArrayAdapter<>(view.getContext(),android.R.layout.simple_list_item_1,list); I tried by put the context view.getContext() and getBaseContext() both of them are not working.
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class PrimaryContent extends AppCompatActivity {
private final String LOG_TAG = PrimaryContent.class.getSimpleName();
public ListView listView;
public ArrayList<String> arrayList;
public ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary_content);
final LayoutInflater factory = getLayoutInflater();
final View rootView = factory.inflate(R.layout.list_view_secondary, null);
listView = rootView.findViewById(R.id.list_view);
arrayList = new ArrayList<>();
for (int i=0; i<20; i++) {
arrayList.add("World News");
}
Button news = findViewById(R.id.button_news);
news.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getBaseContext(),"Damn",Toast.LENGTH_SHORT).show();
for (String x: arrayList) {
Log.v(LOG_TAG,x);
System.out.println();
}
arrayAdapter = new ArrayAdapter<>(view.getContext(),android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
}
});
}
}
R.layout.list_view_secondary
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true"
android:orientation="vertical" />
You forgot to add the inflated layout to your parent layout, for example:
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.parent_layout);
parentLayout.addView(rootView);

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>

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