I am using an array adapter to populate a listview from user input. The array adpter will not work however and crashes the app. I don't no why it does this and I would appreciate if anyone could explain why. Below is my class and the error I get.
My Class
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class AddScore extends AppCompatActivity {
private ListView lv;
private EditText player;
private EditText description;
private EditText winner;
private EditText game;
private Button btn3;
private String TAG = "Hannah";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_score);
// MySQLiteHelper db = new MySQLiteHelper(this);
lv = (ListView) findViewById(R.id.lv);
player = (EditText) findViewById(R.id.player);
description = (EditText) findViewById(R.id.description);
winner = (EditText) findViewById(R.id.winner);
game = (EditText) findViewById(R.id.game);
btn3 = (Button) findViewById(R.id.button3);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
List<String> sLog = new ArrayList<>();
MySQLiteHelper Helper = new MySQLiteHelper(view.getContext());
List sLogs = Helper.getAllScores();
sLog.add(player.getText().toString().trim());
sLog.add(description.getText().toString().trim());
sLog.add(winner.getText().toString().trim());
sLog.add(game.getText().toString().trim());
for (int i = 0; i < sLog.size(); i++) {
Score score = new Score();
sLog.add(score.toString());
}
//ListView listView = (ListView) findViewById(R.id.lv);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, sLog);
Log.d(TAG, "**************************");
lv.setAdapter(arrayAdapter);
Score score = new Score();
arrayAdapter.add(String.valueOf(score));
Toast.makeText(AddScore.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
Error
Error:(62, 53) error: cannot infer type arguments for ArrayAdapter<>
Change
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, sLog);
to
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, sLog);
You need to pass the context. As this is inside a closure, you need to explicitly getActivity() as this will be not get you the context.
Because using only this refers to View.OnClickListener class not activity class. And ArrayAdapter<> requires context as first argument which can be provided here by activity and not View.OnClickListener.
So try like this:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(AddScore.this, android.R.layout.simple_list_item_1, sLog);
Log.d(TAG, "**************************");
lv.setAdapter(arrayAdapter);
Related
I am new to android, I am trying to implement the cascading spinner. When I select the first spinner it should populate the second spinner choices based on the 1st spinner selection. I have almost done, but in second spinner I cannot select the value. When I select the value it is disappearing. Please help me in this.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class DummyMain extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public Spinner spinner1, spinner2;
public String[] spinner1Values = {"A", "B"}, valuesForA = {"1", "2"}, valuesForB = {"3", "4", "5", "1"};
public ArrayAdapter<String> adapterForSpinner1, adapterForSpinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
adapterForSpinner1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, spinner1Values);
adapterForSpinner1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapterForSpinner1);
spinner1.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
Toast.makeText(this, "Result "+spinner1.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
if (parent.getId() == R.id.spinner1) {
if (spinner1.getSelectedItem().toString().equals("A")) {
adapterForSpinner2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item,valuesForA);
adapterForSpinner2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapterForSpinner2);
spinner2.setOnItemSelectedListener(this);
} else {
adapterForSpinner2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item,valuesForB);
adapterForSpinner2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapterForSpinner2);
spinner2.setOnItemSelectedListener(this);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Found the issue, I have fixed it.
ArrayAdapter<String> adapterForSpinner2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, valuesForB);
I have changed the getApplicationConetxt() into this. It works :-)
ArrayAdapter<String> adapterForSpinner2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, valuesForB);
try adding this in your DummyMain
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
I am doing my coursework for computing and every time i try and run my app and go onto this activity it crashes and says unfortunately activity has stopped. If i delete the last part of the code from the line (-----) down, the activity appears and works. But with it, it doesn't work. Does anyone know why this is the case and how i could fix it.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
public class BedroomDoorSigns extends AppCompatActivity {
private String[] wood;
private Spinner spinner;
private String[] colour;
private String[] size;
private Button mButton;
private LinearLayout mLayout;
private EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_bedroom_door_signs);
wood = getResources().getStringArray(R.array.wood_list);
spinner = (Spinner) findViewById(R.id.wood_spinner);
colour = getResources().getStringArray(R.array.colour_list);
spinner = (Spinner) findViewById(R.id.colour_spinner);
size = getResources().getStringArray(R.array.size_list);
spinner = (Spinner) findViewById(R.id.size_spinner);
Button Buttons = (Button) findViewById(R.id.Cart);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("New text");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, wood);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, colour);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter2);
ArrayAdapter<String> dataAdapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, size);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter3);
}
public View.OnClickListener onClick() {
return new View.OnClickListener() {
public void onClick(View v) {
mLayout.addView(createNewTextView(mEditText.getText().toString()));
}
};
}
public TextView createNewTextView(String text) {
final ViewGroup.LayoutParams lparams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("BASKET: " + text);
return textView;
}
}
Thank you
try like this
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLayout.addView(createNewTextView(mEditText.getText().toString()));
}
});
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.emily.activity414timber.BedroomDoorSigns.onCreate(BedroomDoorSigns.java:41) at
your button object (mButton) is null and so it is throwing 'nullpointerexception' when you call 'setOnclickListner' method on that object
The following code gives me this error: The constructor ArrayAdapter(TrainingDetails, int, String[]) is undefined. How to rectify it? Please help. Here I am trying to retrieve the value of the selected spinner and store it in another string.
package com.example.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.R;
public class TrainingDetails extends BaseFragment
{
View view;
private EditText nameEdt;
private Spinner trainingTypes;
private Spinner trainerProfile;
String data1[] = {"1", "2", "3"};
String data2[] = {"a", "b", "c"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view=inflater.inflate(R.layout.training_details, container,false);
nameEdt = (EditText) view.findViewById(R.id.name_edt);
trainingTypes = (Spinner) view.findViewById(R.id.trainingtypes_spn);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data1);
adapter_state.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trainingTypes.setAdapter(adapter_state);
trainingTypes.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
String selectedItem = data1[index];
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
trainerProfile = (Spinner) view.findViewById(R.id.trainerprofile_spn);
return view;
}
}
change
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data1);
to
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, data1);
in Fragment you'll get Context by using getActivity()
For ArrayAdapter you need to pass Context
change this
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data1);
into
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, data1);
The first parameter of ArrayAdapter is a Context object not an instance of a Fragment. Change
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data1);
with
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, data1);
I have two buttons tab1 and tab2.Within tab1 i have few edittext.I want to allow the user to click on the tab2 only when all the edittext in tab1 are filled,they should not be empty.
package com.megasys.roushfunway.survey;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import com.megasys.roushfunway.MasterFragment;
import com.megasys.roushfunway.MasterFragmentActivity;
import com.megasys.roushfunway.R;
public class SurveyFragment extends MasterFragment implements OnClickListener {
View view;
String[] seventPublic, syes, time, people,usa;
Button tab1,tab2;
LinearLayout layout1,layout2;
ArrayAdapter<String> eventyes;
ArrayAdapter<String> usaStates;
ArrayAdapter<String> eventTime;
ArrayAdapter<String> eventPublic;
ArrayAdapter<String> eventPeople;
boolean check=false;
EditText etNoEventDays=null, etMaterialQtyHanded, etEventItemType, etFeedback,
etCommentOpportunity, etHotelName, etHotelCity, etHotelZip,
etHotelRate, etHotelAddress, etHotelPhone;
Spinner spEventPublicPrivate, spEventContact, spPassMaterial,
spAddedEventItems, spEventTimeFrame, spPeopleAttached,
spIntroduceOnsiteContact, spState, spWasHotelBooked;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
}
private void initView() {
etNoEventDays = (EditText) view.findViewById(R.id.et_no_of_events);
etMaterialQtyHanded = (EditText) view
.findViewById(R.id.et_material_quantity_handed);
etEventItemType = (EditText) view
.findViewById(R.id.et_event_items_type);
etFeedback = (EditText) view.findViewById(R.id.et_feedback);
etCommentOpportunity = (EditText) view
.findViewById(R.id.et_opportunity);
etHotelName = (EditText) view.findViewById(R.id.et_Hotel_Name);
etHotelCity = (EditText) view.findViewById(R.id.et_Hotel_City);
etHotelAddress = (EditText) view.findViewById(R.id.et_Hotel_Address);
etHotelZip = (EditText) view.findViewById(R.id.et_Hotel_Zip);
etHotelRate = (EditText) view.findViewById(R.id.et_Hotel_Rate);
spAddedEventItems = (Spinner) view
.findViewById(R.id.sp_event_added_items);
spEventPublicPrivate = (Spinner) view
.findViewById(R.id.sp_event_public_private);
spEventContact = (Spinner) view
.findViewById(R.id.sp_event_contact_prepared);
spEventTimeFrame = (Spinner) view
.findViewById(R.id.sp_event_time_frame);
spPassMaterial = (Spinner) view.findViewById(R.id.sp_pass_out_material);
spPeopleAttached = (Spinner) view
.findViewById(R.id.sp_introduce_yourself);
spPeopleAttached = (Spinner) view
.findViewById(R.id.sp_no_of_people_attended);
spState = (Spinner) view.findViewById(R.id.sp_state);
spIntroduceOnsiteContact = (Spinner) view
.findViewById(R.id.sp_introduce_yourself);
spWasHotelBooked = (Spinner) view.findViewById(R.id.sp_hotel_booked);
seventPublic = getResources().getStringArray(R.array.public_private);
eventPublic = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, seventPublic);
eventPublic
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEventPublicPrivate.setAdapter(eventPublic);
syes = getResources().getStringArray(R.array.yes_no);
eventyes = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, syes);
eventPublic
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEventContact.setAdapter(eventyes);
spAddedEventItems.setAdapter(eventyes);
spPassMaterial.setAdapter(eventyes);
spIntroduceOnsiteContact.setAdapter(eventyes);
spWasHotelBooked.setAdapter(eventyes);
time = getResources().getStringArray(R.array.time_frame);
eventTime = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, time);
eventTime
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEventTimeFrame.setAdapter(eventTime);
people = getResources().getStringArray(R.array.people_attended);
eventPeople = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, people);
eventPeople
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spPeopleAttached.setAdapter(eventPeople);
usa=getResources().getStringArray(R.array.USA);
usaStates=new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item,usa);
usaStates
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spState.setAdapter(usaStates);
tab1=(Button) view.findViewById(R.id.tab1);
tab2=(Button) view.findViewById(R.id.tab2);
tab1.setOnClickListener(this);
tab2.setOnClickListener(this);
layout1=(LinearLayout) view.findViewById(R.id.layout1);
layout2=(LinearLayout) view.findViewById(R.id.layout2);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.survey_addedit_fragment, container,
false);
return view;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.tab1:
layout1.setVisibility(arg0.VISIBLE);
layout2.setVisibility(arg0.GONE);
break;
case R.id.tab2:
validation();
if(check){
layout2.setVisibility(arg0.VISIBLE);
layout1.setVisibility(arg0.GONE);
}else{
layout1.setVisibility(arg0.VISIBLE);
layout2.setVisibility(arg0.GONE);
}
default:
break;
}
}
public boolean validation(){
if(etNoEventDays==null){
etNoEventDays.setBackgroundColor(Color.RED);
MasterFragmentActivity.showprogressDialog(mContext, "Error",
"Please fill all the mandatory fields", true);
check=true;
}
return check;
}
}
I have two buttons tab1 and tab2.Within tab1 i have few edittext.I want to allow the user to click on the tab2 only when all the edittext in tab1 are filled,they should not be empty.
I learned that in order to modify row in a listView I need to gain access eg via adapter.getItem(position) but I have no idea how to work this around. Should I post any code please let me know.
Here is my EditListItemDialog file:
package com.example.classorganizer;
import java.util.ArrayList;
import java.util.List;
import com.example.classorganizer.Monday.DiaryAdapter;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
private DiaryAdapter adapter;
// public EditListItemDialog(Context context, List<String> fragment_monday) { //first constructor
// super(context);
// this.fragment_monday = fragment_monday;
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
private List<String> fragment_monday;
public EditListItemDialog(Context context, DiaryAdapter adapter) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
adapter.notifyDataSetChanged();
dismiss();
}
}
You will have to implement an OnItemClickListener which will be able to tell you what item has been clicked. For example:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
See the official Android documentation for more information.
package com.example.classorganizer;
import java.util.ArrayList;
import java.util.List;
import com.example.classorganizer.Monday.DiaryAdapter;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class EditListItemDialog extends Activity {
ListView listView ;
private View editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
listView = (ListView) findViewById(R.id.list)
String[] values = new String[] { "Automotive", "Banking", "Consumer Electronics",
"Education", "HealthCare and Life Sciences","Industrial Automation","Printing and
Imaging","Manufacturing","Media and
Entertainment","Networking","Retail","Telecom"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
Use This code for simple Listview..