How to use android navigation spinner - java

I'm new to android, and I'm pretty bad at it. So bear with me and please be very clear and basic with your answers.
I'm trying to make a navigation spinner in android. I made it using the tutorial but I can't figure out how to modify the pages that they direct the user to. For now I'm trying to get them all to lead to the same page that just has a basic "Hello." The app keeps crashing though.
public class MainActivity extends ActionBarActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(actionBar.getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3), }), this);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getSupportActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
.getSelectedNavigationIndex());
}
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 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);
}
public boolean onNavigationItemSelected(int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
Intent intent = new Intent (this, Fibonacci.class);
startActivity(intent);
return true;
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
And:
public class Fibonacci extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the message from the intent
Intent intent = getIntent();
String message = "Hello";
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
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;
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
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);
}
public static int fibonacciNum (int position) {
int num = 1;
if (position <= 2) {
return 1;
}
else {
num = fibonacciNum(position-1) + fibonacciNum(position-2);
return num;
}
}
}
Logcat:
07-15 10:08:13.850: E/AndroidRuntime(921): FATAL EXCEPTION: main
07-15 10:08:13.850: E/AndroidRuntime(921): Process: com.zarwanhashem.sequences, PID: 921
07-15 10:08:13.850: E/AndroidRuntime(921): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.zarwanhashem.sequences/com.zarwanhashem.sequences.Fibonacci}; have you declared this activity in your AndroidManifest.xml?
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Activity.startActivityForResult(Activity.java:3424)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Activity.startActivityForResult(Activity.java:3385)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:839)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Activity.startActivity(Activity.java:3627)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.Activity.startActivity(Activity.java:3595)
07-15 10:08:13.850: E/AndroidRuntime(921): at com.zarwanhashem.sequences.MainActivity.onNavigationItemSelected(MainActivity.java:91)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.support.v7.app.ActionBarImplICS$OnNavigationListenerWrapper.onNavigationItemSelected(ActionBarImplICS.java:355)
07-15 10:08:13.850: E/AndroidRuntime(921): at com.android.internal.widget.ActionBarView$1.onItemSelected(ActionBarView.java:145)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.widget.AdapterView.access$200(AdapterView.java:48)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.os.Handler.handleCallback(Handler.java:733)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.os.Handler.dispatchMessage(Handler.java:95)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.os.Looper.loop(Looper.java:136)
07-15 10:08:13.850: E/AndroidRuntime(921): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-15 10:08:13.850: E/AndroidRuntime(921): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 10:08:13.850: E/AndroidRuntime(921): at java.lang.reflect.Method.invoke(Method.java:515)
07-15 10:08:13.850: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-15 10:08:13.850: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-15 10:08:13.850: E/AndroidRuntime(921): at dalvik.system.NativeStart.main(Native Method)
Manifest:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.zarwanhashem.sequences.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

android.content.ActivityNotFoundException: Unable to find explicit
activity class
{com.zarwanhashem.sequences/com.zarwanhashem.sequences.Fibonacci};
have you declared this activity in your AndroidManifest.xml?
Every activity that you intend to call in your application must be declared in the AndroidManifest file. The minimum necessary would be:
<activity android:name=".Fibonacci" />

Related

setAdapter() crashes app

When I call .notifyDataSetChanged() in my constructor after I set my ArrayList my app still crashes, the same as when I call it before I call .setAdapter, it's been bothering me for hours, would love any kind of help, thanks!
public class CustomSwipeAdapter extends PagerAdapter {
private ArrayList<String> image_resources = new ArrayList<>();
private Context mContext;
private LayoutInflater mLayoutInflater;
private ImageLoader mImageLoader;
public CustomSwipeAdapter(Context context, ArrayList<String> images){
this.mContext = context;
this.image_resources = images;
}
#Override
public int getCount() {
return image_resources.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View item_view = mLayoutInflater.inflate(R.layout.swipe_layout, container, false);
final ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);
if (image_resources.get(position) != null || !image_resources.get(position).isEmpty()) {
mImageLoader.get(image_resources.get(position), new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
imageView.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
imageView.setBackgroundColor(Color.CYAN);
}
});
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
super.destroyItem(container, position, object);
}
}
Where I set my Adapter (in my Activity's onCreate()), it's most basic activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
}
Stack Trace:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 4 Pager id: sobmad.com.gamingreminder:id/view_pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class sobmad.com.gamingreminder.GamePage.CustomSwipeAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:967)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
at android.view.View.measure(View.java:15848)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
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)
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChange() //Add this line in your activity

Issue with fragment OptionsMenu when recall fragment?

MainActivity
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, new LayOutOne()).commit();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.settings:
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new PrefFragment())
.addToBackStack(null)
.commit();
break;
}
return super.onOptionsItemSelected(item);
}
PrefFragmentList extends PreferenceFragment
public class PrefFragmentList extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
PrefFragment extends Fragment
public class PrefFragment extends Fragment {
private View v;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v = inflater.inflate(R.layout.layout_settings, null);
setHasOptionsMenu(true);
return v;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
menu.findItem(R.id.settings).setVisible(true).setEnabled(false).setChecked(true).setChecked(true);
super.onCreateOptionsMenu(menu, inflater);
}
PROBLEM:
MainActivity call PrefFragment from OptionMenu , when i go back to MainActivity and re-call PrefFragment, the application crash.
LOGCAT:
11-27 12:12:50.857 1387-1387/xx.xxx.myapplication D/dalvikvm: GC_FOR_ALLOC freed 228K, 3% free 9211K/9476K, paused 25ms, total 25ms
11-27 12:13:02.584 1387-1387/xx.xxxx.myapplication D/AndroidRuntime: Shutting down VM
11-27 12:13:02.584 1387-1387/xx.xxxx.myapplication W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4178b700)
11-27 12:13:02.592 1387-1387/xx.xxxx.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
android.view.InflateException: Binary XML file line #6: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at xx.xxx.myapplication.PrefActivity.onCreateView(PrefActivity.java:23)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
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)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f0e0052, tag null, or parent id 0xffffffff with another fragment for xx.xxxxx.myapplication.PrefFragment
at android.app.Activity.onCreateView(Activity.java:4751)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:34)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:397) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:353) 
at xxx.xxxx.myapplication.PrefFragment.onCreateView(PrefFragment.java:23) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248) 
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613) 
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
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) 
I try replace in OnCreateView:
final View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
with:
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.layout_settings, container, false);
} catch (InflateException e) {
}
return rootView;
Work fine and resolve this error:
LOGCAT
From the logcat: Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f0e0052, tag null, or parent id 0xffffffff with another fragment for xx.xxxxx.myapplication.PrefFragment

App crashed when arrayAdapter.notifyDataSetChanged() was called

public class Activity_search extends ActionBarActivity {
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mArrayAdapter;
private ArrayList<String> mArrayList;
private boolean isDiscovering;
private AdapterView.OnItemClickListener mClickListener = new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> adapterView,View view,int position, long id ){
mBtAdapter.cancelDiscovery();
isDiscovering=false;
Toast.makeText(getApplicationContext(),"Selected",Toast.LENGTH_SHORT).show();
String tmp1 = ((TextView)view).getText().toString();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_search);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mArrayList = new ArrayList<String>();
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(mArrayAdapter);
listView.setOnItemClickListener(mClickListener);
}
#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_activity_search, 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);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String tmp=device.getName() + "\n" + device.getAddress();
Context appContext = getApplicationContext();
Toast.makeText(appContext,tmp,Toast.LENGTH_LONG).show();
mArrayList.add(tmp);
mArrayAdapter.notifyDataSetChanged();
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
Toast.makeText(getApplicationContext(),"Discovery Finished",Toast.LENGTH_SHORT).show();
}
}
};
public void onBtn2Clicked(View view) {
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Context appContext = getApplicationContext();
if(!isDiscovering) {
mBtAdapter.startDiscovery();
Toast.makeText(appContext, "Discovery Started", Toast.LENGTH_SHORT).show();
isDiscovering=true;
} else {
mBtAdapter.cancelDiscovery();
Toast.makeText(appContext,"Discovery Canceled",Toast.LENGTH_SHORT).show();
isDiscovering=false;
}
}
public void onDestroy(){
super.onDestroy();
if(mBtAdapter.isDiscovering()){
mBtAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
}
App always crashed when it called the function as mentioned at above, And its error code is
02-13 16:04:47.974 27328-27328/com.skyjohn.nxtrpc E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 (has extras) } in com.skyjohn.nxtrpc.Activity_search$2#41532570
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:798)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.skyjohn.nxtrpc.Activity_search$2.onReceive(Activity_search.java:90)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
But if i hardcoded mArrayList.add("abc") into the code, the "abc" will appear, but if I do it dynamicly (when I received a new bluetooth device) , the app crashed.
Caused by: java.lang.NullPointerException
at com.skyjohn.nxtrpc.Activity_search$2.onReceive
mArrayAdapter is null because creating new object of Adapter in onCreate method with same name which declare as class level.
To fix error use:
mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);
in onCreate method instead of creating new object of ArrayAdapter.
inside onCreate you are hiding the scope of the class member variable mAdapter, declaring and initialazing it in the local scope of onCreate. The fix is to remove ArrayAdapter<String> from onCreate, leaving only
mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);

Fragment is trying to cast to activity

I know this answer is probably simple but i cannot figure it out. I am modifying example code for a project and keep getting a ClassCastException when i try to launch the app. Says that ListActivityFragment cannot be cast to android.app.Activity. What im not understanding(which is probably the simple part) is why its trying to cast it onto an activity when my main is a fragmentactivity. I know the code is rough, still trying to finish it up but cant get past this.
FragmentActivity
public class MainActivity extends FragmentActivity {
private boolean isLargeScreen = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.normal_screen_layout) != null) {
isLargeScreen = false;
ListActivityFragment listActivityFragment = new ListActivityFragment();
listActivityFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.normal_screen_layout, listActivityFragment)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addItem:
ListActivityFragment newFragment = new ListActivityFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.normal_screen_layout, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
}
ListActivity
public class ListActivityFragment extends ListFragment implements
OnClickListener {
private ArrayList<String> items = new ArrayList<String>();
private ListView listView;
private View outerView;
private Button deleteButton;
private ListActivityListener listener;
public interface ListActivityListener {
public void meetingAdded();
}
public ListActivityFragment() {
}
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (ListActivityListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
outerView = inflater.inflate(R.layout.list_of_meetings, container,
false);
listView = (ListView) outerView.findViewById(R.id.listView1);
deleteButton = (Button) outerView.findViewById(R.id.deleteButton);
createList();
return outerView;
}
public void createList() {
items.clear();
Iterator<Items> iterator = ItemCollection.Instance().iterator();
while (iterator.hasNext()) {
items.add(iterator.next().toString());
}
listView.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, items));
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
ListView listView = getListView();
for (int index = 0; index < listView.getChildCount(); index++) {
View viewGroup = listView.getChildAt(index);
CheckBox checkBox = (CheckBox) viewGroup
.findViewById(R.id.itemSelectCheckBox);
if (checkBox.isChecked()) {
TextView textView = (TextView) viewGroup
.findViewById(R.id.productTextView);
int key = (Integer) textView.getTag();
ItemCollection.Instance().delete(key);
}
}
createList();
}
#Override
public void onStart() {
super.onStart();
}
public void onListItemClick(ListView l, View v, int position, long id) {
getListView().setItemChecked(position, true);
}
}
And heres the Logcat
07-15 01:59:50.710: E/AndroidRuntime(878): FATAL EXCEPTION: main
07-15 01:59:50.710: E/AndroidRuntime(878): Process: com.example.assignment5, PID: 878
07-15 01:59:50.710: E/AndroidRuntime(878): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.assignment5/com.example.assignment5.ListActivityFragment}: java.lang.ClassCastException: com.example.assignment5.ListActivityFragment cannot be cast to android.app.Activity
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:102)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:136)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-15 01:59:50.710: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 01:59:50.710: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:515)
07-15 01:59:50.710: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-15 01:59:50.710: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-15 01:59:50.710: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
07-15 01:59:50.710: E/AndroidRuntime(878): Caused by: java.lang.ClassCastException: com.example.assignment5.ListActivityFragment cannot be cast to android.app.Activity
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
07-15 01:59:50.710: E/AndroidRuntime(878): ... 11 more
07-15 01:59:51.160: E/NetdConnector(383): NDC Command {65 bandwidth setiquota eth0 9223372036854775807} took too long (1117ms)
Caused by: java.lang.ClassCastException:
com.example.assignment5.ListActivityFragment cannot be cast to
android.app.Activity 07-15 01:59:50.710: E/AndroidRuntime(878):
As the error says -
ListActivityFragment is not an activity. So you are trying to access it just like an activity.
Make sure you haven't declared ListActivityFragment in the manifest. In your manifest if you made an entry for the fragment then that's wrong.
Also make sure that you haven't used startActivity for the fragment. Because this is done for activity class and not for fragment class.

Where to create Android Spinner in Fragment?

My question is rather simple: how can one use(populate) Spinners in Fragments? Or better said, what is wrong with my code below? Adding Spinner as I did is as simple as it gets, but after trying in all the different ways, nothing worked. What is FragmentPagerAdapter has to do with Spinner? If I add the Spinner from a method declared somewhere else, the spinner is populated with no problems(for example if populating the spinner from a button).
Thanks in advance
public class MainActivity extends FragmentActivity {
/**
* 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;
public List<String> fragments = new Vector<String>();
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
private MySQLite database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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); // pager
mViewPager.setAdapter(mSectionsPagerAdapter);
// We initialise the database
database = new MySQLite(this);
Spinner spin = (Spinner)findViewById(R.id.spinner1);
List<String> toSpin = new ArrayList<String>();
toSpin.add("ONE");
toSpin.add("TWO");
toSpin.add("THREE");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,toSpin);
spin.setAdapter(adapter);
}
#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;
}
/**
* 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);
fragments.add(ConnectionFragment.class.getName());
fragments.add(DataFragment.class.getName());
}
#Override
public Fragment getItem(int position) {
// we need to instantiate the list of fragments
return Fragment.instantiate(getBaseContext(),
fragments.get(position));
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#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);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class ConnectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public ConnectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View connectionView = inflater.inflate(
R.layout.fragment_main_dummy, container, false);
return connectionView;
}
}
public static class DataFragment extends Fragment {
public DataFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dataView = inflater.inflate(R.layout.fragment_linear,
container, false);
return dataView;
}
}
Logcat:
11-16 18:26:13.092: E/AndroidRuntime(16442): FATAL EXCEPTION: main
11-16 18:26:13.092: E/AndroidRuntime(16442): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iwallet/com.example.iwallet.MainActivity}: java.lang.NullPointerException
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2096)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.access$600(ActivityThread.java:138)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1207)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.os.Handler.dispatchMessage(Handler.java:99)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.os.Looper.loop(Looper.java:213)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.main(ActivityThread.java:4787)
11-16 18:26:13.092: E/AndroidRuntime(16442): at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:26:13.092: E/AndroidRuntime(16442): at java.lang.reflect.Method.invoke(Method.java:511)
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
11-16 18:26:13.092: E/AndroidRuntime(16442): at dalvik.system.NativeStart.main(Native Method)
11-16 18:26:13.092: E/AndroidRuntime(16442): Caused by: java.lang.NullPointerException
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.example.iwallet.MainActivity.onCreate(MainActivity.java:65)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.Activity.performCreate(Activity.java:5008)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2035)
11-16 18:26:13.092: E/AndroidRuntime(16442): ... 11 more
If you want to make your Spinner in your Fragment, maybe you must to declare in these Fragment in onCreatedView(). Not in onCreate() of your FragmentActivity.
And you can do it like this: Error populating spinner in a fragment

Categories