i wrote a toDO list for my android class. It totally works , but now i want to display the todo list on a fragment ( so it can be its on tab). but when i tried making the fragment , i get a weird error when i try to run it. apparently the error comes from my main activity . so the way i have it set up is that, my main activity has a button that opens the fragment that has all the TOdolist stuff in it. but when i run it on my phone i get a unfortunately TodoList ha stopped as soon as it runs. the error is get is
06-10 22:21:51.284 5302-5302/com.example.mike.todolist D/AbsListView﹕ Get MotionRecognitionManager
06-10 22:21:51.304 5302-5302/com.example.mike.todolist D/AndroidRuntime﹕ Shutting down VM
06-10 22:21:51.304 5302-5302/com.example.mike.todolist W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x417c2898)
06-10 22:21:51.314 5302-5302/com.example.mike.todolist E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.mike.todolist.ToDoFragment.onCreateView(ToDoFragment.java:38)
at android.app.Fragment.performCreateView(Fragment.java:1699)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1075)
at android.app.BackStackRecord.run(BackStackRecord.java:682)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1455)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
my main activity look like
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.todo_main_activity);
super.onCreate(savedInstanceState);
Button button1 = (Button) findViewById(R.id.fragButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction
=fragmentTransaction=fragmentManager.beginTransaction();
ToDoFragment fragment = new ToDoFragment();
fragmentTransaction.add(R.id.mainLL, fragment);
fragmentTransaction.commit();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return true;
}
}
My main activity xml is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:id="#+id/mainLL"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="frag"
android:id="#+id/fragButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="fragButtonClick"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Fragment.java
package com.example.mike.todolist;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.example.mike.todolist.db.Contract;
import com.example.mike.todolist.db.DBHelper;
/**
* Created by mike on 6/10/15.
*/
public class ToDoFragment extends ListFragment {
public ListAdapter listAdapter;
public DBHelper helper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragmentlayout, container, false);
// Inflate the layout for this fragment
update();
Button doneButton = (Button)view.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
Contract.TABLE_NAME,
Contract.Columns.TASK,
task);
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
update();
}
});
Button addButton = (Button)view.findViewById(R.id.AddButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
switch (R.id.add_task) {
case R.id.add_task:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add a task");
builder.setMessage("What would you like to do?");
final EditText input = new EditText(getActivity());
builder.setView(input);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = input.getText().toString();
helper = new DBHelper(getActivity());
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.clear();
cv.put(Contract.Columns.TASK, task);
db.insertWithOnConflict(Contract.TABLE_NAME, null, cv, SQLiteDatabase.CONFLICT_IGNORE);
update();
}
});
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
}
});
return view;
}
private void update() {
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(Contract.TABLE_NAME,
new String[]{Contract.Columns._ID, Contract.Columns.TASK},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.task_view,
cursor,
new String[]{Contract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
this.setListAdapter(listAdapter);
}
}
and this is my fragmentlayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:id="#+id/mainLL"
android:layout_height="fill_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/list"
android:layout_weight="1"
android:layout_margin="5dp"
android:background="#color/grey"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Task"
android:id="#+id/AddButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="AddButtonClick"
android:layout_gravity="center_horizontal" />
</LinearLayout>
taskview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taskTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="20dp"
android:textColor="#color/black"
android:typeface="sans"
android:layout_toLeftOf="#+id/doneButton"
android:layout_alignBottom="#+id/doneButton"
android:gravity="center_vertical"
android:textStyle="bold"
android:layout_alignTop="#+id/doneButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:id="#+id/doneButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="DoneButtonClick"
/>
</RelativeLayout>
According to android developers official website (HERE)
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "#android:id/list" (or list if it's in code)
for example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>
So either add a listview to your list activity xml or if you don't need a list view in your activity then simply use FragmentActivity to hold fragments.There is no point in using ListActivity unless it holds a ListView.
Your class is extending to a ListActivity which requires the ListView element in the xml. Your purpose be best served by extending your MainActivity class to Activity and fragments (if any) to Fragments class....
Add an list view to your xml with id android.R.id.list
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
add this xml to your layout
use Activity or FragmentActivity instead of ListActivity
if you want to use ListActivity see here once. you can use ListActivity without setting content view (setContentView()). you can directly setAdapter. or else use your own layout having one ListView with id as "#android:id/list"
EDIT :
public void onClick(View arg0) {
TextView taskTextView = (TextView) view.findViewById(R.id.taskTextView);//directly use 'view' if 'R.id.taskTextView'it present in 'view'
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
Contract.TABLE_NAME,
Contract.Columns.TASK,
task);
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
update();
}
Related
This is my first attempt to develop an android application.
I have a MainActivity with ConstraintLayout that has BottomNavigationView. Whenever the first navigation item is selected, I want to display a list of category (displayed in a fragment), then whenever this category is selected, another list will be displayed for items related to that particular category (in another fragment).
I have read in (Android - fragment .replace() doesn't replace content - puts it on top) it states that "static fragments written in XML are unable to be replaced, it has to be in a fragment container", how does it look like?
I tried to create my fragment container, but there is something wrong when I try to get the ListView (grand child of the container)
categoriesListView = getView().findViewById(R.id.categoriesList);
returns null.
MainActivity
package com.alsowaygh.getitdone.view.main;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.services.CategoriesListFragment;
import com.alsowaygh.getitdone.view.services.OnCategorySelectedListener;
import com.alsowaygh.getitdone.view.services.ServicesListFragment;
public class MainActivity extends AppCompatActivity implements OnCategorySelectedListener {
private static final String TAG = "MainActivity";
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_services:
// mTextMessage.setText(R.string.title_services);
CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
fragmentTransaction.add(R.id.container, categoriesListFragment);
fragmentTransaction.commit();
return true;
case R.id.navigation_bookings:
// mTextMessage.setText(R.string.title_bookings);
return true;
case R.id.navigation_chats:
// mTextMessage.setText(R.string.title_chats);
return true;
case R.id.navigation_settings:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
}
#Override
public void onCategorySelected(String category) {
Log.w(TAG, "Successfully created CategoryListFragment!");
}
}
activity_main layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.main.MainActivity">
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
Fragment
package com.alsowaygh.getitdone.view.services;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.main.MainActivity;
public class CategoriesListFragment extends Fragment {
private ListView categoriesListView;
OnCategorySelectedListener categoryListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
//initializing root view first to refer to it
View rootView = inflater.inflate(R.layout.activity_main, container, false);
//initializing ListView
categoriesListView = getView().findViewById(R.id.categoriesList);
//categories list
final String[] categories = {"first category", "second category", "third category", "Fourth category"};
//initializing and adding categories strings to the addapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this.getContext(),
R.layout.category_textview);
for (String c : categories) {
arrayAdapter.add(c);
}
categoriesListView.setAdapter(arrayAdapter);
//implement onListItemClick
categoriesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//retrieve string from categories list at clicked position
categoryListener.onCategorySelected(categories[position]);
}
});
return rootView;
}
#Override //to fource container activity to implement the OnCategorySelectedListener
public void onAttach(Context context) {
super.onAttach(context);
try{
categoryListener = (OnCategorySelectedListener) context;
}catch(ClassCastException e){
throw new ClassCastException(context.toString() + "must implement OnCategorySelectedListener");
}
}
}
fragments container
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/categories_list_fragment"
android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<ListView
android:id="#+id/categoriesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
</fragment>
</FrameLayout>
Your help will be much appreciated.
You need to add the FrameLayout container within the layout file of the MainActivity(activity_main), onclick of the buttons in BottomNavigationView replace with the fragment. In this way you have a Activity and the fragments are shown within the activity, on click of each menu item you can invoke to replace it with the fragments.
This should resolve your problem.
You need to change the layout as below in activity_main.xml.
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.main.MainActivity">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
In the MainActivity code, you need to change as below:
case R.id.navigation_services:
// mTextMessage.setText(R.string.title_services);
CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
fragmentTransaction.replace(R.id.frame, categoriesListFragment);
fragmentTransaction.commit();
return true;
In the fragment layout file change to LinearLayout:
<LinearLayout
android:id="#+id/categories_list_fragment"
android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<ListView
android:id="#+id/categoriesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
</LinearLayout>
EDIT
In the fragment code, change the layout to the name of the fragment layout file(R.layout.fragment_layout_name).
View rootView = inflater.inflate(R.layout.fragment_layout_name, container, false);
//initializing ListView
categoriesListView = rootView.findViewById(R.id.categoriesList);
The app crashes as soon as any of the list Activities are launched:
NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter' on a null object reference
My instructor says its happening because the layouts haven't been configured correctly. Right now, the list_item is being inflated as the Activity layout. Please create a separate layout, such as activity_list and add the ListView element there to be referenced in the individual Activity files
Here's the code
MainActivity
package com.example.tourguide;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button event = (Button) findViewById(R.id.events);
Button mall = (Button) findViewById(R.id.malls);
Button resturant = (Button) findViewById(R.id.resturants);
Button university = (Button) findViewById(R.id.uinversities);
event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent event = new Intent(MainActivity.this, events.class);
startActivity(event); }
});
mall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mall = new Intent(MainActivity.this, malls.class);
startActivity(mall);
}
});
resturant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent resturant = new Intent(MainActivity.this, resturants.class);
startActivity(resturant);
}
});
university.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent university = new Intent(MainActivity.this, universities.class);
startActivity(university);
}
});
}}
WordAdapter.java
package com.example.tourguide;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<listitem> {
public WordAdapter(Activity context, ArrayList<listitem> listitems) {
super(context, 0, listitems);
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
listitem currentItem = getItem(position);
TextView name = (TextView) listItemView.findViewById(R.id.text1);
name.setText(currentItem.getName());
ImageView image = (ImageView) listItemView.findViewById(R.id.image1);
image.setImageResource(currentItem.getImage());
TextView dist = (TextView) listItemView.findViewById(R.id.text2);
dist.setText(currentItem.getDist());
TextView price = (TextView) listItemView.findViewById(R.id.text2);
price.setText(currentItem.getPrice());
return listItemView;
}
}
listitem.java
package com.example.tourguide;
import android.widget.ImageView;
public class listitem {
private String name="";
private int image;
private String dist="";
private String price="";
public listitem(String namea, int imagea, String dista, String pricea){
name = namea;
imagea = image;
dist= dista;
price=pricea;
}
/*********** Set Methods ******************/
public void setName(String name)
{
this.name = name;
}
public void setImage(int image)
{
this.image = image;
}
public void setDist(String dist)
{
this.dist = dist;
}
public void setPrice(String price)
{
this.price = price;
}
/*********** Get Methods ****************/
public String getName()
{
return this.name;
}
public int getImage()
{
return this.image;
}
public String getDist()
{
return this.dist;
}
public String getPrice()
{
return this.price;
}
}
Univerisities.java
package com.example.tourguide;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class universities extends Activity {
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.list_item);
ArrayList<listitem> listitemArrayList = new ArrayList<listitem>();
listitemArrayList.add(new listitem("Prince Sultan University", R.drawable.u1, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("Princess Nourah University", R.drawable.u2, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("King Saud University", R.drawable.u3, "AlNarjes Dist", "$"));
WordAdapter adapter = new WordAdapter(this, listitemArrayList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.tourguide.MainActivity"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="29sp"
android:textColor="#3DC195"
android:textAlignment="center"
android:text="Tour Guide App" />
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#6AA13F"
android:textSize="18sp"
android:text="Tour Guide App is designed to help you discover Riyadh city sightseeings including events, malls, resturants and universities.the app will be developed periodically to add more features... stay tuned" />
<Button
android:id="#+id/events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:onClick="onClickEvent"/>
<Button
android:id="#+id/malls"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Malls"
android:onClick="onClickMall"/>
<Button
android:id="#+id/resturants"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resturants"
android:onClick="onClickRest"/>
<Button
android:id="#+id/uinversities"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Universities"
android:onClick="onClickUniv"/>
</LinearLayout>
activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/image1"
android:layout_width="163dp"
android:layout_height="96dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_marginTop="30dp"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#DB0BA4"
android:textSize="20sp"
/>
<TextView
android:id="#+id/text2"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#456233"
android:textSize="15sp"
/>
<TextView
android:id="#+id/text3"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#C1B03D"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In the file Univerisities.java you should change your layout file to activity_list.xml.
Line
setContentView(R.layout.list_item);
Must be changed to :
setContentView(R.layout.activity_list);
Bro,
First you are trying to inflate the ListView item into you activity, which is wrong:
Change the setContentView(R.layout.list_item) to setContentView(R.layout.activity_list);
Also please check out the ViewHolder pattern for ListView's since the your adapter's getView method should be improved by that to make scrolling even more smooth:
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
and if no items are appearing in the list, you should also override the getItemCount on adatpterto return the size of the list.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I tried creating a simple app "MemeCrater" which i learned from one of youtube tutorial.but whenever i press the Create button.The App crashes.
This is the error i get.
Error
Process: com.example.iemshekhar.memegenerator, PID: 13118
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.iemshekhar.memegenerator.TopSectionFragment$TopSectionListener.createMeme(java.lang.String, java.lang.String)' on a null object reference
at com.example.iemshekhar.memegenerator.TopSectionFragment.buttonClicked(TopSectionFragment.java:57)
at com.example.iemshekhar.memegenerator.TopSectionFragment$1.onClick(TopSectionFragment.java:49)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10815)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is my main activity java file:
MainActivity.java
package com.example.iemshekhar.memegenerator;
import android.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements TopSectionFragment.TopSectionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void createMeme(String top, String bottom) {
BottomPictureFragment bottmfragment=(BottomPictureFragment)getFragmentManager().findFragmentById(R.id.fragment2);
bottmfragment.setMemeText(top,bottom);
}
#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 my top Fragement java file:
TopSectionFragment.java
package com.example.iemshekhar.memegenerator;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TopSectionFragment extends Fragment {
private static EditText top, bottom;
TopSectionListener activitycommander;
public interface TopSectionListener{
public void createMeme(String top,String bottom);
}
public void onAtttach(Context context)
{
try{
activitycommander=(TopSectionListener)context;
}
catch(ClassCastException e){
throw new ClassCastException(e.getMessage());
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment, container, false);
top = (EditText)view.findViewById(R.id.toptextinput);
bottom = (EditText) view.findViewById(R.id.bottomtextinput);
final Button create = (Button) view.findViewById(R.id.createbutton);
create.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
}
);
return view;
}
public void buttonClicked(View v) {
activitycommander.createMeme(top.getText().toString(),bottom.getText().toString());
}
}
This file is my bottom Fragment java File:
BottomSectionFragment.java
package com.example.iemshekhar.memegenerator;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by IEmShekhar on 6/18/2016.
*/
public class BottomPictureFragment extends Fragment {
public static TextView toptext,bottomtext;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bottom_picture_fragment, container, false);
toptext=(TextView)view.findViewById(R.id.textView1);
bottomtext=(TextView)view.findViewById(R.id.textView2);
return view;
}
public void setMemeText(String top,String bottom){
toptext.setText(top);
bottomtext.setText(bottom);
}
}
These are my XML Files:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:background="#006669"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="290dp"
android:name="com.example.iemshekhar.memegenerator.BottomPictureFragment"
android:id="#+id/fragment2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/bottom_picture_fragment" />
<fragment
android:layout_width="400dp"
android:layout_height="wrap_content"
android:name="com.example.iemshekhar.memegenerator.TopSectionFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/top_section_fragment"
android:layout_above="#+id/fragment2" />
</RelativeLayout>
Top_section_Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:background="#999999">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toptextinput"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:width="300dp"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bottomtextinput"
android:layout_centerHorizontal="true"
android:layout_below="#+id/toptextinput"
android:width="300dp"
android:layout_marginTop="30dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_centerHorizontal="true"
android:text="#string/Create_text"
android:background="#006666"
android:textStyle="bold"
android:id="#+id/createbutton"/>
</RelativeLayout>
Bottom_picture_Fragement.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#drawable/afaque">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/toptext"
android:textStyle="bold"
android:textSize="25sp"
android:background="#ffff"
android:width="400dp"
android:textAlignment="center"
android:id="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/bottomtext"
android:textStyle="bold"
android:textSize="25sp"
android:background="#ffff"
android:width="400dp"
android:textAlignment="center"
android:id="#+id/textView2"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Guessing that you're trying to set the text from editText, You should be accessing the text from your editText in your TopSectionFragment
Replace
//Initialize
`private static TextView top, bottom;`
//onCreateView() Method
top = (TextView) view.findViewById(R.id.textView1);
bottom = (TextView) view.findViewById(R.id.textView2);
with this
//Initialize
`private static EditText top, bottom;`
//onCreateView Method
//onCreateView() Method
top = (EditText) view.findViewById(R.id.toptextinput);
bottom = (EditText) view.findViewById(R.id.bottomtextinput);
in your TopSectionFragment. Hope this will help :)
I want to create a ListView in Fragment but something goes wrong.
In layout listmygroups.xml are three TextViews (trainermygroupslistwhen, trainermygroupslistwhere, trainermygroupslistname).
I try to open fragment with listview(TrainerMyGroups) from another fragment by:
getFragmentManager().beginTransaction().replace(R.id.MainContainer,new TrainerMyGroups()).addToBackStack(null).commit();
TrainerMyGroups.java:
package com.hgyghyfghyu.apkana40;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
/**
* A simple {#link Fragment} subclass.
*/
public class TrainerMyGroups extends Fragment {
ListView listView;
TrainerGroupsAdapter adapter;
String when[]={"tak","ret","sd"};
String where[]={"dsf","sdf","sdfsdf"};
String name[]={"sdfsdf","xcvxcv","xcvxcv"};
public TrainerMyGroups() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_trainer_my_groups, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.trainermygroupslistview);
adapter = new TrainerGroupsAdapter(getContext(),R.layout.list_mygroups);
for(int i=0;i<3;i++){
TrainerGroupsDataProvider dataprovider = new TrainerGroupsDataProvider(when[i],name[i],where[i]);
adapter.add(dataprovider);
}
listView.setAdapter(adapter);
}
}
TrainerGroupsAdapter.java:
package com.hgyghyfghyu.apkana40;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import java.util.ArrayList;
/**
* Created by dd on 2016-04-04.
*/
public class TrainerGroupsAdapter extends ArrayAdapter {
List list = new ArrayList();
public TrainerGroupsAdapter(Context context, int resource) {
super(context, resource);
}
static class Datahandler{
TextView name;
TextView when;
TextView where;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
Datahandler handler;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row= inflater.inflate(R.layout.list_mygroups,parent,false);
handler = new Datahandler();
handler.name = (TextView) row.findViewById(R.id.trainermygroupslistname);
handler.where = (TextView) row.findViewById(R.id.trainermygroupslistwhere);
handler.when = (TextView) row.findViewById(R.id.trainermygroupslistwhen);
row.setTag(handler);
}
else {
handler = (Datahandler)row.getTag();
}
TrainerGroupsDataProvider dataProvider;
dataProvider = (TrainerGroupsDataProvider)this.getItem(position);
handler.name.setText(dataProvider.getName());
handler.when.setText(dataProvider.getWhen());
handler.where.setText(dataProvider.getWhere());
return row;
}
}
and there is error from AndroidMonitor
FATAL EXCEPTION: main
Process: com.hgyghyfghyu.apkana40, PID: 27778
java.lang.NullPointerException
at com.hgyghyfghyu.apkana40.TrainerMyGroups.onCreate(TrainerMyGroups.java:41)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
line 41 from TrainerMyGroups is
listView.setAdapter(adapter);
I am not sure but probably this solution works only in Activity, not in Fragment, How can I change my code to make it workable?
element list xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistwhen"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistname"
android:textStyle="bold"
android:textSize="10sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistwhere"
android:textStyle="bold"
android:textSize="10sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
You should add some data before set the adapter:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.trainermygroupslistview);
adapter = new TrainerGroupsAdapter(getContext(),R.layout.list_mygroups);
for(int i=0;i<3;i++){
TrainerGroupsDataProvider dataprovider = new TrainerGroupsDataProvider(when[i],name[i],where[i]);
adapter.add(dataprovider);
}
listView.setAdapter(adapter);
}
I'm not sure why i am getting this error, it was working before, any help is appreciated. Trying to spawn a new activity upon spinner selection ( I have a working version with a list view inside, I decided to branch off to try a spinner, got pretty far and then got lost trying to figure out this error). It was working perfectly too, so I know that i has to be like 1-5 lines of code or something. Again, any help is appreciated.
Logcat
02-19 23:57:15.980: E/AndroidRuntime(350): FATAL EXCEPTION: main
02-19 23:57:15.980: E/AndroidRuntime(350): java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.jordanmaxportfolio/com.example.jordanmaxportfolio.MainActivity}: java.lang.NullPointerException
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.os.Looper.loop(Looper.java:123)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread.main(ActivityThread.java:3683)
Main Activity
package com.example.jordanmaxportfolio;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity
implements AdapterView.OnItemSelectedListener {
TextView selection;
ListView list;
Spinner spin = (Spinner) findViewById(R.id.spinner2);
public final static String exID="com.example.portfolio.MainActivity";
static final String[] items = new String[] {
"36-2510 Game Engine Scripting I",
"36-2551 C++ I",
"36-3210 Game AI Programming",
"36-3405 Authoring Interactive Media I & II"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listView1);
String[] items = getResources().getStringArray(R.array.Classes);
list.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,items));
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int postion, long id){
Intent i =new Intent(MainActivity.this,ClassPage.class);
i.putExtra(exID, String.valueOf(id));
startActivity(i);
}
});
selection = (TextView) findViewById(R.id.textView1);
Spinner spin = (Spinner) findViewById(R.id.spinner2);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
items);
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
selection.setText(items[position]);
Intent i =new Intent(MainActivity.this,ClassPage.class);
i.putExtra(exID, String.valueOf(position));
startActivity(i);
}
/*spin.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
Intent i =new Intent(MainActivity.this,ClassPage.class);
i.putExtra(exID, String.valueOf(id));
startActivity(i);
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
});*/
/* example I saw online, however not quite right */
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
selection.setText("");
}
}
ClassPage
package com.example.jordanmaxportfolio;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
public class ClassPage extends Activity {
private TextView passedView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class);
String passedVar = getIntent().getStringExtra(MainActivity.exID);
passedView = (TextView)findViewById(R.id.tv1);
//passedView.setText("You have clicked item id: "+passedVar);
if(passedVar.equals("0"))
{
passedView.setText("YAYY");
}
if(passedVar.equals("1"))
{
passedView.setText("Game Engine Scripting I");
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.asteroids);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText("Using C# and Unity, I created a remake of the classic 'Asteroids!'. Dynamic difficulty level is the next addition.");
}
else if(passedVar.equals("2"))
{
passedView.setText("C++ I");
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.poker);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText("Console GUI C++ Texas Hole 'Em Poker created by Neil Inglese and Jordan Max. Basic concept of game was to eliminate cursors. The game was completed, however we are re-doing it for our C++ II class to make it into the Xbox Live and Windows Store.");
}
else if(passedVar.equals("3"))
{
passedView.setText("Game AI Programming");
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.game);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText("Currently enrolled in this class, we are learning about FSM's and C++ data structures such as stacks, vectors and queues. ");
}
else
{
passedView.setText("Authoring Interactive Media I & II");
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.p);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText("Learned basic skills for HTML and CSS. Also divulged into HTML5, PHP, jQuery, and Javascript for web programming. Created my portfolio website based off knowledge learned.");
}
Button btn1 = (Button)findViewById(R.id.button1);
// Show the Up button in the action bar.
setupActionBar();
}
public void btnClicked(View view){
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(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.class_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
acitvity_class.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ClassPage" >
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="#string/hello_world" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_alignLeft="#+id/tv1"
android:layout_alignRight="#+id/tv1"
android:layout_below="#+id/tv1"
android:layout_marginTop="46dp"
android:maxHeight="500dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignParentRight="true"
android:layout_below="#+id/imageView1"
android:layout_marginLeft="21dp"
android:layout_marginTop="60dp"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tv2"
android:layout_below="#+id/tv2"
android:layout_marginTop="20dp"
android:onClick="btnClicked"
android:text="Go Back" />
</RelativeLayout>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner1" >
</ListView>
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="67dp"
android:layout_toLeftOf="#+id/listView1" />
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="#string/hello" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginLeft="57dp" />
</RelativeLayout>
Put this
Spinner spin = (Spinner) findViewById(R.id.spinner2);
Inside your onCreate() after setContentView(R.layout.activity_main);
add this
Spinner spin=(Spinner)findViewById(R.id.spinner2);
in your mainactivity.
Try this..
Do this inside OnCreate after setContentView(R.layout.activity_main); in MainActivity
Spinner spin = (Spinner) findViewById(R.id.spinner2);
OR
Remove Spinner spin = (Spinner) findViewById(R.id.spinner2); from Global variable
You are attempting to initialize the class member spin with a call to findViewById(). However, at the time your Activity class is constructed, the layout will not yet be inflated. This means you must wait until onCreate() to do this initialization. As other's have answered, you need to put spin = (Spinnder) findViewById(R.id.spinner2) in the onCreate() method after the call to setContentView().
To understand this in more detail, I strongly suggest that you read about the Activity life-cycle.