Error inflating class in a view - java

I've already saw questions suggestions but I didn't find my answer.
The LogCat throws this error:
I/Timeline( 7748): Timeline: Activity_launch_request id:com.miracle.livapp time:45951871
I/ActivityManager( 768): START u0 {flg=0x10000000 cmp=com.miracle.livapp/com.odizzain.cordova.plugins.livestream.CameraStreamingActivity} from uid 10252 on display 0
E/AndroidRuntime( 7748): Process: com.miracle.livapp, PID: 7748
E/AndroidRuntime( 7748): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.miracle.livapp/com.odizzain.cordova.plugins.livestream.CameraStreamingActivity}: android.view.InflateException: Binary XML file line #6: Error inflating class ru.denivip.nine00secondssdk.hlsstreaming.Nine00SecondsCameraView
D/ActivityManager( 768): New dropbox entry: com.miracle.livapp, data_app_crash, 877fda44-aca7-4a69-8c23-c0da45fa7bd4
W/ActivityManager( 768): Force finishing activity com.miracle.livapp/com.odizzain.cordova.plugins.livestream.CameraStreamingActivity
W/ActivityManager( 768): Force finishing activity com.miracle.livapp/.MainActivity
W/ActivityManager( 768): Activity pause timeout for ActivityRecord{3e7cfd61 u0 com.miracle.livapp/com.odizzain.cordova.plugins.livestream.CameraStreamingActivity t82 f}
W/ActivityManager( 768): Activity destroy timeout for ActivityRecord{338f1497 u0 com.miracle.livapp/.MainActivity t82 f}
W/ActivityManager( 768): Activity destroy timeout for ActivityRecord{3e7cfd61 u0 com.miracle.livapp/com.odizzain.cordova.plugins.livestream.CameraStreamingActivity t82 f}
The class involved has two constructor avoiding the second argument problem that I read in other places:
public Nine00SecondsCameraView(Context context){
super(context, null);
}
public Nine00SecondsCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
....
}
This is the XML File:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ru.denivip.nine00secondssdk.hlsstreaming.Nine00SecondsCameraView
android:id="#+id/streamingView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageButton
android:id="#+id/toggleRecording_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="16dp"
android:background="#drawable/circle_button_background_selector"
android:src="#drawable/reccord_button"
android:clickable="true"
android:onClick="clickToggleRecording" />
</RelativeLayout>
And this is the CameraStreamingActivity.java
package com.odizzain.cordova.plugins.livestream;
import ru.denivip.nine00secondssdk.hlsstreaming.Nine00SecondsCameraView;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class CameraStreamingActivity extends Activity {
private String appPackageName = null;
private Resources appResources = null;
private Nine00SecondsCameraView streamingView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appPackageName = getApplication().getPackageName();
appResources = getApplication().getResources();
// appResources.getIdentifier("activity_camerabroadcast", "layout", appPackageName)
setContentView(appResources.getIdentifier("camera_streaming_activity", "layout", appPackageName));
streamingView = (Nine00SecondsCameraView) findViewById(appResources.getIdentifier("streamingView", "id", appPackageName));
}
#Override
protected void onResume() {
super.onResume();
streamingView.onResume();
}
#Override
protected void onPause() {
super.onPause();
streamingView.onPause();
}
/**
* onClick handler for "record" button.
*/
public void clickToggleRecording(View unused) {
if (streamingView.isRecording())
streamingView.stopRecording();
else
streamingView.startRecording();
updateControls();
}
/**
* Updates the on-screen controls to reflect the current state of the app.
*/
private void updateControls() {
ImageButton toggleRelease = (ImageButton) findViewById(appResources.getIdentifier("toggleRecording_button", "id", appPackageName));
int id = streamingView.isRecording() ?
appResources.getIdentifier("stop_reccord_button", "drawable", appPackageName) :
appResources.getIdentifier("reccord_button", "drawable", appPackageName);
toggleRelease.setImageResource(id);
}
}
btw, i am using this sdk: http://livestreamsdk.com/

I solved adding constructors for this three and four arguments:
SurfaceView(Context context, AttributeSet attrs, int defStyleAttr)
SurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Like the android documentation says.

Related

Reusing onclick listener with a string parameter in Android Java

I'm mimicking the code in this thread to create a reusable click event that fires up a browser. I want to pass a custom URL destination when instantiating the class. The example has no apparent error in eclipse but crashes when launched:
FATAL EXCEPTION: main
02-19 12:45:57.416: E/AndroidRuntime(12465): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app/com.app.ItemActivity}: java.lang.NullPointerException
The error should come from this line
btn.setOnClickListener(new ButtonInternetAccess("http://google.com"));
because it works okay without that line.
Does the class ButtonInternetAccess fail to return the onClickListener which leads to the null value? How can I fix that?
Main Activity:
public class ItemActivity extends ActionBarActivity{
private static final View View = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
Bundle b = i.getExtras();
Button btn = (Button) findViewById(R.id.button_internet_access);
btn.setOnClickListener(new ButtonInternetAccess("http://google.com"));
}
}
Button Class:
public class ButtonInternetAccess extends Activity implements OnClickListener {
String url;
public ButtonInternetAccess(String url) {
this.url = url;
}
public void onClick(View v) {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(url));
startActivity(callIntent); // No Error here
System.out.println(url);
} catch (ActivityNotFoundException activityException) {
Log.e("Calling a Phone Number", "Call failed", activityException);
}
}
}
layout/activity_item
<TextView
android:id="#+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<include android:id="#+id/header" layout="#layout/button_internet_access">
layout/button_internet_access:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button_internet_access"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="go out" />
Error:
02-19 12:45:57.416: E/AndroidRuntime(12465): FATAL EXCEPTION: main
02-19 12:45:57.416: E/AndroidRuntime(12465): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app/com.app.ItemActivity}: java.lang.NullPointerException
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.os.Looper.loop(Looper.java:137)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-19 12:45:57.416: E/AndroidRuntime(12465): at java.lang.reflect.Method.invokeNative(Native Method)
02-19 12:45:57.416: E/AndroidRuntime(12465): at java.lang.reflect.Method.invoke(Method.java:511)
02-19 12:45:57.416: E/AndroidRuntime(12465): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-19 12:45:57.416: E/AndroidRuntime(12465): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-19 12:45:57.416: E/AndroidRuntime(12465): at dalvik.system.NativeStart.main(Native Method)
02-19 12:45:57.416: E/AndroidRuntime(12465): Caused by: java.lang.NullPointerException
02-19 12:45:57.416: E/AndroidRuntime(12465): at com.app.ItemActivity.onCreate(ItemActivity.java:29)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.Activity.performCreate(Activity.java:5008)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
02-19 12:45:57.416: E/AndroidRuntime(12465): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
Updated:
I have managed to make a plugin following this link.
Final Work:
Class Internet:
public class Internet implements OnClickListener {
private String url;
private Context context;
public Internet(Context context, String url) {
this.context = context;
this.url = url;
}
#Override
public void onClick(View v) {
if (!url.contains("http://")){
url = "http://"+url;
}
Intent callIntent = new Intent(Intent.ACTION_VIEW);
callIntent.setData(Uri.parse(url));
context.startActivity(callIntent);
}
}
Class StyleButton:
public class StyleButton extends Button{
public StyleButton(Context context) {
super(context);
}
public StyleButton(Context context, AttributeSet attrs) {
super(context, attrs);
initStyleButton(attrs);
}
public StyleButton(Context context, AttributeSet attrs, int defStyle,String url) {
super(context, attrs, defStyle);
initStyleButton(attrs);
}
private void initStyleButton(AttributeSet attrs){
TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.style_Button);
String Text1 = a.getString(R.styleable.style_Button_myText_1);
String Text2 = a.getString(R.styleable.style_Button_myText_2);
setText(Text1 + "\n" + Text2);
String url = a.getString(R.styleable.style_Button_url);
System.out.println(url);
setOnClickListener(new Internet(getContext(),url));
a.recycle();
}
}
/layout/item_activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:stylebutton= "http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/response"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""/>
<com.button.StyleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
stylebutton:myText_1="My Text 1"
stylebutton:myText_2="My Text 2"
stylebutton:url="www.google.com"
/>
<com.button.StyleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
stylebutton:myText_1="Hello!"
stylebutton:myText_2="It's a Style Button:)"
stylebutton:url="www.yahoo.com"
/>
/value/attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="style_Button">
<attr name="myText_1" format="string" />
<attr name="myText_2" format="string" />
<attr name="url" format="string" />
</declare-styleable>
</resources>
Create your custom button and use it in your project that way it is possible to use it globally.
public class ButtonInternetAccess extends UIButton implements OnClickListener {
String url;
Context mContext;
public ButtonInternetAccess(Context context, AttributeSet attrs,String url) {
super(context, attrs);
this.url = url;
this.mContext=mContext;
// TODO Auto-generated constructor stub
}
// initialize button and add click listener here.
}
you can add that button to your xml also like
<yourpackagename.ButtonInternetAccess
height=""
width = ""
other properties to include
/>
hope this will help.
your setOnClickListener should be as below way :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("http://google.com"));
startActivity(callIntent); // No Error here
System.out.println(url);
} catch (ActivityNotFoundException activityException) {
Log.e("Calling a Phone Number", "Call failed", activityException);
}
}
});
It seems you do not need to send the URL to another class as you can do the same to ItemActivity itself.
Edited : In case you wants to geralize one class please update your ButtonInternetAccess to below way :
public class ButtonInternetAccess implements OnClickListener {
String url;
Context mContext;
public ButtonInternetAccess(Context mContext,String url) {
this.url = url;
this.mContext=mContext;
}
public void onClick(View v) {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(url));
mContext.startActivity(callIntent);
System.out.println(url);
} catch (ActivityNotFoundException activityException) {
Log.e("Calling a Phone Number", "Call failed", activityException);
}
}
}
Change Button Class to;
public class ButtonInternetAccess implements View.OnClickListener {
private String url;
private Context context;
public ButtonInternetAccess(Context context, String url) {
this.context = context;
this.url = url;
}
public void onClick(View v) {
System.out.println(url);
Intent callIntent = new Intent(Intent.ACTION_VIEW);
callIntent.setData(Uri.parse(url));
try {
context.startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("ONCLICK", "No Activity found", activityException);
}
}
}

MediaPlayer onClick crashes when start() is called

I have an app that simply displays 1 picture, implemented through Picasso. The onClick works fine if I replace the contents with a simple toast, so it must be the MediaPlayer calls. I don't know why it keeps crashing though.
package com.example.andrew.crossfade;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends ActionBarActivity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setClickable(true);
Picasso.with(this)
.load("http://i.imgur.com/vpeH7S2.jpg")
.into(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.later);
mp.start();
}
});
}
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;
}
}
}
The XML:
<FrameLayout 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=".MainActivity" tools:ignore="MergeRootFrame" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
/>
And finally, the log cat:
10-29 12:12:07.343 18409-18409/com.example.andrew.crossfade W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41f38da0)
10-29 12:12:07.343 18409-18409/com.example.andrew.crossfade E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.andrew.crossfade, PID: 18409
java.lang.NullPointerException
at com.example.andrew.crossfade.MainActivity$1.onClick(MainActivity.java:47)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19330)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
something is null in your code
java.lang.NullPointerException
call mp.prepare() before start
and make sure R.raw.later is playable audio for media player

Android inflate exception - ViewPager

I am trying to implement pageviewer in my app using this tutorial. But my app force closes. It shows android.view.InflateException: Binary XML file line #2: Error inflating class com.example.viewpager.ScrollView. Where I am going wrong? I am a beginner in android so please guide me. I thought I might have imported wrong libs as my app is supporting API 10. So I searched other answers but of no use. Here is my code:
MainActvity.java
package com.example.viewpager;
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.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new ScreenSlidePageFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
ScreenSlidePagerFragment.java
package com.example.viewpager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
actvity_main.xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment_slide_screen_page.xml
<?xml version="1.0" encoding="utf-8"?>
<com.example.viewpager.ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:textColor="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Page 1" />
</com.example.viewpager.ScrollView>
Log cat:
android.view.InflateException: Binary XML file line #2: Error inflating class com.example.viewpager.ScrollView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581)
at android.view.LayoutInflater.inflate(LayoutInflater.java:386)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at com.example.viewpager.ScreenSlidePageFragment.onCreateView(ScreenSlidePageFragment.java:14)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
at android.view.View.measure(View.java:8313)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
at android.view.View.measure(View.java:8313)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
at android.view.View.measure(View.java:8313)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
at android.view.View.measure(View.java:8313)
at android.view.ViewRoot.performTraversals(ViewRoot.java:845)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.example.viewpager.ScrollView in loader dalvik.system.PathClassLoader[/data/app/com.example.viewpager-2.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.view.LayoutInflater.createView(LayoutInflater.java:471)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
... 33 more
change adapter to:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
int layouts[];
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
layouts=new int[]{R.layout.fragment_slide_screen_page1,R.layout.fragment_slide_screen_page2,R.layout.fragment_slide_screen_page3,R.layout.fragment_slide_screen_page4,R.layout.fragment_slide_screen_page5};
}
#Override
public Fragment getItem(int position) {
ScreenSlidePageFragment fragment=new ScreenSlidePageFragment();
fragment.setContent(layouts[position]);
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
and in fragment:
public class ScreenSlidePageFragment extends Fragment {
int layout;
public void setContent(int layout){
this.layout=layout;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(layout, container, false);
return rootView;
}
}
Although not sure what change you want in each fragment but the above will require you to create 5 layout xmls that you can set every time you create a new Fragment.
Even I encountered crash.
This is because I was calling mAdapter.notifyDataSetChanged(); inside
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
Later I shifted the method to
#Override
public void onPageSelected(int arg0) {
mAdapter.notifyDataSetChanged();
}
So that did the trick

Cannot launch DialogPreference programmatically (Null Pointer Exception thrown)

I have a custom class that extends DialogPreference. It works perfectly if launched from the Preference menu. I want to be able to launch it from an Activity as well. Below is my DialogPreference class in which I exposed the showDialog() method suggested by this thread. When I call it I get a Null Pointer Exception but haven't been able to figure out why.
The error is thrown at line 27 which is in onBindDialogView() where hText.setText() is called.
package com.jumptuck.recipebrowser;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
// Pop-up dialog used to set and modify host and login credentials
public class HostCredentialsDialogPreference extends DialogPreference {
static final String TAG = "HostCredentialsDialogPreference";
EditText hText, uText, pText;
public HostCredentialsDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_host_credentials);
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
Log.d(TAG,"onBindDialogView");
SharedPreferences sp = getSharedPreferences();
hText.setText(sp.getString("host", ""));
uText.setText(sp.getString("username", ""));
pText.setText(sp.getString("password", ""));
}
#Override
protected View onCreateDialogView() {
// Guide for this technique found at:
// http://alexfu.tumblr.com/post/23683149440/android-dev-custom-dialogpreference
Log.d(TAG,"onCreateDialogView");
View root = super.onCreateDialogView();
hText = (EditText) root.findViewById(R.id.host);
uText = (EditText) root.findViewById(R.id.username);
pText = (EditText) root.findViewById(R.id.password);
return root;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult){
Log.d(TAG,"Clicked Save");
SharedPreferences sp = getSharedPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putString("host", hText.getText().toString());
editor.putString("username", uText.getText().toString());
editor.putString("password", pText.getText().toString());
editor.commit();
}
else {
Log.d(TAG,"Clicked Cancel");
}
}
void show() {
showDialog(null);
}
}
I'm using a "Testing" button try to launch the dialog from another Activity:
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected");
switch (item.getItemId()) {
case R.id.item_prefs:
startActivity(new Intent(this, PrefsActivity.class));
return true;
case R.id.refresh:
if (credentialsExist()) {
refreshListView();
}
return true;
case R.id.recipe_dir:
startActivity(new Intent(this, RecipeDisplayActivity.class));
return true;
case R.id.testing:
HostCredentialsDialogPreference hc = new HostCredentialsDialogPreference(this, null);
hc.show();
return true;
default:
return false;
}
}
Here are the xml files for my Preference and the Dialog Preference:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<com.jumptuck.recipebrowser.HostCredentialsDialogPreference
android:key="dialog_credentials"
android:title="Server Address and Login"
android:summary="Set Host, Username and Password" />
</PreferenceScreen>
and
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/dialog_hostname_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dialog_hint_uri" />
<EditText
android:id="#+id/host"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textUri" />
<TextView
android:id="#+id/dialog_username_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dialog_hint_user" />
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
<TextView
android:id="#+id/dialog_password_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dialog_hint_password" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:inputType="textPassword" />
</LinearLayout>
And finally the Logcat:
D/RecipeListActivity( 5894): onOptionsItemSelected
D/HostCredentialsDialogPreference( 5894): onCreateDialogView
D/HostCredentialsDialogPreference( 5894): onBindDialogView
D/AndroidRuntime( 5894): Shutting down VM
W/dalvikvm( 5894): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
E/AndroidRuntime( 5894): FATAL EXCEPTION: main
E/AndroidRuntime( 5894): java.lang.NullPointerException
E/AndroidRuntime( 5894): at com.jumptuck.recipebrowser.HostCredentialsDialogPreference.onBindDialogView(HostCredentialsDialogPreference.java:27)
E/AndroidRuntime( 5894): at android.preference.DialogPreference.showDialog(DialogPreference.java:289)
E/AndroidRuntime( 5894): at com.jumptuck.recipebrowser.HostCredentialsDialogPreference.show(HostCredentialsDialogPreference.java:62)
E/AndroidRuntime( 5894): at com.jumptuck.recipebrowser.RecipeListActivity.onOptionsItemSelected(RecipeListActivity.java:192)
E/AndroidRuntime( 5894): at android.app.Activity.onMenuItemSelected(Activity.java:2534)
E/AndroidRuntime( 5894): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:958)
E/AndroidRuntime( 5894): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
E/AndroidRuntime( 5894): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
E/AndroidRuntime( 5894): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
E/AndroidRuntime( 5894): at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:166)
E/AndroidRuntime( 5894): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
E/AndroidRuntime( 5894): at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
E/AndroidRuntime( 5894): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2859)
E/AndroidRuntime( 5894): at android.widget.AbsListView$1.run(AbsListView.java:3533)
E/AndroidRuntime( 5894): at android.os.Handler.handleCallback(Handler.java:615)
E/AndroidRuntime( 5894): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 5894): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 5894): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 5894): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 5894): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 5894): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime( 5894): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 5894): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 148): Force finishing activity com.jumptuck.recipebrowser/.RecipeListActivity
W/WindowManager( 148): Failure taking screenshot for (246x410) to layer 21025
W/ActivityManager( 148): Activity pause timeout for ActivityRecord{412097e0 com.jumptuck.recipebrowser/.RecipeListActivity}
I/Choreographer( 281): Skipped 39 frames! The application may be doing too much work on its main thread.
W/ActivityManager( 148): Activity destroy timeout for ActivityRecord{412097e0 com.jumptuck.recipebrowser/.RecipeListActivity}
Anyone idea what I'm doing wrong? Thanks!
The best answer can be found here but I think it needs just a bit of clarification because that answer wrongly suggests two different style declarations for the manifest.
If you want to launch one dialog from an Activity and still be able to launch it form a Preference you just need to create an Activity that launches the Dialog. That Activity can then be launched as an intent in the Preference XML or from another Activity. The trick comes in how you style it. You want to style the Activity as a Dialog. This way the dialog that your Activity launches will looks right. The side effect of this approach is that a floating Action Bar will be show in the middle of the screen behind your Dialog. The fix for that is to use a Dialog style with no ActionBar. I'm using Holo.Light theme so I put this in my AndroidManifest
<activity android:name=".DemoDialogActivity"
android:theme="#android:style/Theme.Holo.Light.Dialog.NoActionBar" />
The other part of the puzzle is to make sure you call finish(); when you're done (It's the last thing I did in the OnClickListener for both of my buttons). If you don't, the dialog will close but the Activity will still be open, leaving a small blank rectangle in the middle of a darkened screen.
Here's a working example of the Activity:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
public class DemoDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater lf = LayoutInflater.from(this);
// This adds XML elements as a custom view (optional):
final View customElementsView = lf.inflate(
R.layout.activity_credentials, null);
AlertDialog alert = new AlertDialog.Builder(this)
// This adds the custom view to the Dialog (optional):
.setView(customElementsView)
.setTitle("This is the Title")
.setMessage("This is the AlertDialog message (optional)")
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// Cancel was clicked; do something
// Close Activity
finish();
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// OK was clicked; do something
// Close Activity
finish();
}
}).create();
// Show the dialog
alert.show();
}
}
Launch it programmatically:
Intent launch_dialog = new Intent(getApplicationContext(),
DemoDialogActivity.class);
startActivity(launch_dialog);
Or as a Preference in XML:
<Preference
android:key="demo_dialog"
android:title="Title of item on Prefs screen"
android:summary="This will be small text below the title">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.example.package.DemoDialogActivity"
android:targetPackage="com.example.package" />
</Preference>
I've been working on this for some time now. There is one workaround which I find entirely inelegant. I can just use the xml layout to build a DialogFragment by making changes in the Activity:
class HCDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_host_credentials, null);
builder.setView(view);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.setTitle(R.string.dialog_title);
return builder.create();
}
}
The DialogFragment can be launched from a button like this (case statement is from the code pasted as part my original question):
case R.id.testing:
FragmentManager fm = getFragmentManager();
HCDialog hack_dialog = new HCDialog();
hack_dialog.show(fm, null);
return true;
This works. But to me it seems rather silly and I imagine I'm taking the long way around. Especially because now I'll be coding to handle persistent preference values for two versions of what appears to be the exact same dialog.
Is there a better way?

Android Location DistanceTo null

package com.competitivegamingaudio;
import android.app.Activity;
import android.content.Context;
import android.location.*;
import android.os.Bundle;
import android.util.Log;
import android.widget.*;
import com.google.android.maps.*;;
public class FindMyFriendsActivity extends Activity {
private static final String TAG = "FindMyFriendsActivity";
public TextView LocationLabel;
public TextView DistanceLabel;
public MapView myMapView;
public Location oldlocation;
public Location currentlocation;
#Override
public void onResume()
{
super.onResume();
LocationManager locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationLabel=(TextView) findViewById(R.id.LocationLabel);
DistanceLabel=(TextView)findViewById(R.id.DistanceLabel);
}
LocationListener locationListener =new LocationListener()
{
public void onLocationChanged (Location location)
{
currentlocation=new Location(location);
LocationLabel.setText(location.toString());
oldlocation=new Location(location);
DistanceLabel.setText("Distance: "+calculatedistance(currentlocation,oldlocation));
}
public String calculatedistance(Location a, Location b)
{
a.distanceTo(b);
return ""+a;
}
public void onStatusChanged(String provider, int status, Bundle extras)
{}
public void onProviderEnabled(String provider)
{
}
public void onProviderDisabled(String provider)
{}
};
}
I'm having trouble getting this code to work properly. I want to be able to calculate the distance between two Locations. The initial location that's being passed to the onLocationChanged method is working (which proves I have the right conditions), because when I do LocationLabel.setText(location.toString()); that works properly without getting any null pointer exceptions. However, when the calculatedistance method is called in line 49, the a.distanceTo(b); line fails on line 54. Any idea why the distanceTo method keeps failing?
Error Message:
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): java.lang.NullPointerException
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at com.competitivegamingaudio.FindMyFriendsActivity$1.onLocationChanged(FindMyFriendsActivity.java:47)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:227)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:160)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:176)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at android.os.Handler.dispatchMessage(Handler.java:99)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at android.os.Looper.loop(Looper.java:130)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at android.app.ActivityThread.main(ActivityThread.java:3821)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at java.lang.reflect.Method.invokeNative(Native Method)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at java.lang.reflect.Method.invoke(Method.java:507)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-09 20:11:58.085: ERROR/AndroidRuntime(9716): at dalvik.system.NativeStart.main(Native Method)
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/LocationLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<TextView
android:id="#+id/DistanceLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
OK, there are a lot of things I'd change about your code but here's not the place. To attempt to fix your problem try this...
// package and imports here
public class FindMyFriendsActivity extends Activity {
// TAG, TextViews, MapView, Locations as before but add
// LocationManager and LocationListener here as below...
LocationManager locationManager = null;
LocationListener locationListener = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationLabel = (TextView)findViewById(R.id.LocationLabel);
DistanceLabel = (TextView)findViewById(R.id.DistanceLabel);
locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
// Put LocationListener methods here
}
}
#Override
public void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
Solved by copying DistanceLabel from my Java code and pasting it over the similar DistanceLabel in main.xml. All the characters appear the same but it fixed it. Perhaps looking at it in a hex editor would help but for now I'm just glad it's working. Thanks MisterSquonk.

Categories