Using boilerpipe in Android - java

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...

Related

java.lang.NullPointerException null object reference viewpager

I am stuck while coding and need help on that.
I am using view binding in my project.
I have unable binding and that is working fine.
I have used same code in my earlier project except view binding and that project was working fine.
Here is my XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context=".Home">
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_navigation_menu" />
</RelativeLayout>
Here is my Java code
package com.example.professionals;
public class Home extends AppCompatActivity {
private ActivityHomeBinding Homebinding;
protected ViewPager viewPager;
protected Mypager_Adapter mypager_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Homebinding = ActivityHomeBinding.inflate(getLayoutInflater());
View view = Homebinding.getRoot();
setContentView(view);
Homebinding.pager.findViewById(R.id.pager);
mypager_adapter = new Mypager_Adapter(this);
viewPager.setAdapter(mypager_adapter);
Homebinding.bottomNavigation.setOnItemSelectedListener(new
NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
showMsg("Home");
break;
case R.id.profile:
showMsg("Profile");
break;
}
return false;
}
});
}
private void showMsg(String msg) {
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
toast.show();
}
}
Here is the error list
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.professionals, PID: 17743
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.professionals/com.example.professionals.Home}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2473)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
at android.app.ActivityThread.access$1100(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5582)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
at com.example.professionals.Home.onCreate(Home.java:32)
at android.app.Activity.performCreate(Activity.java:6321)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535) 
at android.app.ActivityThread.access$1100(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5582) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Thanks in advance for help!
You need to add
viewPager = findViewById<ViewPager>(R.id.pager)
Before this line
viewPager.setAdapter(mypager_adapter);
Edit:
Actually it seems like you're attempting to use ViewBinding as well as regular findViewById, if I were you I'd stick with ViewBinding and delete this line
protected ViewPager viewPager;
Then try this instead
Homebinding.pager.setAdapter(mypager_adapter);
You haven't initialize your ViewPager.
You need initialize your viewPager. For that you have couple of options
Initialize with findViewById before setting adapter.
viewPager = findViewById(R.id.pager)
As you are using view binding would be the good idea
Homebinding.pager.setAdapter(mypager_adapter)

java android crash setOnClickListener

i am new in android and i was trying to make my app works in all phones
it works in 23 API and don't work in 19 API kitkat it crashes each time i open the application
Is there a way to fix this problem ?
and could you tell me what was my problem and explain it to me,
public class MainActivity extends AppCompatActivity {
private Button ButtonStart,ButtonReset ;
private TextView Number ;
private CountDownTimer myTimer ;
private MediaPlayer TimePassesSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
ButtonReset = (Button)findViewById (R.id.button2);
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
}
public void addListerOnButton () {
ButtonStart.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if (ButtonStart.getText ().toString () != "Stop") {
int StartTime = Integer.parseInt (Number.getText ().toString ());
myTimer = new CountDownTimer (StartTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
ButtonStart.setText ("Stop");
Number.setText (""+millisUntilFinished / 1000);
}
public void onFinish() {
Number.setText("60");
ButtonStart.setText ("Start");
TimePassesSound.setLooping(false);
TimePassesSound.start();
}
}.start();
} else {
ButtonStart.setText ("Start");
myTimer.cancel ();
}
}
}
);
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
-- Error messages
Process: com.aabdelrahman730yahoo.mydesign, PID: 3627
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aabdelrahman730yahoo.mydesign/com.aabdelrahman730yahoo.mydesign.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
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:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Main Activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.aabdelrahman730yahoo.mydesign.MainActivity"
android:touchscreenBlocksFocus="false"
android:background="#34416a">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:id="#+id/textView"
android:singleLine="true"
android:textSize="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
That's was my full problem i hope someone could help me with
You are calling the method of the view without initializing it.
You need to initialize the view first and then call the method
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
Check this,
As #Rod_ mentioned and from error log, it clearly states that view is not initialized.
java.lang.NullPointerException
at
com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at
com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
Make sure following buttons were initialized in your java code.
ButtonStart and ButtonReset -- Buttonreset is not initialized here it seems.
Change your code like below.
under oncreate
ButtonStart = (Button)findViewById (R.id.button);
ButtonReset = (Button)findViewById (R.id.button_); --> You missed it ..
Number = (TextView)findViewById (R.id.textView);
addListerOnButton ();
addListerOnButton2 ();
Hope it seems clear..!!
UPDATE:
You may not initialized the media player.
The problem may be also due to usage of media player. Kindly check the code below.
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
in your case
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
Add the above lines befor calling the functions.

Create Popup with Runnable Thread Android

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);

How setText to custom dialog from one class in others?

I have created a dialog class that i would like to use in several other classes and depending in what class they should display different info. I have no problem displaying the dialog itself with working button and an already set text from the xml. But when i try to set my own text with setText the app crashes and give me java.lang.NullPointerException. What can be the problem ?
Here is my custom dialog class
public class CustomDialogInfoClass extends Dialog implements View.OnClickListener {
Button ok;
TextView myTextView;
Typeface myFont;
public CustomDialogInfoClass(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog_not_demo);
CustomDialogInfoClass c = new CustomDialogInfoClass(getContext());
ok = (Button)findViewById(R.id.btnOk);
myTextView = (TextView) c.findViewById(R.id.textViewDialog);
ok.setOnClickListener(this);
myFont = Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf");
ok.setTypeface(myFont);
myTextView.setTypeface(myFont);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnOk:
dismiss();
break;
default:
}
dismiss();
}
}
And here is my main where I try to call it;
public class MainActivity extends ActionBarActivity {
TextView myTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomDialogInfoClass dialogInfo = new CustomDialogInfoClass(this);
myTextview = (TextView) findViewById(R.id.textViewDialog);
myTextview.setText("Lorem ipsum dolor sit amet"); <----Null.pointer error
dialogInfo.show();
}
xml
<?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="200dp"
android:orientation="vertical"
android:background="#drawable/diabox"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textViewDialog"
android:layout_margin="15dp"
android:textColor="#android:color/white"
android:text="Test text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ok"
android:id="#+id/btnOk"
android:layout_gravity="center_horizontal" />
and logcat if that helps?
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.name.appname/com.example.name.appname.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2221)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.access$800(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5064)
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:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:613)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.name.appnamne.MainActivity.onCreate(MainActivity.java:35)
at android.app.Activity.performCreate(Activity.java:6084)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2280)
            at android.app.ActivityThread.access$800(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1202)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5064)
            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:797)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:613)
            at dalvik.system.NativeStart.main(Native Method)
you shouldn't access your text view from activity
in your dialog you have this constructor
public CustomDialogInfoClass(Context context) {
super(context);
}
so make this one too:
public CustomDialogInfoClass(Context context,String text) {
CustomDialogInfoClass(context);
this.text = text;
}
and make a String field in your dialog class
String text;
and setup your TextView in the dialog
myTextView = (TextView) c.findViewById(R.id.textViewDialog);
myTextView.setText(text);
and in your activity pass your text here:
CustomDialogInfoClass c = new CustomDialogInfoClass(getContext(), "MY TEXT");
You need to set the value of the TextView from inside your dialog during onCreate method.
To pass parameters to the dialog the proper way would be to have a static method in you Dialog class that return a new instance of the Object.
This method can accept paramaters and put them in a Bundle. Now you can set this bundle as argument to the created Dialog
public static YourDialog getInstance(String par1, int par2) {
YourDialog dialog = new YourDialog()
Bundle bundle = new Bundle();
bundle.putString(TAG, par1);
bundle.putInt(TAG2, par2);
dialog.setArguments(bundle);
return dialog;
}
At this point in the OnCreate method of your dialog you can get the Bundle using getArguments() using the tag you provided before and set your TextView
Once you have done in your MainActivity get an Instance of the dialog and call show() to show it
Hope it helps

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?

Categories