Hi I have been creating an app that implements a cutom sliding navigation drawer. However, I keep on receiving an error shown on the title.
Logs:
10-30 15:38:20.510: E/AndroidRuntime(1863): FATAL EXCEPTION: main
10-30 15:38:20.510: E/AndroidRuntime(1863): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobextph.krispykreme/com.mobextph.krispykreme.ParentActivity}: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Handler.dispatchMessage(Handler.java:99)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Looper.loop(Looper.java:137)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invokeNative(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invoke(Method.java:511)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-30 15:38:20.510: E/AndroidRuntime(1863): at dalvik.system.NativeStart.main(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): Caused by: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1170)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.changeFragment(ParentActivity.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.onCreate(ParentActivity.java:111)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Activity.performCreate(Activity.java:5104)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
The Main Activity class is:
package com.mobextph.krispykreme;
import java.util.ArrayList;
import com.mobextph.krispykreme.constants.Constants;
import android.R.color;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
public class ParentActivity extends FragmentActivity {
private Fragment changedFragment= null;
private FragmentManager fm;
private DrawerLayout mDrawerLayout;
private LinearLayout linearLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private ArrayList<String> navDrawerItems;
private ArrayAdapter<String> adapter;
private String[] menuItem= {"ORDER", "STAMP CARD", "REWARDS", "STORES", "FAVORITES"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Drawable d;
// getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
/*Slider*/
mTitle = mDrawerTitle = getTitle();
navMenuTitles= menuItem;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, R.id.title, menuItem));
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.button_menu, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
// changeFragment(-1);
}
fm = getSupportFragmentManager();
// DatabaseHandler db= new DatabaseHandler(this);
//
// for(int i = 0; i < 2; i++){
// db.insertFavorite(Constants.id[i], Constants.imageItem[i],
// Constants.title[i], Constants.price[i], Constants.desc[i],
// Constants.status[i]);
// }
changeFragment(-1);
}
public void changeFragment(int fragment){
FragmentTransaction transaction = fm.beginTransaction();
changedFragment = null;
switch(fragment){
case -1:
changedFragment = new HomeFragment();
// mDrawerLayout.closeDrawers();
break;
case Constants.ORDER_SCREEN_CLICKED:
changedFragment = new OrderFragment();
break;
case Constants.FAVORITES_SCREEN_CLICKED:
changedFragment = new FavoritesFragment();
break;
}
if (changedFragment != null) {
transaction.replace(R.id.fragment_holder, changedFragment);
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
mDrawerList.setItemChecked(fragment, true);
mDrawerList.setSelection(fragment);
mDrawerLayout.closeDrawer(linearLayout);
}
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
int fragment = 0;
if(position == 0)
fragment= Constants.ORDER_SCREEN_CLICKED;
else if(position == 4)
fragment= Constants.FAVORITES_SCREEN_CLICKED;
changeFragment(fragment);
}
}
// #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;
// }
//
#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();
// if (id == R.id.action_settings) {
// return true;
// }
// return super.onOptionsItemSelected(item);
if(mDrawerToggle.onOptionsItemSelected(item))
return true;
switch(item.getItemId()){
default: return super.onOptionsItemSelected(item);
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The view code that shows a linear layout for the sliding drawer and a listview is:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#008265"
android:gravity= "left" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/icon_login"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="LOGIN"
android:textSize="15dp"
android:paddingLeft="5dp"
android:paddingRight="0dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="|"
android:gravity="center"
android:textSize="15dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="SIGN UP"
android:textSize="15dp"
android:paddingLeft="0dp"
android:paddingRight="5dp"/>
</LinearLayout>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:gravity= "left" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Try setting
layout_gravity="start" or layout_gravity="left"
in your left_drawer instead of gravity
Related
I want to show/hide fragment when i click the action bar menu item. But my app give me error when i click. Fragment coming on first run. When I want to hide fragment App give null error.
How can i solve this problem ?
Thanks in now.
Logcat
01-26 03:48:40.942 2295-2295/test.sy.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.BackStackRecord.run(BackStackRecord.java:661)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
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:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
LayerList.Java
package test.sy.myapplication;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LayerList extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.layerlist,container,false);
return mView;
}
}
MainActivity.Java
package test.sy.myapplication;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
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);
setContentView(R.layout.activity_main);
}
#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.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.showsth:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
ft.show(fm.findFragmentById(R.id.fragment));
ft.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
ft.show(fm.findFragmentById(R.id.fragment));
this line causes the problem
fm.findFragmentById(R.id.fragment) returns null.
With this line you are trying to find a fragment in layout/activity_main which is previously added to R.id.fragment.
If you didn't add or replace fragment before, it is obvious to return null AMK
I fix this issue.
This situation caused by adding fragment without any framelayout.
Once add framelayout to main activity. And give it id;
<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:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<FrameLayout
android:layout_width="200dp"
android:layout_height="450dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:id="#+id/frameLayout"></FrameLayout>
Second;
Create fragment with its activty. In this example our fragment name may be FragmentTest.java and our Fragments activity may be fragment_activity.xml.
And adding fragment to main activiy;
In Oncreate method you should add this line;
FragmentTest Mfragmenttest = new FragmentTest();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//R.id.frameLayout is our frame layouts id.
ft.add(R.id.frameLayout, Mfragmenttest , "Hello Fragment");
ft.commit
i have an app with swipe menu and have set a font Roboto font for that in Mainactivity also created a folder in assets and pasted the fonts.
But when i run the app it force closes.
Please help me.
Mainactivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Regular.ttf");
TextView tv = (TextView) findViewById(R.id.title);
tv.setTypeface(tf);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
Intent intent = new Intent(this, Projects.class);
startActivity(intent);
break;
case 2:
fragment = new Aboutus();
break;
case 3:
fragment = new Services();
break;
case 4:
fragment = new News_events();
break;
case 5:
Intent intent2 = new Intent(this, Gallery.class);
startActivity(intent2);
case 6:
fragment = new Contactus();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Logcat
12-04 07:23:40.905: E/AndroidRuntime(3654): FATAL EXCEPTION: main
12-04 07:23:40.905: E/AndroidRuntime(3654): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.paarva.CrescentBuilders/info.paarva.slidingmenu.MainActivity}: java.lang.NullPointerException
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.os.Handler.dispatchMessage(Handler.java:99)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.os.Looper.loop(Looper.java:137)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-04 07:23:40.905: E/AndroidRuntime(3654): at java.lang.reflect.Method.invokeNative(Native Method)
12-04 07:23:40.905: E/AndroidRuntime(3654): at java.lang.reflect.Method.invoke(Method.java:525)
12-04 07:23:40.905: E/AndroidRuntime(3654): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-04 07:23:40.905: E/AndroidRuntime(3654): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-04 07:23:40.905: E/AndroidRuntime(3654): at dalvik.system.NativeStart.main(Native Method)
12-04 07:23:40.905: E/AndroidRuntime(3654): Caused by: java.lang.NullPointerException
12-04 07:23:40.905: E/AndroidRuntime(3654): at info.paarva.slidingmenu.MainActivity.onCreate(MainActivity.java:54)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.Activity.performCreate(Activity.java:5133)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-04 07:23:40.905: E/AndroidRuntime(3654): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-04 07:23:40.905: E/AndroidRuntime(3654): ... 11 more
12-04 07:23:42.341: I/Process(3654): Sending signal. PID: 3654 SIG: 9
Activitymain.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
drawer_list_item.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="100dp"
android:background="#drawable/list_selector">
<ImageView
android:id="#+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="#string/desc_list_item_icon"
android:src="#drawable/icon_home"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/list_item_title"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:paddingTop="10dip"
android:paddingLeft="10dp"/>
<TextView android:id="#+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/counter_bg"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:textColor="#color/counter_text_color"/>
</RelativeLayout>
NavDrawerListAdapter
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
Set typeface for text view in getView, remove the textview from main activity.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
Typeface tf = Typeface.createFromAsset(context.getAssets(),
"fonts/Roboto-Regular.ttf");
txtTitle.setTypeface(tf);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
Remove fonts Try like this
Typeface tf = Typeface.createFromAsset(getAssets(),
"Roboto-Regular.ttf");
TextView tv = (TextView) findViewById(R.id.title);
tv.setTypeface(tf);
Inflater layout try like this
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
View theInflatedView = inflater.inflate(R.layout.drawer_list_item, null);
Typeface tf = Typeface.createFromAsset(getAssets(),
"Roboto-Regular.ttf");
TextView tv = (TextView) theInflatedView .findViewById(R.id.title);
tv.setTypeface(tf);
I am having trouble closing a Drawer Layout in Android. Every time I call drawer.closeDrawers() or drawer.closeDrawers(list) I run into a Null Pointer Exception.
Here is my MainActivity.java code.
// Sliding drawer menu
private DrawerLayout drawer;
// Drawer list
private ListView drawerList;
...
...
...
// List of menu options
final String[] menu = new String[]{
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5"
};
// Initialize the drawer menu layout
drawer = (DrawerLayout) findViewById(R.layout.activity_main);
// Initialize the drawer list
drawerList = (ListView) findViewById(R.id.list_slidermenu);
// Drawer list adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menu);
// Set the adapter for the list
drawerList.setAdapter(adapter);
// Set the background selector for each menu item
drawerList.setSelector(android.R.color.holo_blue_dark);
// On click listener for the list
drawerList.setOnItemClickListener(new OnItemClickListener() {
// When a menu item is clicked
public void onItemClick(AdapterView<?> e, View v, int position, long id) {
// Close the drawer
drawer.closeDrawers(); // Causes a Null Pointer Exception
}
});
Here is my activity_main.xml code.
<!-- Left sided swipe in Drawer layout -->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Google maps fragment -->
<fragment
android:id="#+id/google_map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</fragment>
</FrameLayout>
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#F0F0F0"/>
</android.support.v4.widget.DrawerLayout>
Here is my error stack trace.
10-30 20:29:21.956: E/AndroidRuntime(1959): FATAL EXCEPTION: main
10-30 20:29:21.956: E/AndroidRuntime(1959): Process: com.dziz.umbcparkingpal, PID: 1959
10-30 20:29:21.956: E/AndroidRuntime(1959): java.lang.NullPointerException
10-30 20:29:21.956: E/AndroidRuntime(1959): at com.dziz.umbcparkingpal.MainActivity$1.onItemClick(MainActivity.java:108)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.widget.AdapterView.performItemClick(AdapterView.java:301)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.widget.AbsListView$3.run(AbsListView.java:3645)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.os.Handler.handleCallback(Handler.java:733)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.os.Handler.dispatchMessage(Handler.java:95)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.os.Looper.loop(Looper.java:136)
10-30 20:29:21.956: E/AndroidRuntime(1959): at android.app.ActivityThread.main(ActivityThread.java:5097)
10-30 20:29:21.956: E/AndroidRuntime(1959): at java.lang.reflect.Method.invokeNative(Native Method)
10-30 20:29:21.956: E/AndroidRuntime(1959): at java.lang.reflect.Method.invoke(Method.java:515)
10-30 20:29:21.956: E/AndroidRuntime(1959): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-30 20:29:21.956: E/AndroidRuntime(1959): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
10-30 20:29:21.956: E/AndroidRuntime(1959): at dalvik.system.NativeStart.main(Native Method)
Can anyone tell me what I'm doing to cause this Null Pointer Exception?
Set your Drawer with,
drawer= (DrawerLayout) findViewById(R.id.DrawerLayout);
You need to inflate the layout before retrieving the views from within it:
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
View drawer = inflater.inflate(R.layout.activity_main, null);
then you can fetch the views:
drawerList = (ListView) drawer.findViewById(R.id.list_slidermenu);
I had the same issue and solved it by calling this:
DrawerLayout drawerLayout = (DrawerLayout) ((MainActivity) getActivity()).findViewById(R.id.drawer_layout);
drawerLayout.closeDrawers();
within the fragment. Where MainActivity is the activity where you put your drawer_layout.
Also make sure that you get the reference to the drawerLayout right before you call closeDrawers() because in my case I still got a NullPointer when calling the findViewById() at the start of onCreateView() of my fragment.
So in your case call the findViewById() from within your onItemClicked() method.
Hope this helps.
I have use drawer and it's run perfectly with out any error. This is some portion of my code . I think it might help you.
HomeActivity.java
public class HomeActivity extends Activity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Activity :", getClass().getName().toString());
initDrawer(savedInstanceState);
}
private void initDrawer(Bundle savedInstanceState) {
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(
R.array.student_nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(
R.array.student_nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setIcon(android.R.color.transparent);
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setCustomView(R.layout.custom_titlebar);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvTitle.setText(getString(R.string.title_activity_home));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.slider_icon, R.string.app_name, R.string.app_name
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
private void selectItem(int position) {
switch (position) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
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/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:divider="#444"
android:dividerHeight="1dp"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall" />
</android.support.v4.widget.DrawerLayout>
if(mDrawerLayout.isDrawerOpen(mRecyclerDrawer)){
mDrawerLayout.closeDrawer(listview);
}else {
mDrawerLayout.openDrawer(listview);
}
I am stuck with an idea.
I am trying to implement a feature in a android application.
I have an edittext and a button, if I enter 3 in edittext
and press the button I want to go to another activity which will be having 3 buttons.
If i enter 10 I wanna go to another activity where to display 10 buttons.
I know how to make such switch, I don't know how to do it dynamically ,
I want to make for values between 0 and 10 and I don't want to have 10 fragments .
Plaese give me solution to achieve it ..
Thanks..
Untill now:
mainactivity.java:
package com.example.instances_temperature;
import com.example.instances_temperature.Tabel;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText instances;
Button ok;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ok = (Button) findViewById(R.id.ok);
instances = (EditText) findViewById(R.id.instances);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (instances.getText().toString().length() > 0)
{
int value = Integer.parseInt(instances.getText().toString());;
if(value > 10)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value<0)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value >= 0 && value <=10)
{
schimba(v);
}
}
else
{
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
}
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void schimba(View view){
int value = Integer.parseInt(instances.getText().toString());;
Intent intent = new Intent(this, Tabel.class);
intent.putExtra("max", value);
startActivity(intent);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.instances_temperature.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/ShowValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Instances No.:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/instances"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="#+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/instances"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="Ok"
android:onClick="schimba" />
</RelativeLayout>
tabel.java:
package com.example.instances_temperature;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
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.LinearLayout;
import android.widget.TextView;
import android.os.Build;
public class Tabel extends ActionBarActivity {
int i;
int value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout = (LinearLayout)findViewById(R.id.container);
for(i=1;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowview = layoutinflate.inflate( R.layout.ShowMe, null);
TextView showvalue;
showvalue = (TextView) rowview.findViewById(R.id.showid);
showvalue.setText(""+value);
layout.addView(rowview);
}
//showvalue.setText(String.valueOf(getIntent().getExtras().getInt("max")));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).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.tabel, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabel,
container, false);
return rootView;
}
}
}
activity_tabel.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.instances_temperature.Tabel"
tools:ignore="MergeRootFrame" >
</LinearLayout>
LinearLayout code of inflation_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/inflationn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ShowMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
LogCat error:
04-24 06:21:04.244: E/AndroidRuntime(269): FATAL EXCEPTION: main
04-24 06:21:04.244: E/AndroidRuntime(269): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.instances_temperature/com.example.instances_temperature.Tabel}: java.lang.NullPointerException
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.os.Looper.loop(Looper.java:123)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-24 06:21:04.244: E/AndroidRuntime(269): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 06:21:04.244: E/AndroidRuntime(269): at java.lang.reflect.Method.invoke(Method.java:521)
04-24 06:21:04.244: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-24 06:21:04.244: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-24 06:21:04.244: E/AndroidRuntime(269): at dalvik.system.NativeStart.main(Native Method)
04-24 06:21:04.244: E/AndroidRuntime(269): Caused by: java.lang.NullPointerException
04-24 06:21:04.244: E/AndroidRuntime(269): at com.example.instances_temperature.Tabel.onCreate(Tabel.java:42)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-24 06:21:04.244: E/AndroidRuntime(269): ... 11 more
You can get the value from the editText by...
String value= EditText.getText().toString();
Pass the value to another activity (Activity2) through Intent
Now in Activity2 you write this code in the onCreate()
for(int i=1 ; i<= value ; i++){
Button b = new Button(getApplicationContext());
LinearLayout.addView(b);
}
Answer to your edited question.....
main xml file activity_table:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
layout file to be inflated layout_inflate:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ShowValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text" />
</LinearLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout= (LinearLayout)findViewById(R.id.layout)
for(i=0;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = layoutinflate.inflate( R.layout.layout_inflate, null);
TextView showvalue;
showvalue = (TextView) rowview.findViewById(R.id.ShowValue);
showvalue.setText(""+value);
layout.addView(rowview);
}
You can retrieve the EditText value on tha Button click. And pass the Value with the intent.
In that Activity you can build your logic Using Swicth cases. Then you can add the number of Buttons dynamically (eg:- for(i=0;i<yourValue;i++) yourValue is got From intent.)
below find all my code and xml. My problem is that the spinner (in code spinner1) is null for some reason I can't determine and I get no errors other than the app failing to run. Any help would be appreciated!
activity_main.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".MainActivity" />
MainActivity.java:
package com.example.passwordplayground;
import java.util.Locale;
import com.example.MyApplication.EncryptionSpinner;
import com.example.MyApplication.MyApplication;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
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.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Spinner spinner1 = (Spinner) findViewById(R.id.encryptionSpin);
if (spinner1 == null)
System.out.println("Spinner1 is null");
else
System.out.println("Funcion is null");
spinner1.setOnItemSelectedListener(new EncryptionSpinner());
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(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.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return ("Practicality").toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if (getArguments().getInt(ARG_SECTION_NUMBER)==1) {
rootView = inflater.inflate(R.layout.encryption,container, false);
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==2) {
rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText("I'm second!");
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==3) {
//dummyTextView.setText("I'm third");
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==4) {
//dummyTextView.setText("I'm fourth and last!");
}
return rootView;
}
}
}
encryption.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
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$Encryption" >
<Spinner
android1:id="#+id/encryptionSpin"
android1:layout_width="fill_parent"
android1:layout_height="wrap_content"
android1:layout_alignParentTop="true"
android1:layout_centerHorizontal="true"
android1:layout_marginTop="14dp"
android1:background="#color/orange"
android1:entries="#array/cryptArray" />
</RelativeLayout>
EncryptionSpinner.java:
package com.example.MyApplication;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class EncryptionSpinner implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Toast toast = Toast.makeText(MyApplication.getAppContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG);
toast.show();
System.out.println(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
Logcat Error:
04-09 01:16:28.637: I/System.out(1440): Spinner1 is null
04-09 01:16:28.657: D/AndroidRuntime(1440): Shutting down VM
04-09 01:16:28.657: W/dalvikvm(1440): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
04-09 01:16:28.692: E/AndroidRuntime(1440): FATAL EXCEPTION: main
04-09 01:16:28.692: E/AndroidRuntime(1440): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.passwordplayground/com.example.passwordplayground.MainActivity}: java.lang.NullPointerException
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.os.Handler.dispatchMessage(Handler.java:99)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.os.Looper.loop(Looper.java:137)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-09 01:16:28.692: E/AndroidRuntime(1440): at java.lang.reflect.Method.invokeNative(Native Method)
04-09 01:16:28.692: E/AndroidRuntime(1440): at java.lang.reflect.Method.invoke(Method.java:525)
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-09 01:16:28.692: E/AndroidRuntime(1440): at dalvik.system.NativeStart.main(Native Method)
04-09 01:16:28.692: E/AndroidRuntime(1440): Caused by: java.lang.NullPointerException
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.example.passwordplayground.MainActivity.onCreate(MainActivity.java:65)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.Activity.performCreate(Activity.java:5133)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-09 01:16:28.692: E/AndroidRuntime(1440): ... 11 more
Layouts' Gui:
if you want to user spinner from activity_main then you have to put it in that file because right now its not their and it is in encryption.xml file.
make activity_main.xml like below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
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$Encryption" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black"
tools:context=".MainActivity" />
<Spinner
android1:id="#+id/encryptionSpin"
android1:layout_width="fill_parent"
android1:layout_height="wrap_content"
android1:layout_alignParentTop="true"
android1:layout_centerHorizontal="true"
android1:layout_marginTop="14dp"
android1:background="#color/orange"
android1:entries="#array/cryptArray" />
</RelativeLayout>
You have inflated the layout activity_main in your activity and you are trying to access the Spinner which is not in your activity_main layout.
In that point you are getting error. As the Spinner does not resides in your activity_main layout.
So will have to initialize your Spinner in DummySectionFragment onCreateView method as below:
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if (getArguments().getInt(ARG_SECTION_NUMBER)==1) {
rootView = inflater.inflate(R.layout.encryption,container, false);
Spinner spinner1 = (Spinner)rootView.findViewById(R.id.encryptionSpin);
}
you see there is null pointer exception.
means you have no control on the components you are using.
this could be caused due to two reason
1. two components have same ids.
2. wrong defined layout.
in your case you are using layout
R.layout.activity_main
while your layout name is
R.layout.encryption
change the name of layout and you are ready to go.
You putting ViewPager in activity_mail layout and Spinner in encryption.xml if u setting content view as any one of xml. so any one ll identify another one will not be identify. It will throw the null pointer exception.
R.layout.activity_main having ViewPager
R.layout.encryption having Spinner
if u set setcontentView(R.layout.activity_main) then findViewById(R.id.encryptionSpin); line will throw null pointer.
if u set setcontentView(R.layout.encryption) then mViewPager = (ViewPager) findViewById(R.id.pager); line will throw null pointer.