This question already has answers here:
Your content must have a ListView whose id attribute is 'android.R.id.list'
(7 answers)
Closed 7 years ago.
here is the EditFriends activity..........................................
package com.josephvarkey996gmail.test1;
import android.app.ListActivity;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ArrayAdapter;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.List;
public class Editfriends extends ListActivity {
public static final String Tag=Editfriends.class.getSimpleName();
protected List<ParseUser> mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_editfriends);
}
#Override
protected void onResume() {
super.onResume();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query= ParseUser.getQuery();
query.orderByAscending(ParseConstants.key_Username);
query.setLimit(1000);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
setProgressBarIndeterminateVisibility(true);
if (e== null){
mUser=users;
String[] username = new String[mUser.size()];
int i=0;
for(ParseUser user:mUser){
username[i]=user.getUsername();
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(Editfriends.this,android.R.layout.simple_list_item_checked,username);
setListAdapter(adapter);
}
else
{
Log.e(Tag,e.getMessage());
AlertDialog.Builder builder=new AlertDialog.Builder(Editfriends.this);
builder.setMessage(e.getMessage()).setTitle(R.string.error_title).setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_editfriends, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
here is the xml of Editfriends ............................................
<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="com.josephvarkey996gmail.test1.Editfriends">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
im learning ,so cant understand the eror. here is the logcat..............................
07-21 19:42:05.397 9188-9188/com.josephvarkey996gmail.test1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.josephvarkey996gmail.test1, PID: 9188
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.josephvarkey996gmail.test1/com.josephvarkey996gmail.test1.Editfriends}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
at android.app.ListActivity.onContentChanged(ListActivity.java:243)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:382)
at android.app.Activity.setContentView(Activity.java:2145)
at com.josephvarkey996gmail.test1.Editfriends.onCreate(Editfriends.java:27)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Your main activity class is extending a ListActivity. This means that your xml file needs a ListView.
Try adding something like this to your XML:
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
More information can be found at http://developer.android.com/reference/android/app/ListActivity.html.
As the documentation states:
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "#android:id/list
Your activtiy extends ListActivity. So as the crash logs say :
Your content must have a ListView whose id attribute is 'android.R.id.list'
This mean that in your xml file you should have a ListView with the attribute android:id:"android.R.id.list.
This is because ListActivity expect to find a ListView in is content view.
You are using a ListActivity, which is a bit different than a normal Activity.
If you do nothing, then your ListActivity will have a single View in it, which is a ListView.
If you call setContentView() to supply your own layout (perhaps you want to display more than just a ListView), then your layout must contain a ListView and that ListView must have an id of #android:id/list.
Since you are providing a custom layout that consists of a RelativeLayout with a single TextView, your layout does not pass this requirement. Since it looks like you just have placeholder content there, I would remove the layout and remove the call to setContentView().
The exception you posted from your logcat mentions this:
Your content must have a ListView whose id attribute is 'android.R.id.list'
Related
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
/**
* Created by name on 3/13/17.
* Used for the specials tab to allow a list of days to choose what special one would like to view
*/
public class SpecialsScroll extends ListFragment implements AdapterView.OnItemClickListener{
public SpecialsScroll(){
//Empty Constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.fragment_specials_scroll, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(ArrayAdapter.createFromResource(getActivity(), R.array.days, android.R.layout.simple_list_item_1)); //Loads array into the ListFragment
getListView().setOnItemClickListener(this); //activates the listener for this Fragment class
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){ // For checking when a user taps on an option
SpecialsPage specialsPage = new SpecialsPage();
Bundle foodArgs = new Bundle();
switch (position){ // checks what option is chosen and sends respective keys as parameters
case 0:
int[] keysMonday = {R.string.boom_boom_enchiladas_key, R.string.tacos_mexican_key};
foodArgs.putIntArray("keys", keysMonday);
break;
case 1:
int[] keysTuesday = {R.string.shrimp_avocado_tacos_key, R.string.green_chile_chicken_enchiladas_key};
foodArgs.putIntArray("keys", keysTuesday);
break;
}
specialsPage.setArguments(foodArgs);
getActivity().getFragmentManager().beginTransaction().replace(R.id.container, specialsPage).addToBackStack(null).commit();
}
}
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity{
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if(getFragmentManager().findFragmentByTag("CURRENT") == null){
getFragmentManager().beginTransaction().add(R.id.container, new SpecialsScroll(), "CURRENT").commit();
}
switch (item.getItemId()) {
case R.id.special:
getFragmentManager().beginTransaction().replace(R.id.container, new SpecialsScroll(), "CURRENT").commit();
return true;
case R.id.locations:
getFragmentManager().beginTransaction().replace(R.id.container, new LocationsScroll(), "CURRENT").commit();
return true;
case R.id.order:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getFragmentManager().beginTransaction().add(R.id.container, new SpecialsScroll(), "CURRENT").commit();
}
}
So, I am trying to create a ListView and everything in the code works, but suddenly I am unable to get the xml to recognize the android:id/list attribute for some reason, I don't know why. When I click on an item in the listview in my app it still does what it should, I just really want to get rid of the error.
<?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"
android:background="#color/white">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<TextView
android:id="#+id/text_specialsscroll"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
04-26 14:06:30.299 2576-2576
/com.namename.www.name
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.namename.www.name, PID: 2576
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.namename.www.name/com.namename.www.name.MainActivity}: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class
at android.app.ListFragment.ensureList(ListFragment.java:402)
at android.app.ListFragment.onViewCreated(ListFragment.java:203)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1010)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentController.execPendingActions(FragmentController.java:371)
at android.app.Activity.performStart(Activity.java:6695)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Change your id to this:
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
I found the following Android sample app to create a scrollview with checkbox and buttons, everything work great except when I switch or rotate to landscape mode, it crashes with:
Caused by: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.widget.CompoundButton$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/0x0. Make sure other views do not use the same id.
Does rotating the app caused it use the same ids in the for statement?
can I release the setid (if that is the problem before reassigning)
And how could I save the state of checkbox when I rotate?
Sample Code:
package life.poa.webcastman.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
public class MainActivity extends Activity {
ScrollView scrollview;
Button dynamicbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE); //AppCompActivity on public class
setContentView(R.layout.activity_main);
scrollview = new ScrollView(this);
LinearLayout linearlayout = new LinearLayout(this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
scrollview.addView(linearlayout);
ImageView imagetop = new ImageView(this);
imagetop.setBackgroundResource(R.mipmap.ic_launcher );
imagetop.setMaxHeight(50);
imagetop.setMaxWidth(50);
linearlayout.addView(imagetop);
for(int i = 0; i<25;i++)
{
LinearLayout linear1 = new LinearLayout(this);
linear1.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linear1);
ImageView image = new ImageView(this);
image.setBackgroundResource(R.mipmap.ic_launcher );
image.setMaxHeight(50);
image.setMaxWidth(50);
linear1.addView(image);
dynamicbtn = new Button(this);
dynamicbtn.setText("Button no... "+i);
dynamicbtn.setId(i);
dynamicbtn.setTextSize(10);
dynamicbtn.setPadding(8, 3, 8, 3);
dynamicbtn.setTypeface(Typeface.SERIF,Typeface.BOLD_ITALIC);
dynamicbtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
linear1.addView(dynamicbtn);
dynamicbtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Yipee.."+ v.getId(), Toast.LENGTH_SHORT).show();
}
});
CheckBox dynamicchk = new CheckBox(this);
dynamicchk.setId(i);
dynamicchk.setText("Wow..A checkbox" + i);
linear1.addView(dynamicchk);
dynamicchk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1)
{
Toast.makeText(getApplicationContext(), "Checked.."+ arg0.getId() + " " + arg1, Toast.LENGTH_SHORT).show();
}
});
}
this.setContentView(scrollview);
}
}
Abend:
09-04 18:59:04.631 2854-2854/life.poa.webcastman.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: life.poa.webcastman.myapplication, PID: 2854
java.lang.RuntimeException: Unable to start activity ComponentInfo{life.poa.webcastman.myapplication/life.poa.webcastman.myapplication.MainActivity}: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.widget.CompoundButton$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/0x0. Make sure other views do not use the same id.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.widget.CompoundButton$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/0x0. Make sure other views do not use the same id.
at android.view.View.onRestoreInstanceState(View.java:13764)
at android.widget.TextView.onRestoreInstanceState(TextView.java:3781)
at android.view.View.dispatchRestoreInstanceState(View.java:13740)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2893)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2893)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2893)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2893)
at android.view.View.restoreHierarchyState(View.java:13718)
at com.android.internal.policy.impl.PhoneWindow.restoreHierarchyState(PhoneWindow.java:2009)
at android.app.Activity.onRestoreInstanceState(Activity.java:1023)
at android.app.Activity.performRestoreInstanceState(Activity.java:978)
at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1162)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You don't need to set ID. If You want to assign some ID to the view you could achive this by using view.setTag(). And it will not affect any aspect of view hierarchy:
...
dynamicbtn.setTag(i);
...
dynamicbtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//You can cast it to `Integer` to get `ID` value
Toast.makeText(getApplicationContext(), "Yipee.."+ v.getTag(), Toast.LENGTH_SHORT).show();
}
});
...
dynamicchk.setTag(i);
...
dynamicchk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1)
{
//You can cast it to `Integer` to get `ID` value
Toast.makeText(getApplicationContext(), "Checked.."+ arg0.getTag() + " " + arg1, Toast.LENGTH_SHORT).show();
}
});
I am trying to link a Fragment, RecycleView and CardView using a variation of the tutorial found on:
http://www.treyrobinson.net/blog/android-l-tutorials-part-3-recyclerview-and-cardview/
Unfortunately my app crashes with the following error message:
"java.lang.IllegalStateException: RecyclerView has no LayoutManager"
I am fairly new with Android development. I tried to find similar issues on Stackoverflow but am unable to find the issue. Any help would be greatly appreciated!
Layout of the main activity: "activity_library.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=".LibraryActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/library_activity_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LibraryActivity"
/>
</RelativeLayout>
The main activity class "LibraryActivity.java":
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class LibraryActivity extends AppCompatActivity{
private static final String TAG = LibraryActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); /**Create the activity and populate the savedInstanceState if the activity existed but has been destroyed (otherwise savedInstanceState will return 'null'*/
setContentView(R.layout.activity_library); /** Call to the XML layout library which display the activity */
if (savedInstanceState != null) {
// Restore value of members from saved state
} else {
// Probably initialize members with default values for a new instance
}
try {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
BooksFragment bookFragment = new BooksFragment();
fragmentTransaction.add(R.id.library_activity_recycler_view,bookFragment);
/*The line below is the one generating the error - java.lang.IllegalStateException: RecyclerView has no LayoutManager*/
fragmentTransaction.commit();
}
catch(Exception e){
Log.d(TAG,"[ERROR] " + e.getMessage());
}
}
}
The layout of the fragment "fragment_books.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" >
<android.support.v7.widget.RecyclerView
android:id="#+id/Book_Recycler_View"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
And the fragment class:
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BooksFragment extends Fragment {
public BooksFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_library, container, false);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView bookRecycler = (RecyclerView) v.findViewById(R.id.library_activity_recycler_view);
bookRecycler.setLayoutManager(layoutManager);
BookRecyclerViewAdapter adapter = new BookRecyclerViewAdapter();
bookRecycler.setAdapter(adapter);
/*In the line below should we return the view 'v' or the RecyclerView 'bookRecycler'??*/
return bookRecycler;
}
}
As I said I am fairly new to Android and therefore apologies if my code contains quite a few errors. Thanks for your help!
For reference the complete error log:
04-18 14:04:52.323 11225-11225/com.wldtaster.tellmeastory E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wldtaster.tellmeastory, PID: 11225
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wldtaster.tellmeastory/com.wldtaster.tellmeastory.LibraryActivity}: java.lang.IllegalStateException: RecyclerView has no LayoutManager
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
at android.support.v7.widget.RecyclerView.generateLayoutParams(RecyclerView.java:3393)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at com.wldtaster.tellmeastory.BooksFragment.onCreateView(BooksFragment.java:23)
at android.app.Fragment.performCreateView(Fragment.java:2053)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.Activity.performStart(Activity.java:6005)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You must return the view ie. v in the onCreateView method of the Fragment inherited class.
I have two radio buttons and if one is selected I want to change the value of Textview. I am getting an error. The app stops working when I click one of my radio buttons. It is giving this error on log.
logged error
> /com.example.myapp.mttally E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapp.mttally, PID: 15125
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4025)
at android.view.View.performClick(View.java:4785)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:19884)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4020)
at android.view.View.performClick(View.java:4785)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:19884)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
`com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
..`
My java code on main file is this
package com.example.myapp.mttally;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
RadioButton lend;
RadioButton borrow;
TextView toFrom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView toFrom = (TextView) findViewById(R.id.toFrom);
RadioButton lend = (RadioButton) findViewById(R.id.lend);
RadioButton borrow = (RadioButton) findViewById(R.id.borrow);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
Boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.lend:
if (checked)
toFrom.setText(" To");
break;
case R.id.borrow:
if (checked)
toFrom.setText(" From");
break;
}
}
}
Here my xml file
<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:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="8dp"
android:id="#+id/linearLayout">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="false"
>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_button1"
android:id="#+id/lend"
android:textSize="16dp"
android:onClick="onRadioButtonClicked"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_button2"
android:id="#+id/borrow"
android:textSize="16dp"
android:onClick="onRadioButtonClicked"
/>
</RadioGroup>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="140dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/toFrom"
android:layout_below="#+id/linearLayout"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp" />
</RelativeLayout>
Every time you write something like TextView toFrom, RadioButton lend, or, more generally <type of variable> <variable name>, you're declaring a new variable. You declare variables called twoFrom, lend, and borrow in two places: once in the MainActivity class and once in the onCreate method. So, your code has two different variables that are both called toFrom, two variables called lend, and two variables called borrow.
Consider the lend variable. Each copy of the lend variable has its own "scope", or the area of code in which it exists. Since you declared the first lend variable in the class itself (not inside any of the methods), its scope is the class. You can (typically) use it in code anywhere in the class.
Your second lend variable, however, is what causes the problem. You've declared a second lend variable inside the onCreate method. That second lend is the one gets the TextView object...and then it ceases to exist once the onCreate method finishes executing.
So, to fix this, your onCreate should look like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toFrom = (TextView) findViewById(R.id.toFrom);
lend = (RadioButton) findViewById(R.id.lend);
borrow = (RadioButton) findViewById(R.id.borrow);
}
That way, when you get the reference to the TextView, you're holding it in the variable that will still exist when onRadioButtonClicked is called, not in a second identically-named variable that will cease to exist almost immediately.
I have problem with the adapter.add() method. It causes my app to crash.
My MainActivity is here:
package com.example.olev.shoppinglist;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
ArrayList<String>productNames=new ArrayList<String>();
ArrayAdapter<String> adapter;
public void addNewProduct(View view){
Intent i = new Intent(this,AddProduct.class);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addToList();
ListView productList=(ListView)findViewById(R.id.productList);
adapter = new CustomAdapter(this,productNames);
productList.setAdapter(adapter);
}
public void addToList(){
Bundle itemData=getIntent().getExtras();
if(itemData==null){
return ;
}
String product=itemData.getString("product");
productNames.add(product);
//adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
also my AddProduct:
package com.example.olev.shoppinglist;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class AddProduct extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
}
public void sendProductToMain(View view){
EditText productName= (EditText)findViewById(R.id.productName);
String product= productName.getText().toString();
Intent i = new Intent (this,MainActivity.class);
i.putExtra("product",product);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Other than that im using CustomAdapter which extends ArrayAdapter.
My problem is that if I run this code like it is, I can add item to listview, but as I try to add another one the first one gets overwritten. So I have only one item all the time. If I remove comment on line adapter.notifyDataSetChanged(); the app crashes when reaching to this line.
I have also tried adapter.add(product); The result is the same as the line above - app crashes.
I have searched for answer in here, but can't find it.
My question is how to fix it so that I could dynamically add item to ListView??
EDIT:
The error message im getting
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.olev.shoppinglist/com.example.olev.shoppinglist.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object reference
at com.example.olev.shoppinglist.MainActivity.addToList(MainActivity.java:48)
at com.example.olev.shoppinglist.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
It's because you are sending String in place of List from your first activity to another activity.
i.e. Suppose the line putExtra("product","Item1") is for sending a string item item1 in your second activity. When you call your second activity, list is intialized again and only one item i.e. "Item1" is added to the list.
To send list, you can use intent.putParcelableArrayListExtra("key",value); method.