I test my application on debug and crash on this line:
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);
with this error:
System services not available to Activities before onCreate()
I solved this error whit this code (change this with context):
listAdapter = new ArrayAdapter(promptsView.getContext(), R.layout.cd_edittext_for_listview, planetList);
And change on XML file "EditView" with "EditText"!*
I have this layout for the items "editText_for_listview.xml":
<EditView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowEditView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp">
</EditView>
And my main layout "items_listview.xml"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mylistview"
android:layout_gravity="center" />
</LinearLayout>
The code is this:
public void _ShowItems(String sTitle,android.content.Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(sTitle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
final View promptsView = inflater.inflate(R.layout.items_listview, null);
ListView mainListView ;
ArrayAdapter<String> listAdapter ;
mainListView = (ListView) promptsView.findViewById( R.id.editText_for_listview );
String[] planets = new String[] { "Test1", "Test2", "Test3" };
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
builder.setView(promptsView)
.setPositiveButton("One", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Two", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
Can you help me?
Where I wrong?
Thanks
Obviously you are trying to use the Activity Context prior to the Activity's onCreate() method being called. Try moving your call to _ShowItems() to onResume() method.
Could you show up more code of your activity. You could just be calling the method in a spot where the context isn't initialized but something else could be going on that will be revealed once we have a better look at the activity.
I would have made this a comment but I don't have the reputation to do so.
Related
So what I'm trying to do is to have an AlertDialog where the user can add their own groceries to the database. I want the program to give suggestions while the user is typing. I want to combine an AlertDialog with an AutoCompleteTextView. I followed this guide for the AutoComplete section https://developer.android.com/reference/android/widget/AutoCompleteTextView.html, but I can't seem to get it right.
In main:
public void add(View caller) {
MaterialAlertDialogBuilder mBuilder = new MaterialAlertDialogBuilder(mainActivity.this);
mBuilder.setTitle(R.string.dialog_title);
mBuilder.setView(R.layout.add_items_dialog);
mBuilder.setMessage("Enter a grocery");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, GROCERIES);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.name_text_field);
textView.setAdapter(adapter);
mBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
}
});
mBuilder.setNegativeButton(R.string.dismiss_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
add_items_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/name_text_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/dp_16"
android:layout_marginEnd="#dimen/dp_16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:hint="#string/enter_text"
android:textColorHint="#color/colorDarkGreen"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/et_input"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="text"
android:singleLine="true" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Error at the line textView.setAdapter(adapter):
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setAdapter(android.widget.ListAdapter)' on a null object reference
I guess that it has something to do with setting the adapter to the wrong textview but it can also be something entirely different. Any suggestions?
You need to change mbuilder.addView(R.layout.add_itemes_dialog)
by
View view =LayoutInflater.from(this).inflate(R.layout.add_itemes_dialog, null);
builder.setView(view);
// and to find your AutoCompleteTextView
AutoCompleteTextView textView = (AutoCompleteTextView) view.findViewById(R.id.et_input);
and also in your xml file change TextInputEditText by MaterialAutoCompleteTextView and it should work
I am getting an error when trying to set my view to display the ListView for the file I want to display(text file). I am pretty sure it has something to do with the XML. I just want to display the information from this.file = fileop.ReadFileAsList("Installed_packages.txt");. My code:
public class Main extends Activity {
private TextView tv;
private FileOperations fileop;
private String[] file;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.fileop = new FileOperations();
this.file = fileop.ReadFileAsList("Installed_packages.txt");
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
ListView lv = new ListView(this);
lv.setTextFilterEnabled(true);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
setContentView(lv);
}
}
list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#000">
</LinearLayout>
main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<ScrollView
android:id="#+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fillViewport="true">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5sp"
android:id="#+id/TextView01"
android:text="#string/hello"/>
</ScrollView>
</LinearLayout>
The ArrayAdapter requires the resource ID to be a TextView XML exception means you don't supply what the ArrayAdapter expects. When you use this constructor:
new ArrayAdapter<String>(this, R.layout.a_layout_file, this.file)
R.Layout.a_layout_file must be the id of a xml layout file containing only a TextView(the TextView can't be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
// other attributes of the TextView
/>
If you want your list row layout to be something a little different then a simple TextView widget use this constructor:
new ArrayAdapter<String>(this, R.layout.a_layout_file,
R.id.the_id_of_a_textview_from_the_layout, this.file)
where you supply the id of a layout that can contain various views, but also must contain a TextView with and id(the third parameter) that you pass to your ArrayAdapter so it can know where to put the Strings in the row layout.
Soution is here
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
</LinearLayout>
Java code :
String[] countryArray = {"India", "Pakistan", "USA", "UK"};
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listitem,R.id.textview, countryArray);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
If you are getting that message when you are extending an ArrayAdapter, you are getting that error because you have not provided the correct resource id to display the item. Call the super class in the constructor and pass in the resource id of the TextView:
//Pass in the resource id: R.id.text_view
SpinnerAdapter spinnerAddToListAdapter = new SpinnerAdapter(MyActivity.this,
R.id.text_view,
new ArrayList<>());
Adapter:
public class SpinnerAdapter extends ArrayAdapter<MyEntity> {
private Context context;
private List<MyEntity> values;
public SpinnerAdapter(Context context, int textViewResourceId,
List<MyEntity> values) {
//Pass in the resource id: R.id.text_view
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
The problem is in the line:
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));
Because when i change it to:
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.file));
It works!
I'm experiencing the problem "Unfortunately, your listview has stopped working" when i was using the android emulator to run my codes.
Please take a look at my codes thanks!
For activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="com.example.it3783.listview.MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Choose a location..."/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:id="#+id/spLocations"></ListView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#+id/superHerosTV"
/>
</LinearLayout>
For MainActivity.java:
public class MainActivity extends AppCompatActivity {
ArrayAdapter<CharSequence>adapter;
TextView tvSelection;
ListView lvLocation;
String []strArray;
String []superHeros = {"1. Batman\n 2. SpiderMan", "1. Peter Pan\n2. Superman",
"1. IronMan\n2. Peter Pan", "1. SnowWhite \n2. Gingerbreadman"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1, strArray);
tvSelection = (TextView) findViewById(R.id.superHerosTV);
lvLocation = (ListView) findViewById(R.id.spLocations);
Resources myRes = this.getResources();
strArray = myRes.getStringArray(R.array.locationArea);
lvLocation.setAdapter(adapter);
lvLocation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text = strArray[position];
tvSelection.setText(text);
}
});
adapter = ArrayAdapter.createFromResource(this, R.array.locationArea, android.R.layout.simple_list_item_1);
}
}
For strings.xml:
<resources>
<string name="app_name">ListView</string>
<string-array name="locationArea">
<item>North</item>
<item>South</item>
<item>East</item>
<item>West</item>
</string-array>
</resources>
adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, strArray);
This line in your onCreate methods takes the strArray, which is not initialized so its value is null.
Now when you set the adapter with null data to the listview, it crashes.
I create a custom DialogFragment. It contains a listView, but when the list calls setAdapter there is a NullPointerException. I can't understand why.
This is the code:
public class LineUpConfirm extends DialogFragment {
private ListView list;
private List<ItemLineUpConfirm> pList = new ArrayList<ItemLineUpConfirm>();
private AdapterListConfirmLineUp adapter;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.confirm_lineup_layout, null));
pList.add(new ItemLineUpConfirm("P", "C. Abbiati","MIL","INT"));
pList.add(new ItemLineUpConfirm("D", "C. Papastapopulos","SAS","VER"));
pList.add(new ItemLineUpConfirm("C", "Cacca","SAM","GEN"));
adapter = new AdapterListConfirmLineUp(CurrentContext.getContext(),
R.layout.item_confirm_lineup, pList);
list = (ListView) getActivity().findViewById(R.id.list_confirm_lineup);
list.setAdapter(adapter); // HERE NullPointerException
return builder.create();
}
}
This is the layout of my Dialogfragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/title_progressdialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Formazione creata"
android:layout_margin="5dp" />
<ListView
android:id="#+id/list_confirm_lineup"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff"
android:divider="#575555"
android:dividerHeight="1dp" />
<Button
android:id="#+id/button_confirm_lineup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Conferma"
android:layout_gravity="center" />
</LinearLayout>
Your list is null because you're trying to get the View from the Activity layout instead of the one of the Dialog.
Try to keep a reference of the Dialog view and get it from there:
View dialogView = inflater.inflate(R.layout.confirm_lineup_layout, null);
// some code
list = (ListView) dialogView.findViewById(R.id.list_confirm_lineup);
I update your method
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.confirm_lineup_layout, null);
builder.setView(v);
pList.add(new ItemLineUpConfirm("P", "C. Abbiati", "MIL", "INT"));
pList.add(new ItemLineUpConfirm("D", "C. Papastapopulos", "SAS", "VER"));
pList.add(new ItemLineUpConfirm("C", "Cacca", "SAM", "GEN"));
adapter = new AdapterListConfirmLineUp(CurrentContext.getContext(), R.layout.item_confirm_lineup, pList);
list = (ListView) v.findViewById(R.id.list_confirm_lineup);
list.setAdapter(adapter); // HERE NullPointerException
return builder.create();
}
The problem was you are trying to find the listview from activity but it is actually in alertbuilder view. So I just change that.
I'm having problems with setting multiple choice selection in ListView. My ListView has contacts' names which are retrieved from the android phone.
I've followed examples on setting multiple choice but it didn't work out.
I've tried typing
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contacts_list, c, columns, views);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
this.setListAdapter(adapter);
but I don't see the checkbox in the ListView.
And I've replaced R.layout.contacts_list with android.R.layout.simple_list_item_multiple_choice and it showed checkboxes but no names from the android phone's contacts.
Here are my codes:
contacts_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#color/light_goldenrod"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stackFromBottom="false"
android:transcriptMode="normal"
android:choiceMode="multipleChoice" >
</ListView>
<TextView
android:textColor="#color/dark_purple"
android:id="#+id/contactName"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
ContactsList.java
public class ContactsList extends ListActivity
{
final Context context = this;
Cursor cursor;
String[] buddiesList =
{"Kanak Priya",
"Joanne Liew",
"Michelle Lam",
"Teo Kin Hua",
"Melissa Haiting",
"David Yeo",
"Natasha Akhbar",
"Gillian Gan",
"Sonia",
"Ms Long",
"Joan Tang",
"Stephanie",
"Nur Ashiqin"
};
BuddyDBAdapter buddyDB = new BuddyDBAdapter(this);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_list);
ListView list = getListView();
setListAdapter(new ArrayAdapter<String> (this, R.layout.contacts_list, R.id.contactName, buddiesList));
Uri allContacts = Uri.parse("content://contacts/people");
Cursor c = managedQuery(allContacts, null, null, null, null);
String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
int[] views = new int[] {R.id.contactName};
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contacts_list, c, columns, views);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
this.setListAdapter(adapter);
/*if(cursor.getCount()<0)
{
Intent displayIntent = new Intent(Intent.ACTION_VIEW);
displayIntent.setData(Uri.parse("content://contacts/people"));
startActivity(displayIntent);
displayIntent = new Intent(Intent.ACTION_VIEW);
//displayIntent.setData(Uri.parse("content://contacts/people/"+id));
startActivity(displayIntent);
}
else
{
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("ALERT!");
alertDialog.setMessage("NO Name is Found! D:");
alertDialog.setIcon(R.drawable.warning);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent backIntent = new Intent(context, ContactsList.class);
startActivity(backIntent);
}
});
alertDialog.show();
}*/
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
buddyDB.open();
long name_id;
super.onListItemClick(l, v, position, id);
Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
TextView contactName = (TextView) v.findViewById(R.id.contactName);
String NameValue = contactName.getText().toString();
name_id = buddyDB.insertNames(NameValue);
Toast.makeText(getBaseContext(),
"Selected: " + buddiesList[position], Toast.LENGTH_SHORT).show();
buddyDB.close();
Oh by the way, the
String[] buddiesList =
{"Kanak Priya",
"Joanne Liew",
"Michelle Lam",
"Teo Kin Hua",
"Melissa Haiting",
"David Yeo",
"Natasha Akhbar",
"Gillian Gan",
"Sonia",
"Ms Long",
"Joan Tang",
"Stephanie",
"Nur Ashiqin"
};
is for my Toast message.
I really need help with this. Any help will be appreciated. Examples will be greatly appreciated too.
Thanks
You may have two choices:
1 - Use default layout from Android resources (simple_list_item_multiple_choice)
you may replace this code:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.contacts_list, c, columns, views);
to:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, c, columns, new int {android.R.id.text1});
2 - Create your new row layout contains your defined checkbox and handle it by your own.
contact_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#color/light_goldenrod"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stackFromBottom="false"
android:transcriptMode="normal"
android:choiceMode="multipleChoice" >
</ListView>
</LinearLayout>
contact_entry.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#color/dark_purple"
android:id="#+id/contactName"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/contactCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:checked="false" />
</LinearLayout>
Add custom cursor adapter like this:
public class YourCursorAdapter extends CursorAdapter {
private Context mContext;
private Cursor mCurser;
public YourCursorAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, ContentResolver co) {
super(context, c);
mCurser = c;
mContext = context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.contact_entry, parent, false);
bindView(v, mContext, cursor);
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView contactName= (TextView)view.findViewById(R.id.contactName);
contactName.setText(cursor.getString((mCurser
.getColumnIndexOrThrow(Contacts.Phones.DISPLAY_NAME))));
CheckBox contactCheckbox = (TextView)view.findViewById(R.id.contactCheckbox);
contactCheckbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Checkbox checkBox = (Checkbox) v.findViewById(R.id.contactCheckbox)
if (checkBox.isChecked())
checkBox.setChecked(false);
else
checkBox.setChecked(true);
}
});
}
in your ListActivity:
YourCursorAdapter adapter = new YourCursorAdapter(this,
null, c, null, null,null);
this.setListAdapter(adapter);