I'm trying to add a spinner to my android app but gives me this error(Compilation failed; see the compiler error output for details.) and this part (MainActivity.this,) has a red line under it when the cursor is under it says 'com.example.myapplication.MainActivity' is not an enclosing class. I'm doing this from another activity not from the main activity. No changes in the MainActivity.
AddEmployee class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_employee);
Spinner myspinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter myAdapter = ArrayAdapter.createFromResource(MainActivity.this, R.array.types, android.R.layout.simple_list_item_1);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(myAdapter);
}
try with like this
List<String > strings = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<>(activity,android.R.layout.simple_list_item_1,strings);
spinner.setAdapter(adapter);
You need a valid context, so you should use your current activity
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_employee);
Spinner myspinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter myAdapter = ArrayAdapter.createFromResource(SecondActivity.this, R.array.types, android.R.layout.simple_list_item_1);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(myAdapter);
}
}
or you can use this or getApplicationContext() instead of MainAcitvity.this
but I prefer to use this
createFromResource's first parameter is context. You can get context in two way:
Application Context: getApplicationContext()
Activity's Context: ActivityName.this
Application context is general context of project, you can get it from all activity.
Activity contexs are specific to the activity. So you can access it from only it's own activity. You tried to access an activity context from another activity so it gave this error. You can try getApplicationContext() or AddEmployee.this
Here is a working example :
public class Main extends AppCompatActivity implements AdapterView.OnItemSelectedListener
{
String[] item_list= {"Select your option", "item1", "item2", "item3", "item4"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_employee);
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, item_list);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Related
public class SecondActivity extends AppCompatActivity {
private String [] myList = new String[]{"Blue", "Green", "Red"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ListView listView = (ListView)findViewById(R.id.ListView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listView.setAdapter(adapter);
}
}
Don't use an ArrayAdapter. Use a custom adapter and set the background of each item.
Better yet- don't use ListView. It's been deprecated for most of a decade. Use a RecyclerView, and set the background color in onBindViewHolder.
I have a fragment in which I am trying to call a new activity on a button click.
btnLoadLimit.setOnClickListener(v -> {
Intent intent = new Intent(getActivity(), DataActivity.class);
startActivity(intent);
});
Data Activity
public class DataActivity extends AppCompatActivity {
Context mContext;
#BindView(R.id.smart_msn_spinner)
Spinner msnSpinner;
ArrayList<String> msnArrayList = new ArrayList<>(Arrays.asList("Select MSN","002998002010" )); //"002999002020"
ArrayAdapter<String> msnAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
msnAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
msnSpinner.setAdapter(msnAdapter);
msnSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedMeterNo = msnArrayList.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
When I click on btnLoadLimit button my app is closing with the following error
Unable to start activity ComponentInfo{com.thumbsol.accuratemobileassetsmanagament/com.thumbsol.accuratemobileassetsmanagament.fragment.DataActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at com.thumbsol.accuratemobileassetsmanagament.fragment.DataActivity.onCreate(DataActivity.java:122)
The line 122 is msnAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
The same method I have applied in my fragment and it's working but in my new activity it's not.
Note: The activity is displaying if none of the methods are invoked.
Looks like you don't initialize your mContext. meaning you're passing null to your ArrayAdapter().
You shouldn't be storing your context anyway, since your context is your activity..
You can just use this:
msnAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, msnArrayList);
I have two activities. When an item in a RecyclerView is selected, it takes the user to the second activity and fills in the details with the related RecyclerView item.
In the second RecyclerView activity, there is a Spinner. Depending on the item selected in the spinner, different RecyclerViews become visible/invisible to the user on the second activity.
How do I make it work so that the information is sent from the first activity to command the spinner on what to do?This is how Second Activity looks
SecondActivity.java
public class SecondActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private TextView tv_title, tv_description;
private ImageView PartiesThumbnailImg,PartiesCoverImg;
private RecyclerView RvPartyMembers;
private PartyMembersAdapter partyMembersAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parties_detail);
Spinner spinner = findViewById(R.id.spnConstituencies);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.constituencies, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//ini views
iniViews();
//Setting up members list
setupRvPartyMembers();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
void iniViews() {
RvPartyMembers = findViewById(R.id.rv_party_members);
String partiesTitle = getIntent().getExtras().getString("title");
String partiesDescription = getIntent().getExtras().getString("description");
int imageResourceId = getIntent().getExtras().getInt("imgURL");
int imagecover = getIntent().getExtras().getInt("imgCover");
PartiesThumbnailImg = findViewById(R.id.detail_members_img);
Glide.with(this).load(imageResourceId).into(PartiesThumbnailImg);
PartiesThumbnailImg.setImageResource(imageResourceId);
PartiesCoverImg = findViewById(R.id.detail_members_cover);
Glide.with(this).load(imagecover).into(PartiesCoverImg);
tv_title = findViewById(R.id.tvPartyTitle);
tv_title.setText(partiesTitle);
tv_description = findViewById(R.id.tvPartyDesc);
tv_description.setText(partiesDescription);
}
void setupRvPartyMembers(){
List<PartyMembers> mdata = new ArrayList<>();
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
partyMembersAdapter = new PartyMembersAdapter(this,mdata);
RvPartyMembers.setAdapter(partyMembersAdapter);
RvPartyMembers.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
}
These are the important pieces of code of the FirstActivity.java
#Override
public void onPartiesItemClick(PartiesOireachtas partiesOireachtas, ImageView partiesImageView) {
Intent intent = new Intent(getContext(),PartiesDetailActivity.class);
intent.putExtra("title", partiesOireachtas.getTitle());
intent.putExtra("description",partiesOireachtas.getDescription());
intent.putExtra("imgURL", partiesOireachtas.getThumbnail());
intent.putExtra("imgCover",partiesOireachtas.getCoverPhoto());
and
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//RecyclerView Setup
//int data
lstPartiesOireachtas = new ArrayList<>();
lstPartiesOireachtas.add(new PartiesOireachtas("Fianna Fáil", "example1", R.drawable.fianna_fail_logo,R.drawable.fianna_fail_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Sinn Féin", "example2", R.drawable.sinn_fein_logo,R.drawable.sinn_fein_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Fine Gael", "example4", R.drawable.fine_gael_logo,R.drawable.fine_gael_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Green Party", "example9", R.drawable.green_party_logo,R.drawable.green_party_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Social Democrats", "example3", R.drawable.soc_dems_logo,R.drawable.soc_dems_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Independent", "example2", R.drawable.independent_party_logo,R.drawable.independent_party_cover));
As you probably noticed an activity doesn't have a default constructor, but uses an onCreate(Bundle savedInstanceState) method. This means you should pass your information using this Bundles, or use something like SharedPreferences / SQLite. Since SharedPreferences / SQLite is a bit overkill for this in my opinion, you can add the object upon creating an intent.
Intent intent = new Intent();
intent.putExtra("name", parcelableObject);
If you want to pass a custom object you have to implement the Parcelable interface, this is pretty straightforward since you can basically auto generate all code for this in Android studio (just hit alt-enter a few times). For more information you can check out the following link.
https://developer.android.com/reference/android/os/Parcelable
In the receiving activity you can do the following:
Bundle bundle = getIntent().getExtras();
Object object = bundle.getObject("name"); //Don't forget to cast!
I trying to create a ListView in AndroidStudio with value "nome". I created a list and a adapter for this, but my application not recognize variable "services".
This is my activity code
public class MainActivity extends AppCompatActivity {
private String service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_item1);
ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services); <-- in this line
listView.setAdapter(servicesAdapter);
}
private List<Services> gerarServices(){
List<Services> services = new ArrayList<Services>();
services.add(criarServices("Home"));
services.add(criarServices("Delivery"));
return services;
}
private Services criarServices(String nome){
Services service = new Services(nome);
return service;
}
}
Any suggestion? Thank's in advance!
The services variable is not in the scope of your onCreate method. As mentioned by #Code-Apprentice, you might want to find out more about scope of local variables.
So, what you might want to do is to invoke the gerarServices() method in the onCreate method and assign it to a local variable which will then be passed to the ArrayAdapter. Like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_item1);
List<Services> services = gerarServices();
ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services);
listView.setAdapter(servicesAdapter);
}
or
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_item1);
ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, gerarServices());
listView.setAdapter(servicesAdapter);
}
Hope it helps!
In your code, I dont see any mehod for declaring and initializing services.
But gerarServices() return a list of Services. So I guess you have to do above action(s) before using any variables or instances of class, etc.
Like so,
ListView listView = (ListView) findViewById(R.id.list_item1);
// Add this line of code
List<Services> services = gerarServices();
ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services);
Hope this help.
I have a spinner that i populate with an array list from a resource. I have it populated and the code is compiling correctly. My problem now is that I can't seem to figure out how to access the spinner from my main class. For instance, I have my class "CreateExerciseActivity" where I have my method "createExercise"
public class CreateExerciseActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_create_exercise_activiy);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void createExercise(View view){
EditText name = (EditText) findViewById(R.id.editText1);
DataBaseWrapper dbHandler = new DataBaseWrapper(this);
Exercise exercise = new Exercise(name.getText().toString(), category);
dbHandler.addExercise(exercise);
name.setText("");
}
}
And below is the code for my fragment where I initialize and populate the spinner
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
private Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater
.inflate(R.layout.fragment_create_exercise_activiy,
container, false);
loadSpinnerCategories(rootView);
return rootView;
}
private void loadSpinnerCategories(View view){
spinner = (Spinner) view.findViewById(R.id.category_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(), R.array.categories,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
I want to know how I can access my spinner from the first class "CreateExerciseActivity" now that it has been populated from the fragment. I want to be able to take the option someone has selected and enter it into the database along with exercise name in the method "createExercise".
There's many ways of doing this.
Usually, you want to respond to some type of event in the fragment. For example, a button is pressed. From the fragment you can call the activity like this:
CreateExerciseActivity activity = (CreateExerciseActivity) getActivity();
activity.createExercise(....);
A better way would be for the activity to implement an interface IOptionSelectedListener for example. The interface could have a method called OnOptionSelected(value). Then you could do:
IOptionSelectedListener listener = (IOptionSelectedListener) getActivity();
listener.OnOptionSelected(....);
You could also pass the activity reference to the newInstance() method of the fragment, instead of calling getActivity().
The activity could also have a reference to the fragment and call a method on the fragment to get the actual value of the spinner.