Dialog Fragment throws null pointer exception after implementing it into MainActivity - java

I am trying to use a AlertDialog in my application, but it requires an input to be given. So i was forced to create an interface and override the onAttach() method within my custom DialogFragment class. Once i properly set everything in both the Dialog class and MainActivity, i tried to run my app and it gave me a runtime exception referring to nullpointer among other things. im not sure why this is and i am in need of assistance, please help. Below you will wind the Override of my interface method, the place where my .show() method is called, the code for my DialogFragment class, and my error log lastly.
public class MainActivity extends FragmentActivity implements CDia_exp.NDListener
{
//Integers and Strings for performing calculations
int a;
int b;
static int deci_cnt;
int cnt;
int temp;
Double exp_x;
Double exp;
Double [] num_trk;
String [] op_trk;
String num_hold;
String op_hold;
String del_hold;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//....Lots of other code here.......
//Exp_x Button
opSet[6].setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(num_hold != "")
{
cDia_exp.show(getSupportFragmentManager(), "exp_x");
del_hold = tViews[0].getText().toString();
for(int x = num_hold.length() - 1; x >= 0; x--)
{
del_hold = del_hold.substring(0, del_hold.length() - 1);
}
num_hold = exp.toString();
tViews[0].setText(del_hold + num_hold);
return;
}
else
{
return;
}
}
});
}
//Objects and Overrides for calling foreign functions
CTrim cTrim = new CTrim();
CDia cDia = new CDia();
CDia_exp cDia_exp = new CDia_exp();
EditText exp_inp = (EditText) findViewById(R.id.exp_inp);
#Override
public void onDPClick(DialogFragment dialog)
{
exp = Double.parseDouble(num_hold);
exp_x = Double.parseDouble(exp_inp.getText().toString());
for(double x = exp_x; x > 0; x--)
{
exp *= exp;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
My Custom DialogFragment class
package com.example.musicalc;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
public class CDia_exp extends DialogFragment
{
public interface NDListener
{
public void onDPClick(DialogFragment dialog);
}
NDListener expListener;
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
expListener = (NDListener) activity;
}
catch(ClassCastException e)
{
throw new ClassCastException(activity.toString() + "does not implement NDListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder aDia = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
aDia.setView(inflater.inflate(R.layout.calc_dia, null)).setPositiveButton(R.string.diaOk_b, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
expListener.onDPClick(CDia_exp.this);
}
}).setNegativeButton(R.string.cancel_b, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
getDialog().cancel();
}
});
return aDia.create();
}
}
And Now the Error Log
07-20 14:23:43.599: E/Trace(24173): error opening trace file: No such file or directory (2)
07-20 14:23:43.622: D/AndroidRuntime(24173): Shutting down VM
07-20 14:23:43.622: W/dalvikvm(24173): threadid=1: thread exiting with uncaught exception (group=0x4137d2a0)
07-20 14:23:43.653: E/AndroidRuntime(24173): FATAL EXCEPTION: main
07-20 14:23:43.653: E/AndroidRuntime(24173): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.musicalc/com.example.musicalc.MainActivity}: java.lang.NullPointerException
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2060)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2174)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.access$700(ActivityThread.java:141)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1267)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.os.Looper.loop(Looper.java:137)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.main(ActivityThread.java:5059)
07-20 14:23:43.653: E/AndroidRuntime(24173): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 14:23:43.653: E/AndroidRuntime(24173): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 14:23:43.653: E/AndroidRuntime(24173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
07-20 14:23:43.653: E/AndroidRuntime(24173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
07-20 14:23:43.653: E/AndroidRuntime(24173): at dalvik.system.NativeStart.main(Native Method)
07-20 14:23:43.653: E/AndroidRuntime(24173): Caused by: java.lang.NullPointerException
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.Activity.findViewById(Activity.java:1851)
07-20 14:23:43.653: E/AndroidRuntime(24173): at com.example.musicalc.MainActivity.<init>(MainActivity.java:43)
07-20 14:23:43.653: E/AndroidRuntime(24173): at java.lang.Class.newInstanceImpl(Native Method)
07-20 14:23:43.653: E/AndroidRuntime(24173): at java.lang.Class.newInstance(Class.java:1319)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
07-20 14:23:43.653: E/AndroidRuntime(24173): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2051)
07-20 14:23:43.653: E/AndroidRuntime(24173): ... 11 more
07-20 14:25:56.817: E/Trace(24308): error opening trace file: No such file or directory (2)
07-20 14:25:56.934: D/AndroidRuntime(24308): Shutting down VM
07-20 14:25:56.934: W/dalvikvm(24308): threadid=1: thread exiting with uncaught exception (group=0x4137d2a0)
07-20 14:25:57.013: E/AndroidRuntime(24308): FATAL EXCEPTION: main
07-20 14:25:57.013: E/AndroidRuntime(24308): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.musicalc/com.example.musicalc.MainActivity}: java.lang.NullPointerException
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2060)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2174)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.access$700(ActivityThread.java:141)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1267)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.os.Looper.loop(Looper.java:137)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.main(ActivityThread.java:5059)
07-20 14:25:57.013: E/AndroidRuntime(24308): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 14:25:57.013: E/AndroidRuntime(24308): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 14:25:57.013: E/AndroidRuntime(24308): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
07-20 14:25:57.013: E/AndroidRuntime(24308): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
07-20 14:25:57.013: E/AndroidRuntime(24308): at dalvik.system.NativeStart.main(Native Method)
07-20 14:25:57.013: E/AndroidRuntime(24308): Caused by: java.lang.NullPointerException
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.Activity.findViewById(Activity.java:1851)
07-20 14:25:57.013: E/AndroidRuntime(24308): at com.example.musicalc.MainActivity.<init>(MainActivity.java:803)
07-20 14:25:57.013: E/AndroidRuntime(24308): at java.lang.Class.newInstanceImpl(Native Method)
07-20 14:25:57.013: E/AndroidRuntime(24308): at java.lang.Class.newInstance(Class.java:1319)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
07-20 14:25:57.013: E/AndroidRuntime(24308): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2051)
07-20 14:25:57.013: E/AndroidRuntime(24308): ... 11 more

Thanks to some experimentation and some research on stackoverflow i have located the answer.
The problem is that the compiler was having trouble locating the view either because it is in a separate xml file from my activity_main.xml file or because i was creating my dialog within a separate class from my MainActiviy.java.
To solve this i created my dialog within my MainActivity.java class outside of the onCreate method. Also i created a layout inflater to inflate my layout within a View in my MainActivity, which was key because the LayoutInflater provided a way to directly call my EditText into code.
The code that fixed the nullpointer when declaring my EditText is as follows:
LayoutInflater inflater = LayoutInflater.from(this);
//Inflater "inflates" layout into View as a value
final View infV = inflater.inflate(R.layout.calc_dia, null);
//Use layout value inflated in View "infV" to find EditText
final EditText eDTemp = (EditText) infV.findViewById(R.id.expInp);
***The full code for the dialog is as follows****:
public void showCD()
{
LayoutInflater inflater = LayoutInflater.from(this);
final View infV = inflater.inflate(R.layout.calc_dia, null);
final EditText eDTemp = (EditText)infV.findViewById(R.id.expInp);
TextView tView0 = (TextView)findViewById(R.id.calcView);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(infV).setPositiveButton("Ok", new
DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
}}).setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
builder.show();
}
When you are ready for the dialog to appear, simply call the function that contains it.

Related

why component == null in dagger 2?

It seems that it just created AppComponent and then delete it. In other my projects it's works correctly. Why appComponent become null and how to make it working ?
App.class
public class App extends Application {
private static AppComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
buildGraphAndInject();
}
public static AppComponent getAppComponent() {
if(appComponent == null) {
Log.d("getter", "null");
}
return appComponent;
}
public void buildGraphAndInject() {
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
appComponent.inject(this);
if(appComponent == null) {
Log.d("build", "null");
}
}
}
call from Activity
#Override
public void setupComponent(AppComponent appComponent) {
mComponent = DaggerMainComponent.builder()
.appComponent(App.getAppComponent())
.build();
mComponent.inject(this);
}
AppComponent
#Component(modules = {AppModule.class})
public interface AppComponent {
void inject(App app);
}
result
04-02 02:16:23.544 32016-32016/exp.privatebank D/getter: null
04-02 02:16:23.569 32016-32016/exp.privatebank E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{exp.privatebank/exp.privatebank.view.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at dagger.internal.Preconditions.checkNotNull(Preconditions.java:32)
at exp.privatebank.di.DaggerMainComponent$Builder.appComponent(DaggerMainComponent.java:110)
at exp.privatebank.view.activity.MainActivity.setupComponent(MainActivity.java:58)
at exp.privatebank.common.BaseActivity.onCreate(BaseActivity.java:19)
at exp.privatebank.view.activity.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
at android.app.ActivityThread.access$700(ActivityThread.java:159) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:176) 
at android.app.ActivityThread.main(ActivityThread.java:5419) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 
at dalvik.system.NativeStart.main(Native Method) 

Cant start a dialog activity from a button in another activity

I am trying to start a new activity as a Dialog Activity putting a Intent on a button from another activity. Whenever I try and press the button, the activity unfotunately closes.
Main Activity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ab = (Button) findViewById(R.id.button1);
ab.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, NewDialog.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void side(View view){
android.support.v4.app.FragmentManager fm1 = getSupportFragmentManager();
NewDialog newdialog = new NewDialog();
newdialog.show(fm1, "SideDialog");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
}
NewDialog.java
public class NewDialog extends DialogFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.activity_new_dialog, container);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
return view;
}
}
Added Logcat:
05-29 22:37:36.472: D/dalvikvm(26806): Late-enabling CheckJNI
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapUtilization:0.25
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapIdealFree:8388608
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapConcurrentStart:2097152
05-29 22:37:39.172: D/libEGL(26806): loaded /system/lib/egl/libEGL_adreno200.so
05-29 22:37:39.222: D/libEGL(26806): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
05-29 22:37:39.322: D/libEGL(26806): loaded /system/lib/egl/libGLESv2_adreno200.so
05-29 22:37:39.362: I/Adreno200-EGL(26806): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.1_RB1.04.01.01.45.000_msm8625_JB_REL_2.0.3.1_Merge_release_AU (Merge)
05-29 22:37:39.362: I/Adreno200-EGL(26806): Build Date: 03/28/13 Thu
05-29 22:37:39.362: I/Adreno200-EGL(26806): Local Branch:
05-29 22:37:39.362: I/Adreno200-EGL(26806): Remote Branch: m/jb_rel_2.0.3.1
05-29 22:37:39.362: I/Adreno200-EGL(26806): Local Patches: NONE
05-29 22:37:39.362: I/Adreno200-EGL(26806): Reconstruct Branch: NOTHING
05-29 22:37:39.452: D/OpenGLRenderer(26806): Enabling debug mode 0
05-29 22:37:43.822: D/AndroidRuntime(26806): Shutting down VM
05-29 22:37:43.822: W/dalvikvm(26806): threadid=1: thread exiting with uncaught exception (group=0x40fd4438)
05-29 22:37:44.022: E/AndroidRuntime(26806): FATAL EXCEPTION: main
05-29 22:37:44.022: E/AndroidRuntime(26806): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.createdialog/com.example.createdialog.NewDialog}: java.lang.ClassCastException: com.example.createdialog.NewDialog cannot be cast to android.app.Activity
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2038)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.access$700(ActivityThread.java:143)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.os.Handler.dispatchMessage(Handler.java:99)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.os.Looper.loop(Looper.java:137)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.main(ActivityThread.java:4963)
05-29 22:37:44.022: E/AndroidRuntime(26806): at java.lang.reflect.Method.invokeNative(Native Method)
05-29 22:37:44.022: E/AndroidRuntime(26806): at java.lang.reflect.Method.invoke(Method.java:511)
05-29 22:37:44.022: E/AndroidRuntime(26806): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
05-29 22:37:44.022: E/AndroidRuntime(26806): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
05-29 22:37:44.022: E/AndroidRuntime(26806): at dalvik.system.NativeStart.main(Native Method)
05-29 22:37:44.022: E/AndroidRuntime(26806): Caused by: java.lang.ClassCastException: com.example.createdialog.NewDialog cannot be cast to android.app.Activity
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2029)
05-29 22:37:44.022: E/AndroidRuntime(26806): ... 11 more
I might be wrong here, but as far as I know, you can't start an Intent passing a DialogFragment, you should pass an Activity. Here's what's wrong:
Intent intent = new Intent(MainActivity.this, NewDialog.class);
startActivity(intent);
Since NewDialog is declared as a DialogFragment and not as an Activity subclass.
If what you are trying to do is show the dialog, then you should do:
NewDialog dialog = NewDialog();
// use getSupportFragmentManager() if using support fragments instead of native fragments, or
// use getChildFragmentManager() if this code is inside a fragment rather than an activity
dialog.show(getFragmentManager(), "pass-any-string-here");
Without a logcat stacktrace to look at, I am assuming that your issue has to do with variable scope (here is an example explanation on the topic).
What you need to do is declare your button as a class level variable because right now it is a method variable and as such ceases to exist once your onCreate method has finished executing.
public class MainActivity extends FragmentActivity {
private Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(...);
...
}
}

Create Dialog Box For Checking Internet Connection in Android

I'm implementing to show dialog box when Internet is offline, when i run my app i got "FATAL Exception main" and ClassCastException when when i click on button and application is crash . Can someone tell me what i am doing wrong ? Thanks to you in Advanced.
here is code how i check is internet enabled or not:
public class AndroidDetectInternetConnectionActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isOnline())
{
showNoConnectionDialog(this);
}
}
});
}
public static void showNoConnectionDialog(OnClickListener onClickListener)
{
final Context ctx = (Context) onClickListener;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
}
// This is my Log Cat stack trace
11-15 11:57:19.115: D/AndroidRuntime(453): Shutting down VM
11-15 11:57:19.115: W/dalvikvm(453): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-15 11:57:19.122: E/AndroidRuntime(453): FATAL EXCEPTION: main
11-15 11:57:19.122: E/AndroidRuntime(453): java.lang.ClassCastException: com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity.showNoConnectionDialog(AndroidDetectInternetConnectionActivity.java:99)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1.onClick(AndroidDetectInternetConnectionActivity.java:64)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View.performClick(View.java:2485)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View$PerformClick.run(View.java:9080)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.handleCallback(Handler.java:587)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Looper.loop(Looper.java:123)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invoke(Method.java:507)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-15 11:57:19.122: E/AndroidRuntime(453): at dalvik.system.NativeStart.main(Native Method)
11-15 11:57:24.892: I/Process(453): Sending signal. PID: 453 SIG: 9
change this line
final Context ctx = (Context) onClickListener;
to below one
final Context ctx = AndroidDetectInternetConnectionActivity.this;
basically you are trying to conver onClickListener to Contex which is incorrect and can not be casted.
Either you directly use ActivityName.this wherever you need context instance, or define static Context ctx as a class variable and intialize it in onCreate()by just adding this line ctx =this also remember to intialize it before using it.
Enjoy
There are two ways to solve this problem.
1) showNoConnectionDialog(this); and later on:
public static void showNoConnectionDialog(Context ctx) ...
2) showNoConnectionDialog(); and later on: public void showNoConnectionDialog() { Context ctx = AndroidDetectInternetConnectionActivity.this
You basic problem is generated by the line:
final Context ctx = (Context) onClickListener;
This is simply not a context so trying to force it to be one doesn't work.
I believe that you wanted to do was pass a context (or activity) to this function (as opposed to the local unnamed OnClickListener class that you are now passing)
The easiest solution would be to simple not pass anything to the constructor and use AndroidDetectInternetConnectionActivity.this to access your valid context.

Error in fetching data from database table

I am making an android app. and am trying to fetching data from column, name and score from
the database table but getting this error at run time,
Sorry this application has stopped unexpectedly.
This is my Code from Database Class,
public long addscore(String name, int score)
{
ContentValues values = new ContentValues();
values.put(KEY_name, name);
values.put(KEY_score, score);
// Inserting Row
return db.insert(DATABASE_TABLE, null, values);
}
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },,KEY_scoreid + "="
+ rowid,null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
And this is the code of class from where i m trying to
fetch the Data from Database table (Highscore.java),
public class Highscore extends Activity
{
TextView name1,name2,name3,name4,name5,score1,score2,score3,score4,score5;
DBAdapter db1;
Cursor c;
int id;
String n1,n2,n3,n4,n5;
String s1,s2,s3,s4,s5;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
Button backbtn=(Button)findViewById(R.id.backbtn);
OnClickListener listener=new OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Highscore.this,MainActivity.class);
startActivity(i);
finish();
}
};
backbtn.setOnClickListener(listener);
id=1;
name1=(TextView)findViewById(R.id.name1);
score1=(TextView)findViewById(R.id.score1);
db1=new DBAdapter(this);
db1.open();
c=db1.getScore(1);
n1=c.getString(1);
name1.setText(n1);
s1=c.getString(2);
score1.setText(s1);
c=db1.getScore(2);
n2=c.getString(1);
name2.setText(n2);
s2=c.getString(2);
score2.setText(s2);
c=db1.getScore(3);
n3=c.getString(1);
name3.setText(n3);
s3=c.getString(2);
score3.setText(s3);
id++;
c=db1.getScore(4);
n4=c.getString(1);
name4.setText(n4);
s4=c.getString(2);
score4.setText(s4);
id++;
c=db1.getScore(5);
n5=c.getString(1);
name5.setText(n5);
s5=c.getString(2);
score5.setText(s5);
c.deactivate();
c.close();
db1.close();
}
}
This time i am only fetching 5 names and scores.
Here's my Logcat Error,
09-19 12:01:36.046: D/AndroidRuntime(455): Shutting down VM
09-19 12:01:36.046: W/dalvikvm(455): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-19 12:01:36.066: E/AndroidRuntime(455): FATAL EXCEPTION: main
09-19 12:01:36.066: E/AndroidRuntime(455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.Highscore}: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Looper.loop(Looper.java:123)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invoke(Method.java:521)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-19 12:01:36.066: E/AndroidRuntime(455): at dalvik.system.NativeStart.main(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): Caused by: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at com.example.quizapp.Highscore.onCreate(Highscore.java:59)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-19 12:01:36.066: E/AndroidRuntime(455): ... 11 more
If you people are not getting any thing from my question so please ask..
Please help me to Solve out the Error.
Thanks in Advance
From what I see you problem is not in the database connection, you have some untreated exceptions. You have a NULL pointer exception also in onCreate(Highscore.java:59)
You can do a thing: comment parts of the code until you get a working app(that does nothing) and then uncomment until you find the exact code that crashes the app, it is easy to do and usually you will find the line that is problematic
Good luck
Use this code insted of your.....
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },KEY_scoreid + " ='"
+ rowid + "'",null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}

table name = null; NullPointerException Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent

I am having a problem with regards to checking records from the table and compare it to the word spoken. I am developing a text twist-like game.
The variable randomWord is the result of the random() method.. The words from the database must be randomized before displaying to user and it shouldn't repeat in a session.
BTW my problem is the exists() method; a NullPointerException occurs and it looks like it's because the table name is null.
What should I do with this?
exists() and random() method
public boolean exists(String word) {
Cursor cursor = null;
String WORD_TABLE = randomWord;
System.out.println("exists: "+randomWord);
String [] selectionArgs = {word + "%"};
cursor = db.rawQuery("SELECT * from "+ WORD_TABLE + "WHERE Word like ?", selectionArgs);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
public String random(){
List<Words> words = getAllWords();
for (Words wrd : words) {
String log = "WORDPOOL: "+ wrd.getWord() +" ID: "+ wrd.getId();
stringList.add(wrd.getWord());
// Writing Contacts to log
Log.d("Name: ", log);
}
selectedWord = randomGenerator.nextInt(stringList.size());
System.out.println("HEY"+stringList.remove(selectedWord)+" "+selectedWord);
randomWord = stringList.remove(selectedWord);
return randomWord;
}
logcat
07-20 16:49:04.171: E/AndroidRuntime(4081): FATAL EXCEPTION: main
07-20 16:49:04.171: E/AndroidRuntime(4081): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.flip/com.flip.main.friend}: java.lang.NullPointerException
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.app.ActivityThread.deliverResults(ActivityThread.java:2536)
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2578)
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:965)
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.os.Looper.loop(Looper.java:130)
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.app.ActivityThread.main(ActivityThread.java:3687)
07-20 16:49:04.171: E/AndroidRuntime(4081): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 16:49:04.171: E/AndroidRuntime(4081): at java.lang.reflect.Method.invoke(Method.java:507)
07-20 16:49:04.171: E/AndroidRuntime(4081): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
07-20 16:49:04.171: E/AndroidRuntime(4081): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
07-20 16:49:04.171: E/AndroidRuntime(4081): at dalvik.system.NativeStart.main(Native Method)
07-20 16:49:04.171: E/AndroidRuntime(4081): Caused by: java.lang.NullPointerException
07-20 16:49:04.171: E/AndroidRuntime(4081): at com.flip.dao.DBHelper.exists(DBHelper.java:107)
07-20 16:49:04.171: E/AndroidRuntime(4081): at com.flip.main.friend.onActivityResult(friend.java:289)
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
07-20 16:49:04.171: E/AndroidRuntime(4081): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
07-20 16:49:04.171: E/AndroidRuntime(4081): ... 11 more
The implementation
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
System.out.println(""+text.get(0));
String wanted = text.get(0);
if(dbHelp.exists(wanted)){
gameScore = text.get(0).length()*10;
TextView score = (TextView) findViewById(R.id.scoreView);
score.setText(""+gameScore);
playSound(R.raw.correct);
}
}
}
}
It's my problem mates.. the database is still not open.. For that, I called
db = this.getReadableDatabase
inside the exists method...
Thanks for replies... Regards

Categories