i m trying to create popup with runnable but i m not able to. i always get "NULLPOINTEREXPEXTIONS" i m almost done with my android app, the only thing left is show popup after some time, i used runnable to show popup
here is my code, ERROR generate this line
View layout = inflater.inflate(R.layout.popup_layout,(ViewGroup) findViewById(R.id.popup_element));
NOTE : popup_element is ID of popup layout xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
android:orientation="vertical"
android:padding="10sp" >
public void run() {
//Do something after 100ms
initiatePopupWindow();
}
private void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup_layout,(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 300, 370, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
Button btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();
}
};
}, 700);
}
}
ERROR LOG
D/gralloc_goldfish(906): Emulator without GPU emulation detected.
W/System.err(906): java.lang.NullPointerException
W/System.err(906): at com.example.runnable_with_popup.MainActivity$1.initiatePopupWindow(MainActivity.java:43)
W/System.err(906): at com.example.runnable_with_popup.MainActivity$1.run(MainActivity.java:34)
W/System.err(906): at android.os.Handler.handleCallback(Handler.java:730)
W/System.err(906): at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err(906): at android.os.Looper.loop(Looper.java:137)
W/System.err(906): at android.app.ActivityThread.main(ActivityThread.java:5103)
W/System.err(906): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(906): at java.lang.reflect.Method.invoke(Method.java:525)
W/System.err(906): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
W/System.err(906): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
W/System.err(906): at dalvik.system.NativeStart.main(Native Method)
Please help me out from this problem. i searched over internet but did not found example or question related to my problem
help will be appreciated
thanks
The parent might be missing, put false on the last part
View layout = inflater.inflate(R.layout.popup_layout,(ViewGroup) findViewById(R.id.popup_element),false);
use this one
View popupView = layoutInflater.inflate(R.layout.popup_layout, null);
Related
Note: I'm using the YouTube Android Player API
Expected behavior:
The activity remains in portrait mode when the video is not fullscreen (Enforced by AndroidManifest ok).
The activity is set to landscape orientation when the video enters fullscreen mode (ok).
The activity returns to portrait orientation when the user exits fullscreen mode (ExceptionInInitializerError occurs here).
See the problem in action here
YouTubeFailureRecoveryActivity.java (This is included in the library under sample/src/com/examples/youtubeapidemo)
Main Activity
package test.testapp;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeFailureRecoveryActivity implements YouTubePlayer.OnFullscreenListener {
static final String API_KEY = "PLACE YOUTUBE DATA API KEY HERE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
youTubePlayer.setOnFullscreenListener(this);
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
if(!wasRestored){
youTubePlayer.cueVideo("wKJ9KzGQq0w");
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
#Override
public void onFullscreen(boolean isFullscreen) {
if(isFullscreen){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else if(!isFullscreen){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
tools:context="test.testapp.MainActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</com.google.android.youtube.player.YouTubePlayerView>
</LinearLayout>
Stack trace
06-10 09:47:09.205 2646-2646/test.testapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
at android.view.View.dispatchSaveInstanceState(View.java:11839)
at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2576)
at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.View.saveHierarchyState(View.java:11822)
at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1566)
at android.app.Activity.onSaveInstanceState(Activity.java:1188)
at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
at android.app.Activity.performSaveInstanceState(Activity.java:1137)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1215)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3486)
at android.app.ActivityThread.access$700(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoClassDefFoundError: rt
at rs.<clinit>(SourceFile:17)
at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
at android.view.View.dispatchSaveInstanceState(View.java:11839)
at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2576)
at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.View.saveHierarchyState(View.java:11822)
at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1566)
at android.app.Activity.onSaveInstanceState(Activity.java:1188)
at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
at android.app.Activity.performSaveInstanceState(Activity.java:1137)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1215)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3486)
at android.app.ActivityThread.access$700(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Looks like the application is crashing when restarting because of a configuration change
https://developer.android.com/guide/topics/resources/runtime-changes.html
You can disable the automatic activity recreation for orientation changes, and handle it yourself.
To do that, add
android:configChanges="orientation|screenLayout|screenSize"
With orientation alone it probably works, but the other ones I think were triggered also on some devices.
You can then override onConfigurationChanged() to do stuff on an orientation change if you need it, like showing / hiding views, etc.. as Android will not recreate your layouts automatically (that's what it does when restarts the activity on an orientation change)
So you can do:
#Override
public void onConfigurationChanged(final Configuration newConfiguration) {
Log.wtf(
"Orientation",
newConfiguration.orientation == Configuration.ORIENTATION_PORTRAIT
? "portrait"
: "landscape"
);
}
i am try to implement a numberPicker to select minute values.
But i am getting a NullPointer Exception at this line:
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
Following Code:
public class MainActivity extends Activity {
NumberPicker minutePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Auswahl Minuten zum starten / Stoppen aller
minutePicker = new NumberPicker(MainActivity.this);
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
minutePicker.setMaxValue(30);
minutePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
abschaltzeit = minutePicker.getValue();
}
});
minutePicker.setValue(0);
minutePicker.setWrapSelectorWheel(false);
}
}
XML:
<NumberPicker
android:id="#+id/minuten_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="6"
android:layout_column="0"
android:paddingLeft="20dp" />
Log:
09-25 11:00:09.749 10687-10687/de.carsten.awesome.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.carsten.awesome.app, PID: 10687
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.carsten.awesome.app/de.carsten.awesome.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at de.carsten.awesome.app.MainActivity.onCreate(MainActivity.java:83)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
minutePicker = new NumberPicker(MainActivity.this);
minutePicker = (NumberPicker) findViewById(R.id.minuten_picker);
You're creating a NumberPicker programmatically and then overwriting the reference with whatever findViewById() returns. It returns null if your activity_main layout does not contain a minuten_picker.
Choose only the other: either create it prorgrammatically or find it from a view hierarchy you inflated.
If you choose the programmatic way new NumberPicker(), remember to add it to some layout in your activity view hierarchy, e.g. with setContentView()
If you choose the inflation way, make sure you have the view in your XML layout file.
I'm guessing the NPE you're seeing is actually on the following line where you're trying to invoke a method on the minutePicker and it's null.
I apologize.
I moved the Code from the MainActivity in the creating Fragment and it works with rootView.findView.
Sorry but i am new with the Fragement Konzept.
Thanks a lot for your help !
Boilerpipe is a library that basically extracts the main content from a webpage. For news websites, it is especially hard to extract the content as the formatting differs from site to site. So I've tried to integrate the boilerpipe library - https://code.google.com/p/boilerpipe/wiki/QuickStart
As per the installing guide, I have added the following to my Java classpath - boilerpipe-VERSION.jar, nekohtml-1.9.13.jar and xerces-2.9.1.jar
What I'm trying to do with boilerpipe and my application flow that involves it
I have a list view where there are a list of articles. I've set up an onItemClickListener such that when you click on any of the items on the listview, it takes the url specific to that article and uses boilerpipe to extract the text from that article and starts a new activity where it is printed in textview.
The Problem
My application crashes once I click on one of the items in the list.
a. I'm not sure if the code I've written is correct, as I'm a beginner. Please excuse me for that. If it is incorrect, how can I fix it? I have a feeling it may be a problem with the url.
b. If I haven't installed boilerplate correctly, what is the correct way of doing it
List Activity:
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), ArticleActivity.class);
// getting page url
String page_url = ((TextView) view.findViewById(R.id.page_url)).getText().toString();
Toast.makeText(getApplicationContext(), page_url, Toast.LENGTH_SHORT).show();
URL url = null;
try {
url = new URL(page_url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// NOTE: Use ArticleExtractor unless DefaultExtractor gives better results for you
try {
String text = null;
text = ArticleExtractor.INSTANCE.getText(url);
in.putExtra("text", text);
} catch (BoilerpipeProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(in);
});
}
Article Activity:
public class ArticleActivity extends Activity{
Intent in = getIntent();
String text = in.getStringExtra("text");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.article_view);
TextView tv;
tv = (TextView) findViewById(R.id.page_url);
tv.setText(text);
}
}
article_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Article Title -->
<TextView android:id="#+id/content_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:paddingBottom="8dp"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#dc6800"/>
</RelativeLayout>
Stack Trace:
USER_COMMENT=null
ANDROID_VERSION=4.1.2
APP_VERSION_NAME=1.0
BRAND=samsung
PHONE_MODEL=GT-N8000
CUSTOM_DATA=
STACK_TRACE=android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
at libcore.net.http.HttpURLConnectionImpl.getHeaderField(HttpURLConnectionImpl.java:130)
at java.net.URLConnection.getContentType(URLConnection.java:326)
at de.l3s.boilerpipe.sax.HTMLFetcher.fetch(HTMLFetcher.java:35)
at de.l3s.boilerpipe.extractors.ExtractorBase.getText(ExtractorBase.java:87)
at com.j.infographx.ListRSSItemsActivity$1.onItemClick(ListRSSItemsActivity.java:94)
at android.widget.AdapterView.performItemClick(AdapterView.java:301)
at android.widget.AbsListView.performItemClick(AbsListView.java:1287)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3078)
at android.widget.AbsListView$1.run(AbsListView.java:4161)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Looks like this doesn't have anything to do with BoilerPlate, but rather the fact that you're making a network call on the main thread. I recommend you check out this thread regarding the problem.
i thing its common problem... u just use AsyncTask. see that....
Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`
don't block main ui use child thread...
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?
I am using this library https://github.com/chrisbanes/Android-PullToRefresh for implementing a refreshable grid view and i am getting this error:
android.view.InflateException: Binary XML file line #8: Error inflating class com.handmark.pulltorefresh.library.PullToRefreshGridView
at android.view.LayoutInflater.createView(LayoutInflater.java:518)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at com.example.retrievetweets.FragmentPhotos.onCreateView(FragmentPhotos.java:55)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)
at android.support.v4.view.ViewPager.populate(ViewPager.java:880)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:238)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
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.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
at android.view.LayoutInflater.createView(LayoutInflater.java:505)
... 24 more
Caused by: java.lang.NullPointerException
at com.handmark.pulltorefresh.library.internal.IndicatorLayout.<init>(IndicatorLayout.java:66)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.addIndicatorViews(PullToRefreshAdapterViewBase.java:355)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.updateUIForMode(PullToRefreshAdapterViewBase.java:328)
at com.handmark.pulltorefresh.library.PullToRefreshBase.init(PullToRefreshBase.java:1142)
at com.handmark.pulltorefresh.library.PullToRefreshBase.<init>(PullToRefreshBase.java:113)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.<init>(PullToRefreshAdapterViewBase.java:74)
at com.handmark.pulltorefresh.library.PullToRefreshGridView.<init>(PullToRefreshGridView.java:35)
... 27 more
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- The PullToRefreshGridView replaces a standard GridView widget. -->
<com.handmark.pulltorefresh.library.PullToRefreshGridView
xmlns:ptr="http://schemas.android.com/apk/res-auto"
android:id="#+id/pull_refresh_grid"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="0dp"
android:horizontalSpacing="1dp"
android:columnWidth="80dp"
android:stretchMode="columnWidth"
android:gravity="fill"
ptr:ptrMode="both"
ptr:ptrDrawable="#drawable/default_ptr_rotate"
/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:indeterminateOnly="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
And here is the java code for the method onCreateView in FragmentPhotos (the line 55 is this one "ll = (RelativeLayout) inflater.inflate(R.layout.activity_grid_view,"):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ref = "";
fa = getActivity();
ll = (RelativeLayout) inflater.inflate(R.layout.activity_grid_view,
container, false);
bar = (ProgressBar) ll.findViewById(R.id.progressBar);
mPullRefreshGridView = (PullToRefreshGridView) ll
.findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView
.setOnRefreshListener(new OnRefreshListener<GridView>() {
#Override
public void onRefresh(
PullToRefreshBase<GridView> refreshView) {
// TODO Auto-generated method stub
if (NetworkReceiver.mobileConnected) {
new GetDataTaskWhitoutLoading().execute();
} else {
Toast.makeText(
getActivity(),
"Ahora mismo no se pueden cargar nuevos datos."
+ " Comprueba la conexi—n a Internet.",
Toast.LENGTH_LONG).show();
mPullRefreshGridView.onRefreshComplete();
}
}
});
mGridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
// Do something in response to the click
Intent intent = new Intent(fa, ImageSelected.class);
intent.putExtra("URL_image", mListItems.get(position)
.subSequence(0, mListItems.get(position).length() - 6));
startActivity(intent);
}
});
mListItems = new ArrayList<String>();
mAdapter = new FotosItemAdapter(fa, R.layout.image_group, mListItems);
mGridView.setAdapter(mAdapter);
if (NetworkReceiver.mobileConnected) {
GetDataTask.newInstance(bar).execute();
}
return ll;
}
Thank you!!
Are you importing in your classhpath on eclipse?
Pull to refhresh is a lib for android,then import like this:
project properties> android> add lib.
In my case it solved by adding this to my project.properties :
target=android-19
android.library.reference.1=../library
that library is the name of the handmark library.
hope be useful.