I am trying to display a listview of items at the launch of my application.But at the launch of the application no listview is displayed but only a blank screen.Below are the codes:
MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static class PlaceholderFragment extends Fragment
{
ArrayAdapter<String> mForecastAdapter;
public PlaceholderFragment()
{}
#Override
public View onCreateView(LayoutInflater inflator, ViewGroup v, Bundle savedInstanceState)
{
View rootView = inflator.inflate(R.layout.fragment_main, v);
String[] forecastArray= {
"Today - Sunny - 88/63",
"Monday - foggy - 67/20",
"Tuesday - Sunny - 88/63"
};
List<String> weekforecast= new ArrayList<String>(Arrays.asList(forecastArray));
mForecastAdapter= new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekforecast);
ListView listview =(ListView)rootView.findViewById(R.id.listview_forecast);
listview.setAdapter(mForecastAdapter);
return rootView;
}
}
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sunshineapp.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="64dp"
android:paddingRight="64dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context="com.example.sunshineapp.MainActivity$PlaceholderFragment" >
<ListView
android:id="#+id/listview_forecast"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
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="match_parent"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:id="#+id/list_item_forecast_textview"/>
Can Someone please guide me with the issue? Thanks in advance!
Edit:
As suggested by #Sanjeet I had forgotten to attach the fragment to the activity.So I attached it as follows in the onCreate method of activity:
if(savedInstanceState == null)
{
android.app.FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, new PlaceholderFragment());
fragmentTransaction.commit();
}
But now I am getting the following in the logcat:
08-03 11:55:37.365: E/AndroidRuntime(20088): FATAL EXCEPTION: main
08-03 11:55:37.365: E/AndroidRuntime(20088): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sunshineapp/com.example.sunshineapp.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
08-03 11:55:37.365: E/AndroidRuntime(20088): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
08-03 11:55:37.365: E/AndroidRuntime(20088): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
08-03 11:55:37.365: E/AndroidRuntime(20088): at android.app.ActivityThread.access$600 (ActivityThread.java:162)
And the application stops..Please help!
You should use
View rootView = inflator.inflate(R.layout.fragment_main, v,false);
instead of
View rootView = inflator.inflate(R.layout.fragment_main, v);
To me somehow helped to update the adapter simply:
ListView listview =(ListView)rootView.findViewById(R.id.listview_forecast);
listview.setAdapter(mForecastAdapter);
mForecastAdapter.notifyDataSetChanged();
return rootView;
it seems to me that your mForecastAdapter array is empty. try to add some values inside for testing first.
Try changing
List<String> weekforecast= new ArrayList<String (Arrays.asList(forecastArray));
to
ArrayList<String> weekforecast= new ArrayList<String>(Arrays.asList(forecastArray));
Try changing
View rootView = inflator.inflate(R.layout.fragment_main, v);
to
View rootView = inflator.inflate(R.layout.fragment_main, v,false);
For more info about false in last parameter. You should check this answer.
Hope this helps.
Related
I am new to android and have been following udacity's video lectures.
The list view is not getting populated by the array adapter and when
i ran the app on mobile the app showed only the main activity layout.
the list view is not appearing on the mobile screen ,can anyone tell me whats the error here,is it something related to frame layout or is there an
error in
array adapter.
Thanks in advance
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","Tommorow","wed","Thursday","Friday","Saturday","Sunday"
};//creating some fake data to show in list view
List<String> fore=new ArrayList<String>(Arrays.asList(forecastArray));
mForecastAdapter=new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,fore);
ListView listview= (ListView)rootview.findViewById(R.id.listview_forecast);
listview.setAdapter(mForecastAdapter);
return rootview;
}
}
}
activity_main_xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:id="#+id/container"
tools:context="com.saxenarc.jeetesh.layouts.MainActivity">
</FrameLayout>
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:id="#+id/list_item_forecast_textview"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
>
</TextView>
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listview_forecast"></ListView>
</FrameLayout>
Checked everything thrice before posting it.
Your code and list is working well but you haven't told the list where to be displayed. You can fix this in 2 ways.
First
Add the fragment inside the main activity since its not visible.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager.beginTransaction().replace(R.id.container, new PlaceHolderFragment).commit();
}
Second
Stop using the fragment and use the listview inside the Main activity
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listview_forecast"></ListView>
</FrameLayout>
MainActivity.java
List<String> fore = new ArrayList<String>(Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<String>(this,R.layout.list_item_forecast,R.id.list_item_forecast_textview,fore);
ListView listview= (ListView) findViewById(R.id.listview_forecast);
listview.setAdapter(mForecastAdapter);
I'm really confused on what I've done with my code.
It's just a simple app using Fragments but I get below error :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sgrumo.sunshineonyourmind/com.example.sgrumo.sunshineonyourmind.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
This is my MainActivity class :
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState==null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MainActivityFragment()).commit();
}
}
Activity-main XML :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="#+id/container"
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:ignore="MergeRootFrame"
tools:context="com.example.sgrumo.sunshineonyourmind.MainActivity">
I just wanted a Fragment inside my activity main, what's wrong with my code?
This is the Fragment class i use :
public class MainActivityFragment extends Fragment {
public MainActivityFragment() {}
String[] forecastArray = {
"Today - Sunny - 31/20",
"Tomorrow - Sunny - 42,30",
"Wednesday - Rainy - 20,15",
"Thursday - FINIMONDO - 35,20"
};
ArrayList<String> list = new ArrayList<>(Arrays.asList(forecastArray));
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,list);
ListView lw = (ListView)rootView.findViewById(R.id.listview_forecast);
lw.setAdapter(adapter);
return rootView;
}
And its 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.example.sgrumo.sunshineonyourmind.MainActivityFragment"
tools:showIn="#layout/activity_main">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listview_forecast"
android:layout_gravity="center" />
Please change the code as following in your onCreateView method
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
You missed to add false. Thanks.
Use getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new MainActivityFragment()).commit() instead of getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MainActivityFragment()).commit()
I'm trying to follow the Udacity Developing Android Apps course. I got to Lesson 3.03. Here, we are instructed to launch a new Activity (DetailActivity) from ForecastFragment when clicking an item in a list.
However, I keep getting an error when attempting to launch the DetailActivity. Binary XML file line #1: Error inflating class fragment, where it's caused by DetailActivity.java in it's onCreate() method.
I've already searched around, but none of the fixes suggested for this issue helped me at all.
The specific error is:
Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class
com.myapp.sunshine.app.DetailActivityFragment that is not a Fragment
DetailActivity.java
public class DetailActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail); //failing here
}
}
DetailActivityFragment.java
public class DetailActivityFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
activity_detail.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/fragment"
android:name="com.myapp.sunshine.app.DetailActivityFragment"
tools:layout="#layout/fragment_detail" android:layout_width="match_parent"
android:layout_height="match_parent" />
I should mention that I'm not using support libraries--as I'm targeting SDK 21+, Lollipop only.
This isn't the only fragment we've created in the course either. The other fragment we created looks identical to this one.
activity_main.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/fragment"
android:name="com.myapp.sunshine.app.ForecastFragment"
tools:layout="#layout/fragment_main" android:layout_width="match_parent"
android:layout_height="match_parent" />
And for good measure, I'm including the ForecastFragment class. I've omitted unnecessary parts of code.
ForecastFragment.java
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForecaseAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 74/58",
"Sunday - Rainy - 65/59",
"Monday - Cloudy - 72/67"
};
final List<String> weekForecast = new ArrayList<>(Arrays.asList(forecastArray));
mForecaseAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecaseAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String forecast = mForecaseAdapter.getItem(position);
Intent detailActivityIntent = new Intent(getActivity(), DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT, forecast);
startActivity(detailActivityIntent);
}
});
return rootView;
}
}
fragment_detail.xml
<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=".DetailActivityFragment">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
which is nearly identical to
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: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=".MainActivityFragment">
<ListView
android:id="#+id/listview_forecast"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
</FrameLayout>
You should be using FragmentActivity instead of Activity
public class DetailActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail); //failing here
}
}
First off; I would like to apologize for the lengthy question. I though this was the only way to get across what I am trying to do. Anyway. I have an app that user a navigation drawer that will offer a user 3 choices. I want Test1Fragment to be a listview. I can not seem to figure out how to make this happen. Please help.
MainActivity method that controls which fragment is loaded based on the selection:
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Test1Fragment();
break;
case 1:
fragment = new Test2Fragment();
break;
case 2:
fragment = new Test3Fragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
Test1Fragment:
public class Test1Fragment extends Fragment {
public Test1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_create, container, false);
return rootView;
}
fragment_create.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!--<TextView-->
<!--android:id="#+id/txtLabel"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_centerInParent="true"-->
<!--android:text="Create View"-->
<!--android:textSize="16dp" />-->
<!--<ImageView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_below="#id/txtLabel"-->
<!--android:layout_centerHorizontal="true"-->
<!--android:layout_marginTop="10dp"-->
<!--android:src="#drawable/ic_action_copy" />-->
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I understand that I am missing code for the listview, but this is all I want int the xml view.
Thank you
In your current implementation, your layout code should look in example like that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/layout_fragment_listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
Then in your class, you must fill listview with data. You have to create adapter and attach data to this adapter. Then adapter must be passed to listview.
Quick example :
public class Test1Fragment extends Fragment {
//No need for empty constructor, it is made by default
//public Test1Fragment() {
//}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_create, container, false);
ListView listView =(ListView)rootView.findViewById(R.id.layout_fragment_listView);
String[] items = { "Milk", "Cheese", "Cucumber", "Toilet", "Duck" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
return rootView;
}
This way you will have filled listview with strings from array items.
This is very basic example, you can extend also base adapter, and populate it with your own objects and views.
Here is screenshot with result :
I could manage to create a TabAdapter with pager (swiping tabs), which implements a ListFragment for each. Then I called my items through the strings. This works just fine.
But the ListView here implements plain text.
My question: how can implement a custom ListView with custom Rows (Text and image)?
Here is my code:
.MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pager = new ViewPager(this);
pager.setId(R.id.pager);
setContentView(pager);
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, pager);
mTabsAdapter.addTab(bar.newTab().setText("Grundlagen"), ListViewTabGrundlagen.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Anästhesie"), ListViewTabAnaesthesie.class, null);
}
ListViewTabGrundlagen
public class ListViewTabGrundlagen extends ListFragment {
String[] list_items;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
list_items = getResources().getStringArray(R.array.listGrundlagen);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list_items));
return rootView;
}
}
list.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
activity_main.xml
<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"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager" />
</RelativeLayout>
Any workaround?
Thank you very much!
You need to look for the custom adapters, You can start by extending the BaseAdaper or ArrayAdapter and Overriding the proper methods in the classes.