ListView in Fragment doesn't show anything - java

I know that this question has been asked a lot of times already but I have went to all of the answers and none of them worked for me.
So, issue with the App is that I am trying to populate an ArrayList into a ListView using an ArrayAdapter and the app MainActivity doesn't show anything but white screen when launched.
Here's
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static class PlaceholderFragment extends Fragment{
private ArrayAdapter<String> mForecastAdapter;
public PlaceholderFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
//Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/46",
"Weds - Cloudy - 72/63",
"Thurs - Rainy - 64/51",
"Fri - Foggy - 70/46",
"Sat - Sunny - 76/68"
};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
mForecastAdapter = new ArrayAdapter<String>(
//The current context (current activity)
getActivity(),
//ID of list item layout
R.layout.list_item_forecast,
//id of the textView to populate
R.id.list_item_forecast_textview,
//data to populate
weekForecast
);
return rootView;
}
}
fragment_main.xml
<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"
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="com.gautamhans.sunshine.app.MainActivityFragment"
tools:showIn="#layout/activity_main">
<ListView
android:id="#+id/listview_forecast"
android:layout_width="match_parent"
android:layout_height="667dp"
/>
</FrameLayout>
Here's list_item_forecast.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="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:id="#+id/list_item_forecast_textview"
>
</TextView>

Of course the activity is not showing anything, you're not placing the fragment inside your activity! Use this in your activity's onCreate():
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new PlaceholderFragment(), "fragment_tag").commit();
Where R.id.container is a layout inside your main_activity_layout file (empty layout)
UPDATE:
have these 2 file:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
fragment_main:
<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"
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="com.gautamhans.sunshine.app.MainActivityFragment"
tools:showIn="#layout/activity_main">
<ListView
android:id="#+id/listview_forecast"
android:layout_width="match_parent"
android:layout_height="667dp"
/>
</FrameLayout>
keep the 3° layout file, it's ok.
Now, in your activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new PlaceholderFragment(), "fragment_tag").commit();
}
also:
mForecastAdapter = new ArrayAdapter<String>(
//The current context (current activity)
getActivity(),
//ID of list item layout
R.layout.list_item_forecast,
//id of the textView to populate
R.id.list_item_forecast_textview,
//data to populate
weekForecast
);
//move this after the initialization of adapter
listView.setAdapter(mForecastAdapter);

When you set the ListView adapter,the adapter's reference is null and you set the null adapter for ListView.You should create the adapter before set ListView adapter.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
mForecastAdapter = new ArrayAdapter<String>(
//The current context (current activity)
getActivity(),
//ID of list item layout
R.layout.list_item_forecast,
//id of the textView to populate
R.id.list_item_forecast_textview,
//data to populate
weekForecast
);
listView.setAdapter(mForecastAdapter);

Is your PlaceHolderFragment within your MainActivity.java file?
If so, try separating it on its own file PlaceHolderFragment.java..
As far as I know, java only allows one public class per source file.. That maybe the reason of your problem..

Related

Android: java.lang.ClassCastException [duplicate]

I am getting an error when trying to set my view to display the ListView for the file I want to display(text file). I am pretty sure it has something to do with the XML. I just want to display the information from this.file = fileop.ReadFileAsList("Installed_packages.txt");. My code:
public class Main extends Activity {
private TextView tv;
private FileOperations fileop;
private String[] file;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.fileop = new FileOperations();
this.file = fileop.ReadFileAsList("Installed_packages.txt");
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
ListView lv = new ListView(this);
lv.setTextFilterEnabled(true);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
setContentView(lv);
}
}
list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#000">
</LinearLayout>
main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<ScrollView
android:id="#+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fillViewport="true">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5sp"
android:id="#+id/TextView01"
android:text="#string/hello"/>
</ScrollView>
</LinearLayout>
The ArrayAdapter requires the resource ID to be a TextView XML exception means you don't supply what the ArrayAdapter expects. When you use this constructor:
new ArrayAdapter<String>(this, R.layout.a_layout_file, this.file)
R.Layout.a_layout_file must be the id of a xml layout file containing only a TextView(the TextView can't be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
// other attributes of the TextView
/>
If you want your list row layout to be something a little different then a simple TextView widget use this constructor:
new ArrayAdapter<String>(this, R.layout.a_layout_file,
R.id.the_id_of_a_textview_from_the_layout, this.file)
where you supply the id of a layout that can contain various views, but also must contain a TextView with and id(the third parameter) that you pass to your ArrayAdapter so it can know where to put the Strings in the row layout.
Soution is here
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
</LinearLayout>
Java code :
String[] countryArray = {"India", "Pakistan", "USA", "UK"};
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listitem,R.id.textview, countryArray);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
If you are getting that message when you are extending an ArrayAdapter, you are getting that error because you have not provided the correct resource id to display the item. Call the super class in the constructor and pass in the resource id of the TextView:
//Pass in the resource id: R.id.text_view
SpinnerAdapter spinnerAddToListAdapter = new SpinnerAdapter(MyActivity.this,
R.id.text_view,
new ArrayList<>());
Adapter:
public class SpinnerAdapter extends ArrayAdapter<MyEntity> {
private Context context;
private List<MyEntity> values;
public SpinnerAdapter(Context context, int textViewResourceId,
List<MyEntity> values) {
//Pass in the resource id: R.id.text_view
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
The problem is in the line:
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));
Because when i change it to:
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.file));
It works!

Design spinner programmatically (android)

I need create spinner programmatically. I add spinner to linearLayout, its work but I don't know how chache designe it.
Example, I have this:
How remove it?(highlighted in red)
And how remove spinner text to center?
My xml
LinearLayout spinnerL add this my spinner
<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=".MainActivity">
<LinearLayout
android:id="#+id/spinnerL"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
/>
</RelativeLayout>
and main class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array of choices
View linearLayout = findViewById(R.id.spinnerL);
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
Spinner spinner = new Spinner(this);
//Make sure you have valid layout parameters.
spinner.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item, list);
spinner.setAdapter(spinnerArrayAdapter);
((LinearLayout) linearLayout).addView(spinner );
}
To remove small triangle, simplest method is to set background drawable, for example:
spinner.setBackgroundResource(android.R.drawable.btn_default);
To align text center, you need to create layout for spinner, see examples

How to display the listview content in xml file in android

I have 2 xml file
MainActivity.xml
2.Example.xml
I have listview in Example.xml.the code I have written in Example.java. But the data is not displaying in listview..Kindly go through my code
Example.xml
<?xml version="1.0" encoding="utf-8"?>
<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/profileSwitcher"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listPasscode"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"/>
</LinearLayout>
</ViewSwitcher>
Example.java
public class ListViewAndroidExample extends Activity {
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) findViewById(R.id.listPasscode);
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
// Array of strings...
String[] countryArray = {"India", "Pakistan", "USA", "UK"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, countryArray);
// Assign adapter to ListView
listView.setAdapter(adapter);
setContentView(R.layout.activity_list_view_android_example);
}
}
Is linking between xml and java file right ?If not suggest me
Try this..
Add setContentView before initializing the ListView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
listView = (ListView) findViewById(R.id.listPasscode);
EDIT
Change this..
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, countryArray);
to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countryArray);

Fragment Not Displaying In Activity

Currently when running my application, going to this activity does not display my fragment. Am I adding the fragment wrong and so nothing in the fragment is displayed? Or is there something wrong the dynamic behavior in the fragment onCreateView method?
My Activity Code
public class AskQuestionActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ask_question);
}
}
My Activity XML
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/header_text"/>
<fragment android:name="com.mypackage.AskQuestionFragment"
android:id="#+id/question_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
My Fragment Code
public class AskQuestionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String questionText = "What is your favorite color?";
List<String> answers = Arrays.asList("Red", "Blue", "Yellow");
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.question, container);
Resources res = getResources();
int id = res.getIdentifier("question_text", "id", layout.getContext().getPackageName());
TextView questionTextView = (TextView)layout.findViewById(id);
questionTextView.setText(questionText);
id = res.getIdentifier("question_answers", "id", layout.getContext().getPackageName());
RadioGroup radioGroup = (RadioGroup)layout.findViewById(id);
Collections.reverse(answers);
for (String s : answers) {
RadioButton button = new RadioButton(layout.getContext());
button.setText(s);
radioGroup.addView(button, 0);
}
return layout;
}
}
My Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/question_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/question_text"/>
<RadioGroup android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/question_answers"></RadioGroup>
<Button
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit_button_text"
/>
</LinearLayout>
try to put framelayout instead of fragment in xml. and in your activity's onCreate create the instance of your fragment you want to display and add it to the fragment container
public class AskQuestionActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ask_question);
AskQuestionFragment fragment = new AskQuestionFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.id_of_your_container, fragment).commit();
}
}
Your problem might be when doing this:
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.question, container);
Consider to replace that line with one of the following:
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.question, null);
or
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.question, container, false);
change your layout from linear to be framelayout, and attach your fragment in activity .
getSupportFragmentManager().beginTransaction()
.add(R.id.your_fragment_container, fragment).commit();

Using a DrawerLayout along with a ListView

I'm trying to write an android app with a listview of a few different items and also a drawerlayout that you can drag from the left side of the screen. Here's what i mean....
This is what the main screen looks like:
And here's what the drawer menu thing looks like:
The problem i'm having is that when I open the side drawer menu thing and tap an option it doesn't work and the menu just closes. However i'm able to interact with the main listview page. Here's what my code looks like:
String[] homeArray = { "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test", "Test" };
private ListView homeListView;
private ArrayAdapter arrayAdapter;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerTitles = getResources().getStringArray(R.array.Menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mDrawerTitles));
And the activity_main.xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<FrameLayout
android:id="#+id/content_frame"
android:layout_height="match_parent"
android:layout_width="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_height="match_parent"
android:layout_width="240dp"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/darker_gray"
android:dividerHeight="1dp"
android:background="#111"
/>
<LinearLayout 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:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="#+id/homeListView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
I have a feeling the problem is in the xml but i'm not sure.
Please post the full code of your Activity that holds the NavigationDrawer.
Furthermore, I would strongly recommend (and so would Google) that you use Fragments for the individual NavigationDrawer sections ("Settings", "Submit Bug" and "Help" in your case).
Do not put all the layout components into the layout file of your Activity.
The layout therefore should look like the following:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
The FrameLayout content_frame is where your Fragment that holds the ListView will go into.
Simply create a custom Fragment (or use a ListFragment) that contains the ListView you displayed in your picture and insert it into the "content_frame".
Use this to replace Fragments inside the content frame: (when you switch your section)
/** Swaps fragments in the main content view */
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Fragment fragment = new YourListFragment(); // this fragment contains the list with all the "test" items
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
An Example of how your Fragment could look like: YourListFragment.java
The layout file "list_fragment.xml" simply contains whatever layout components you want. For example a ListView. Initialize an populate the ListView inside the Fragments onCreateView() method.
public class YourListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_fragment, container, false);
return rootView;
}
}
All taken from Googles example on how to create a NavigationDrawer:
http://developer.android.com/training/implementing-navigation/nav-drawer.html

Categories