My app keeps crashing when i open it - java

I had added 2 spinners to my cricket scoring app and there are no compiler errors however my app keeps crashing on start. It was working fine when I added the first spinner but the moment I added the second spinner the app started to crash. Please help.
package com.example.visha.cricketcounter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner spinner;
private Spinner spinner2;
EditText text = (EditText)findViewById(R.id.editText);
String value = text.getText().toString();
EditText text2 = (EditText)findViewById(R.id.editText2);
String value2 = text2.getText().toString();
private static final String[]paths = {"15", "20", "30"};
private final String[]paths1 = {value, value2};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item,paths);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item,paths1);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
switch (position) {
case 0:
// Whatever you want to happen when the first item gets selected
break;
case 1:
// Whatever you want to happen when the second item gets selected
break;
case 2:
// Whatever you want to happen when the thrid item gets selected
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
#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);
}
}

You should implement OnItemSelectedListener to access the onItemSelected method.

you are passing this in method like setOnItemSelectedListener(this) means you are passing reference of listener as class but you don't implemented listener, impalement OnItemSelectedListener like following and try,
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener

Your activity must implement the interface onItemSelectedListener and override the method OnNothingSelected
Example:
public class MainActivity extends AppCompatActivity implements onItemSelectedListener{
....
Then with the Mouse Cursor in the Main Activity let your IDE auto insert all the missing method implementations

Related

Issue with a simple app

I'm new in coding, and I was trying to make a simple app that make a subtraction from 2 variable, but when I click the button to calculate, the app crashes... Can someone help me finding the problem in the code? (Android Studio)
Here's the code:
package apps.ste.resto;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import static apps.ste.resto.R.id.risultato;
public class MainActivity extends AppCompatActivity {
TextView importo;
TextView conto;
TextView risultato;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
TextView risultato = (TextView) findViewById(R.id.textView);
TextView importo = (TextView) findViewById(R.id.editText);
TextView conto = (TextView) findViewById(R.id.editText2);
Button bottone = (Button) findViewById(R.id.button);
bottone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result();
}
});
}
public void result(){
float result = Float.parseFloat(importo.getText().toString()) - Float.parseFloat(conto.getText().toString());
risultato.setText(Float.toString(result));
}
#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);
}
I think you are getting null value for getText()..
SO you can try this :
public void result(){
boolean digitsOnly1 = TextUtils.isDigitsOnly(importo.getText()+"");
boolean digitsOnly2 = TextUtils.isDigitsOnly(conto.getText()+"");
if(digitsOnly1 && digitsOnly2){
float result = Float.parseFloat(importo.getText().toString()) - Float.parseFloat(conto.getText().toString());
risultato.setText(result+""));
}else{
risultato.setText("Please provide inputs");
}
}

Updating an ArrayAdapter from inside an onClickListener in getView

I am making a shopping cart app where users can add and remove items from the cart. When a user views their cart, a list of items they have added appear. This list is made using an ArrayAdapter. Each row contains a remove button where the user can remove the item from the cart. I have successfully been able to remove the item from the Cart object. However, I am running into trouble when it comes to updating the screen when the user clicks the remove button. I have heard of the notifydatasetchanged() method for adapters, but I am not sure how to implement that from inside the OnClickListener in getView. Here is the code:
CartScreen.java
package com.livilatenight.livilatenight;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class CartScreen extends ActionBarActivity {
ListView items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart_screen);
final ParseUser current = ParseUser.getCurrentUser();
try{
Cart userCart = (Cart) current.fetchIfNeeded().get("cart");
String[] itemNames = userCart.getItems();
String[] itemPrices = userCart.getPrices();
int[] quantities = userCart.getQuantities();
Integer[] itemPictures = userCart.getPictures();
CartListAdapter adapter = new CartListAdapter(CartScreen.this, itemNames,itemPrices,quantities,itemPictures);
items = (ListView) findViewById(R.id.listView);
items.setAdapter(adapter);
}catch(ParseException e){
Toast.makeText(CartScreen.this, e.toString(),Toast.LENGTH_LONG).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_cart_screen, 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);
}
}
CartListAdapter.java
package com.livilatenight.livilatenight;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseUser;
public class CartListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] items;
private final String[] prices;
private final int[] quantities;
private final Integer[] pictures;
public CartListAdapter(Activity context, String[] itemnames, String[] prices, int[] quantities, Integer[] pictures) {
super(context, R.layout.item_list, itemnames);
this.context=context;
this.items=itemnames;
this.prices=prices;
this.quantities=quantities;
this.pictures=pictures;
}
public View getView(final int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.cart_item, null,true);
TextView itemName = (TextView) rowView.findViewById(R.id.tvItemName);
TextView itemPrice = (TextView) rowView.findViewById(R.id.tvPrice);
ImageView itemPicture = (ImageView) rowView.findViewById(R.id.ivItemPicture);
View blankView = (View) rowView.findViewById(R.id.blankView);
Button removeCart = (Button) rowView.findViewById(R.id.btnRemoveCart);
final Spinner spinner = (Spinner) rowView.findViewById(R.id.spinnerQty);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.spinner_numbers, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(quantities[position]-1);
itemName.setText(items[position]);
itemPrice.setText(prices[position]);
itemPicture.setImageResource(pictures[position]);
removeCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseUser current = ParseUser.getCurrentUser();
int quantity = spinner.getSelectedItemPosition()+1;
Cart userCart = (Cart) current.get("cart");
boolean success = userCart.removeFromCart(items[position]);
if(success){
Toast.makeText(getContext(), "Removed from Cart", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getContext(), "Item is already in your shopping cart", Toast.LENGTH_LONG).show();
}
current.saveInBackground();
}
});
return rowView;
};
}
I want to update the cart list when a user clicks the removeCart button. How could I do this?
UPDATE
I did a workaround where I just set a new adapter each time an item is removed. Not what I wanted to do but it works so I'll keep it the way it is.
try this
if (success) {
Toast.makeText(getContext(), "Removed from Cart", Toast.LENGTH_LONG).show();
final String s = items[position];
List<String> list = new ArrayList<String>(Arrays.asList(items));
list.remove(s);
items = list.toArray(array);
this.notifyDataSetChanged()
}
In your custom adapter call this.notifyDataSetChanged(); where you are performing delete functionality and deleting that element from arrayList which is set to that adapter.
You have to remove that record from the ArrayList too that you have set to your adapter if you know which record it is you can use ArrayList.remove(index); and then use notifyDataSetChanged();
EDIT:
Go to your adapter and add a method delete();
public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}
In your onClick(); method add this:
delete(getPosition());
Here is the solution that worked in my case.
In your CartListAdapter override remove method of Array Adapter.
#Override
public void remove(String var){
// Call your utility methods you defined to delete the item
// Notify ListView that their is a change
notifyDataSetChanged();
}
Make the following changes in your Click Listener
removeCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call this.remove(var) with String you want to delete
}
});
notifyDataSetChanged() works only in case of add(), insert(), remove(), and clear(). Read this
HTH

How to change layout & class with arraylist

I want to make my class and layout change when I click on specific items. For example, if I click "physical" from the array list I want it to open up the physical java class and the physical xml layout. How do i do this? As you can see down below I have already tried with the View view and switch/case.
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v4.app.FragmentActivity;
import java.util.List;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private ListView listView;
private String[] planets;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
drawerLayout=(DrawerLayout)findViewById(R.id.drawerLayout);
planets=getResources().getStringArray(R.array.planets);
listView=(ListView) findViewById(R.id.drawerList);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, planets));
listView.setOnItemClickListener(this);
}
#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
return super.onOptionsItemSelected(item);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, planets[position] + " was selected", Toast.LENGTH_LONG).show();
selectItem(position);
selectItem2(view);
}
public void selectItem(int position) {
listView.setItemChecked(position, true);
setTitle(planets[position]);}
public void selectItem2 (View view){
switch (view.getId()) {
case 0:
Intent intent = new Intent(view.getContext(), physical_fragment.class);
startActivityForResult(intent, 0);}}
public void setTitle(String title){
getSupportActionBar().setTitle(title);
}
}
You probably don't want compare the id of the View since all of the Views in your list will use android.R.layout.simple_list_item_1 they will all have the same id.
You may consider passing the position and comparing that.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, planets[position] + " was selected", Toast.LENGTH_LONG).show();
selectItem(position);
selectItem2(position);
}
public void selectItem2 (int position) {
switch (position) {
case 0:
Intent intent = new Intent(MainActivity .this, physical_fragment.class);
startActivityForResult(intent, 0);
break;
}
}
Something like that should get you started. However, you may eventually want to check the content of the item selected such as the the actual position of the string resource then get that id in case you decide to switch around the list items or modify them in some other way.

Unable To Create CardView Fragment

I have no idea on what is wrong with my code.
My application is using navigation drawer. There are 4 different fragments and one of it is a cardview fragment which I have converted earlier from activity to fragment.
The cardview fragment is being underlined red which shows error that would not able to be compiled. Kindly refer the attached pictures.
If I were to accept the proposed solutions by the Android Studio,it will just solve the CardViewFragment and new problem would occur at the other 3 fragments.
And this is both my main activity and the cardview fragment.
MainActivity.java
package info.androidhive.materialdesign.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import info.androidhive.materialdesign.R;
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
case 3:
fragment = new CardViewFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
CardViewFragment.java
package info.androidhive.materialdesign.activity;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.util.ArrayList;
import info.androidhive.materialdesign.R;
public class CardViewFragment extends Fragment {
private Toolbar toolbar;
private RecyclerView recyclerView;
private CardView cardView;
private ArrayList<FeddProperties> os_versions;
private RecyclerView.Adapter mAdapter;
// private RecyclerView.LayoutManager mLayoutManager;
private LinearLayout llLayout;
private FragmentActivity faActivity;
#Override
/*protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initContrls();
}*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
faActivity=(FragmentActivity)
super.getActivity();
llLayout=(LinearLayout)
inflater.inflate(R.layout.activity_main, container, false);
initContrls();
return llLayout;
}
private void initContrls() {
//toolbar = (Toolbar) findViewById(R.id.toolbar);
// cardView = (CardView) findViewById(R.id.cardList);
recyclerView = (RecyclerView) llLayout.findViewById(R.id.my_recycler_view);
/*if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Versions");
}*/
final String[] versions = {"Alpha", "Beta", "CupCake", "Donut",
"Eclair", "Froyo", "Gingerbread", "Honeycomb",
"Ice Cream Sandwitch", "JellyBean", "KitKat", "LollyPop"};
final int[] icons = {R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.donut, R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.icecream_sandwhich, R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop};
os_versions = new ArrayList<FeddProperties>();
for (int i = 0; i < versions.length; i++) {
FeddProperties feed = new FeddProperties();
feed.setTitle(versions[i]);
feed.setThumbnail(icons[i]);
os_versions.add(feed);
}
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Grid View
// recyclerView.setLayoutManager(new GridLayoutManager(this,2,1,false));
//StaggeredGridView
// recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,1));
// create an Object for Adapter
mAdapter = new CardViewDataAdapter(os_versions);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(mAdapter);
}
/* #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);
}*/
}
In MainActivity.java, you declared
import android.support.v4.app.Fragment
Import the same type of Fragment in CardViewFragment.java instead of
import android.app.Fragment;
so that it's clear that the same type of Fragment is being used in both pieces of code.

Can't get To Do Activity to work in a fragment

sorry I'm fairly new to android so I seem to keep getting stuck on the simplest things.
I had two projects I had completed for a class. One was a simple To Do List and another that allowed different fragments to be used depending on whether you are in portrait or landscape mode. both worked but when trying to combine the two I get an error when put my To Do activity in the fragment if I extend Fragment (findByViews and setContentView dont work.
I can replace Fragment with FragmentActivity which fixes this but then my MainActivity.java's fragmentTransaction.replace(android.R.id.content, pm_fragment); gets an error saying:
"replace (int, android.app.Fragment) in FragmentTransaction cannot be applied to (int, com.android.MyFragmentsTodo.PM_Fragment)"
Can anyone tell me what I can do to make this work? I have a test tomorrow and I'm worried the lecturer might want us to mix an activity with fragments.
Any help would be greatly appreciated.
MainActivity.java
package com.android.myfragmentstodo;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//check device orientation and act upon it
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
// If orientation is landscape then
LM_Fragment ls_fragment = new LM_Fragment();
fragmentTransaction.replace(android.R.id.content, ls_fragment);
}else{
// If orientation is portrait then
PM_Fragment pm_fragment = new PM_Fragment();
fragmentTransaction.replace(android.R.id.content, pm_fragment);
}
//apply (commit) the changes
fragmentTransaction.commit();
}
#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);
}
}
PM_Fragment.java
package com.android.myfragmentstodo;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Malan on 4/20/2015.
*/
public class PM_Fragment extends android.support.v4.app.Fragment {
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.todoItems);
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
Button button = (Button) findViewById(R.id.btnAddItem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
Toast toast = Toast.makeText(getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
toast.show();
}
});
setupListViewListener();
return inflater.inflate(R.layout.lm_fragment, container, false);
}
private void setupListViewListener() {
listView.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> av,
View item, int pos, long id){
items.remove(pos);
adapter.notifyDataSetChanged();
return true;
}
});
}
#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 AddItem(View view) {
EditText editText = (EditText) findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
}
}
OK i have figured out how to fix the issue. One must keep extending Fragment but when doing using findViewById one must use:
rootView = inflater.inflate(R.layout.pm_fragment, container, false);
and then precede all findViewById's with rootView like this:
listView = (ListView) rootView.findViewById(R.id.todoItems);
Whenever "this" is used instead use "getActivity()" for example:
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
when using getApplicationContext you must use getActivity().getApplicationContext() for example:
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
in the end my PM_Fragment is altered to look like this:
PM_Fragment.java
package com.android.myfragmentstodo;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Malan on 4/20/2015.
*/
public class PM_Fragment extends Fragment {
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
private ListView listView;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState){
rootView = inflater.inflate(R.layout.pm_fragment, container, false);
listView = (ListView) rootView.findViewById(R.id.todoItems);
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
Button button = (Button) rootView.findViewById(R.id.btnAddItem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) rootView.findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
toast.show();
}
});
setupListViewListener();
return rootView;
}
private void setupListViewListener() {
listView.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> av,
View item, int pos, long id){
items.remove(pos);
adapter.notifyDataSetChanged();
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 AddItem(View view) {
EditText editText = (EditText) rootView.findViewById(R.id.todoEdit);
String itemText = editText.getText().toString();
adapter.add(itemText);
editText.setText("");
}
}

Categories