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.
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>
After i made some changes in an AsynTask i get this error when running the app:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.popularmovies/com.example.android.popularmovies.MainActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
This is the activity_main.xml file.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment"
android:name="com.example.android.popularmovies.MainActivityFragment"
tools:layout="#layout/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And this is the MainActivity.java file:
package com.example.android.popularmovies;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
}
Thanks for any help you can provide! ;)
I am not sure try the following:
Add
tools:context= ".MainActivity"
or Can you put <fragment> inside a <FrameLayout>.
Clean the code once.
I know there are many equal to the problems but none of the many who have read is equal to mine or has worked for me for help , so it is going to require your help.
I'm working on an application with a NavigationDrawer , I need to make an image work for me on and off the bluetooth cell .
I made another code separately with an " empty activity" and if I worked, but in the navigariondrawe that is where I need it to work , but it does not work , I 've tried many things , but I hope you can help me .
FATAL EXCEPTION: main
Process: com.example.lab02pc19.myapplication2, PID: 5146
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lab02pc19.myapplication2/com.example.lab02pc19.myapplication2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.lab02pc19.myapplication2.MainActivity.setImagenBluetooth(MainActivity.java:69)
at com.example.lab02pc19.myapplication2.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6245)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lab02pc19.myapplication2">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package com.example.lab02pc19.myapplication2;
import android.bluetooth.BluetoothAdapter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentBlue.OnFragmentInteractionListener {
ImageView miimagen;
BluetoothAdapter adaptador_bluetooth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
miimagen= (ImageView)findViewById(R.id.ivw);
adaptador_bluetooth= BluetoothAdapter.getDefaultAdapter();
if(adaptador_bluetooth==null)
{
miimagen.setVisibility(View.GONE);
}
else
{
setImagenBluetooth(adaptador_bluetooth.isEnabled());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void clickImagen(View view)
{
switch (view.getId())
{
case R.id.ivw:
setEstadoBluetooth();
break;
}
}
public void miimagen()
{
setEstadoBluetooth();
}
public void setImagenBluetooth(boolean valor)
{
if(valor)miimagen.setImageResource(R.drawable.ic_action_bluetooth);
}
public void setEstadoBluetooth()
{
if(adaptador_bluetooth.isEnabled())
{
setImagenBluetooth(false);
adaptador_bluetooth.disable();
}
else
{
setImagenBluetooth(true);
adaptador_bluetooth.enable();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
boolean FragmenTransaction= false;
Fragment fragment = null;
if (id == R.id.nav_camera) {
fragment = new FragmentBlue();
FragmenTransaction= true;
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if(FragmenTransaction)
{
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,fragment).commit();
item.setChecked(true);
getSupportActionBar().setTitle(item.getTitle());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
<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.example.lab02pc19.myapplication2.FragmentBlue">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivw"
android:layout_gravity="left|top"
android:background="#drawable/ic_action_bluetooth"
android:clickable="true"
android:onClick="clickImagen"
android:contentDescription="#string/imagen" />
</FrameLayout>
As I think (it is not enough info), you want to create a fragment in the activity and make some actions with ImageView further. But you didn't create the fragment and try to find ImageView by id in other layout - thus, the image view didn't exist here, next you try to call function of the null object and finally have a NPE and crash. You need to read tutorial about fragment in Android: https://developer.android.com/training/basics/fragments/index.html
You are trying to access the image view of the fragment in your activity class which is not possible that's why giving null point exception. What you can do it that you can setImage in the image view in you fragment java class in onActivityCreated override method after setting the contentView.
If you want to set the image from the activity only then you can create the public method in the fragment and call the method from the activity.
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'
So I'm starting to work on my first Android App and I've already hit a wall. I want to start off with a "Create" button at the action menu at the top that has the ability to create new contacts. But then I hit some sort of error I can't understand and it's been hindering my process.
The error started when I added the "onClick" line tot he action item and since then, stopped running on my emulator.
Thank you.
MainActivity.java
package com.xephos.detra;
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.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
public void create(View v){
TextView tv = (TextView) findViewById(R.id.test);
tv.setText("Working!");
}
}
This might help: the menu_main.xml.
<menu 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" tools:context=".MainActivity">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
<item
android:id="#+id/add"
android:title="Add New Contact"
app:showAsAction ="always"
android:icon="#drawable/ic_add_white_48dp"
android:onClick="create"/>
</menu>
And finally, the error:
20653-20653/com.xephos.detra E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.xephos.detra, PID: 20653
android.view.InflateException: Couldn't resolve menu item onClick handler create in class com.xephos.detra.MainActivity
at android.support.v7.internal.view.SupportMenuInflater$InflatedOnMenuItemClickListener.<init>(SupportMenuInflater.java:242)
at android.support.v7.internal.view.SupportMenuInflater$MenuState.setItem(SupportMenuInflater.java:443)
at android.support.v7.internal.view.SupportMenuInflater$MenuState.addItem(SupportMenuInflater.java:479)
at android.support.v7.internal.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:196)
at android.support.v7.internal.view.SupportMenuInflater.inflate(SupportMenuInflater.java:118)
at com.xephos.detra.MainActivity.onCreateOptionsMenu(MainActivity.java:22)
at android.app.Activity.onCreatePanelMenu(Activity.java:2823)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:277)
at android.support.v7.internal.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:84)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:275)
at android.support.v7.app.AppCompatDelegateImplV7.preparePanel(AppCompatDelegateImplV7.java:1117)
at android.support.v7.app.AppCompatDelegateImplV7.doInvalidatePanelMenu(AppCompatDelegateImplV7.java:1399)
at android.support.v7.app.AppCompatDelegateImplV7.access$100(AppCompatDelegateImplV7.java:89)
at android.support.v7.app.AppCompatDelegateImplV7$1.run(AppCompatDelegateImplV7.java:126)
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: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.NoSuchMethodException: create [interface android.view.MenuItem]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.support.v7.internal.view.SupportMenuInflater$InflatedOnMenuItemClickListener.<init>(SupportMenuInflater.java:240) ...
You create method needs to take a MenuItem as the argument, not a View.
public void create(MenuItem item){
TextView tv = (TextView) findViewById(R.id.test);
tv.setText("Working!");
}
Alternatively, remove the android:onClick attribute of your menu item and handle the click in onOptionsItemSelected() by checking the id of the item:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
// your code here
return true;
case R.id.action_settings:
// copied from auto-generated stub
return true;
}
return super.onOptionsItemSelected(item);
}
Either will work, my preference is the second approach.
You'd be better off doing it programmatically. Get rid of the 'android:OnClick' line in the XML, then after you set the text of 'tv' put in this:
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Process click here
});
This should do the trick!