Android Studio error: class, interface, enum expected - java

Starting with line 34 I am getting error: class, interface, enum expected. This is a simple percent calculator app as my introduction to android studio. I have tried fix all all the formatting suggestion I read for other people getting the same error but I had no luck. I would appreciate any suggestions or ideas on how to fix that or also if you have any basic app ideas I would love to hear them.
package com.example.bheue.percenttutorial;
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.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView totalTextView;
EditText percentageText;
EditText numberText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
};
TextView totalTextView = (TextView) findViewById(R.id.totalText);
percentageText = (EditText) findViewById(R.id.percentageText);
numberText = (EditText) findViewById(R.id.numberText);
Button calcButton = (Button) findViewById(R.id.percentText);
calcButton.setOnClickListener(new view.OnClickListener())
#Override
public void onClick(view view){
float percentage = Float.parseFloat(percentageText.getText().toString());
float dec = percentage / 100;
float total = dec * Float.parseFloat(numberText.getText().toString());
totalTextView.setText(Float.toString(total));
}
#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);
}

This is what your code should be:
package com.example.bheue.percenttutorial;
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.EditText;
import android.widget.TextView;
import com.uplication.hamza.helpinghands.R;
public class MainActivity extends AppCompatActivity {
TextView totalTextView;
EditText percentageText;
EditText numberText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView totalTextView = (TextView) findViewById(R.id.totalText);
percentageText = (EditText) findViewById(R.id.percentageText);
numberText = (EditText) findViewById(R.id.numberText);
Button calcButton = (Button) findViewById(R.id.percentText);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float percentage = Float.parseFloat(percentageText.getText().toString());
float dec = percentage / 100;
float total = dec * Float.parseFloat(numberText.getText().toString());
totalTextView.setText(Float.toString(total));
}
});
}
#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);
}
}
Did you copy this code from somewhere and had problems in pasting?

Related

Android Text input always give me NaN value

I can not figure out why this code output always show NaN. Is there anybody who can help me figure out where I did mistake?
package com.example.user.solar_calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Context;
import android.content.Intent;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class efficiency extends Activity {
Button button;
EditText efficiency;
EditText vol;
String e,v;
double e1,wat,v1, AC_Load_in_ampere_hour_calculation,dc;
double load,load_vol,Total_Daily_load,lol;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_efficiency);
initControls();
addListenerOnButton();
}
public void initControls() {
efficiency=(EditText)findViewById(R.id.editText1);
vol=(EditText)findViewById(R.id.editText2);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
e1=Double.parseDouble(efficiency.getText().toString()); // Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
e1=1;
}
try {
v1=Double.parseDouble(vol.getText().toString());// Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
v1=1;
}
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String value = extras.getString("FOUR");
load=Double.parseDouble(value.toString());
}
wat=load_vol*(1+.1);
AC_Load_in_ampere_hour_calculation = (load)/( v1* (e1/100));
Total_Daily_load=AC_Load_in_ampere_hour_calculation+dc;
Intent i = new Intent(efficiency.this, calculation.class);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("seven", String.valueOf(AC_Load_in_ampere_hour_calculation));
bundle.putString("eight", String.valueOf(Total_Daily_load));
bundle.putString("nine", String.valueOf(dc));
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
}
});
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button);
}
#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 the line who cause problem is AC_Load_in_ampere_hour_calculation = (load)/( v1* (e1/100));
Because if v1 = 0 it will be impossible.

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");
}
}

Unable to get host address in Android

I am creating an Android application. Here I need to get the IP address of the Android device. Below is my MainActivity code,
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
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.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
public class MainActivity extends AppCompatActivity {
Button button;
TextView txtView;
public static Context context = MyApplication.getAppContext();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
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();
}
});
}
public void addListenerOnButton() {
button = (Button) findViewById(R.id.button_ip);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
ipAddress = Integer.reverseBytes(ipAddress);
}
byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
String ipAddressString;
try {
ipAddressString = InetAddress.getByAddress(ipByteArray)
.getHostAddress();
} catch (UnknownHostException ex) {
Log.e("WI-Resource", "Unable to get host address.");
ipAddressString = null;
}
System.out.println(ipAddress);
//txtView.setText(ipAddress);
}
});
}
#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);
}
}
After creating the WiFi hotspot in my device, I started the application, then it gives following exception,
Unable to get host address
So please anyone can help me to solve this problem?
try this Android: How to Know an IP Address is a Wifi IP Address?
o can read more here: https://developer.android.com/reference/java/net/NetworkInterface.html

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