Android Java: Global variables through subclass; can't launch app? - java

I've been reading up examples on how to do this, trying to piece together a functioning example from posts on this site and others. I'm sure I'm missing something small, but as a novice to Java, I could use some assistance.
I'm merely trying to create a small example, derived from the automated hello world generated when creating a new project in Eclipse. All I want to do is be able to store a few global variables in a subclass, then reference those values in my main activity. Unfortunately, every time I try to run the app, it crashes "Unfortunately, GeneralTest1 has stopped", and the log cat error is not very helpful.
Quick overview:
GlobalVars class extends Application
In the manifest, android:name has been added to reference the additional GlobalVars class
Within my main activity, I'm initializing the global vars class with getApplicationContext()
Here is everything I've got; any help would be much appreciated!
MainActivity.java
package com.example.generaltest1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
GlobalVars myVars = ((GlobalVars)getApplicationContext());
TextView myText = (TextView) findViewById(R.id.myText);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myText.setText(myVars.getMyString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
GlobalVars.java
package com.example.generaltest1;
import android.app.Application;
public class GlobalVars extends Application {
String myString = "Some Text";
public String getMyString() {
return myString;
}
public String setMyString(String string) {
this.myString = string;
return myString;
}
}
activity_main.xml
<RelativeLayout 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" >
<TextView
android:id="#+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
strings.xml
<resources>
<string name="app_name">GeneralTest1</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
GeneralTest1 Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.generaltest1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:name="GlobalVars">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Log Cat
08-14 09:53:05.546: E/Trace(620): error opening trace file: No such file or directory (2)
08-14 09:53:05.656: D/AndroidRuntime(620): Shutting down VM
08-14 09:53:05.656: W/dalvikvm(620): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
08-14 09:53:05.676: E/AndroidRuntime(620): FATAL EXCEPTION: main
08-14 09:53:05.676: E/AndroidRuntime(620): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.generaltest1/com.example.generaltest1.MainActivity}: java.lang.NullPointerException
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.os.Looper.loop(Looper.java:137)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-14 09:53:05.676: E/AndroidRuntime(620): at java.lang.reflect.Method.invokeNative(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620): at java.lang.reflect.Method.invoke(Method.java:511)
08-14 09:53:05.676: E/AndroidRuntime(620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-14 09:53:05.676: E/AndroidRuntime(620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-14 09:53:05.676: E/AndroidRuntime(620): at dalvik.system.NativeStart.main(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620): Caused by: java.lang.NullPointerException
08-14 09:53:05.676: E/AndroidRuntime(620): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
08-14 09:53:05.676: E/AndroidRuntime(620): at com.example.generaltest1.MainActivity.<init>(MainActivity.java:10)
08-14 09:53:05.676: E/AndroidRuntime(620): at java.lang.Class.newInstanceImpl(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620): at java.lang.Class.newInstance(Class.java:1319)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
08-14 09:53:05.676: E/AndroidRuntime(620): ... 11 more

You are calling getApplicationContext() in your class definition, which is too early in the activity lifetime and results in a nullpointer exception. Move the assignments to your onCreate() function and it should work as expected.

Please check this article about activities and their lifecycle :
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Your activity should look like this:
public class MainActivity extends Activity {
GlobalVars myVars;
TextView myText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myVars = ((GlobalVars)getApplication());
myText = (TextView) findViewById(R.id.myText);
myText.setText(myVars.getMyString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Add these lines in oncreate()..
GlobalVars myVars = ((GlobalVars)getApplicationContext());
TextView myText = (TextView) findViewById(R.id.myText);

Related

Unfortunately your "APP" has stopped working [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
I am new to Android App development and I am having an issue with an app. I have read everything I could find on stackoverflow about the problem and checked my work against the suggestions from the other questions asked.
Thanks for the help.
Unfortunately application has stopped android emulator genymotion
I am trying to run the app on a Samsung Gal 3 tab.
Below are my files
MainActivity.java
package net.androidbootcamp.concerttickets;
import java.text.DecimalFormat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
double costPerTicket = 79.99;
int numberOfTickets;
double totalCost;
String groupChoice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText tickets=(EditText)findViewById(R.id.txtTicket);
final Spinner group = (Spinner)findViewById(R.id.txtGroup);
Button cost = (Button)findViewById(R.id.btnCost);
cost.setOnClickListener(new OnClickListener() {
final TextView result = ((TextView)findViewById(R.id.txtResult));
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
numberOfTickets = Integer.parseInt(tickets.getText().toString());
totalCost = costPerTicket * numberOfTickets;
DecimalFormat currency = new DecimalFormat("$###,###.##");
groupChoice = group.getSelectedItem().toString();
result.setText("Total Cost for" + groupChoice + "is" + currency.format(totalCost));
}
});
}
#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;
}
#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);
}
}
ActivityMain.xml
<RelativeLayout 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"
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="net.androidbootcamp.concerttickets.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/txtTitle"
android:textSize="48sp" />
<EditText
android:id="#+id/txtTicket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtGroup"
android:layout_below="#+id/textView1"
android:ems="10"
android:hint="#string/txtTickets"
android:inputType="number"
android:textSize="32sp" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/txtGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtTicket"
android:layout_centerHorizontal="true"
android:entries="#array/txtGroup"
android:prompt="#string/prompt" />
<Button
android:id="#+id/btnCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtGroup"
android:layout_centerHorizontal="true"
android:text="#string/btnCost"
android:textSize="32sp" />
<TextView
android:id="#+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnCost"
android:layout_centerHorizontal="true"
android:textSize="18sp" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtGroup"
android:layout_alignParentBottom="true"
android:layout_marginBottom="19dp"
android:contentDescription="#string/description"
android:src="#drawable/concert" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.androidbootcamp.concerttickets"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<activity
android:name="net.androidbootcamp.concerttickets.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
LogCat
08-14 17:19:35.330: D/AndroidRuntime(20330): Shutting down VM
08-14 17:19:35.330: W/dalvikvm(20330): threadid=1: thread exiting with uncaught exception (group=0x41cf0e10)
08-14 17:19:35.340: E/AndroidRuntime(20330): FATAL EXCEPTION: main
08-14 17:19:35.340: E/AndroidRuntime(20330): java.lang.RuntimeException: Unable to start activity ComponentInfo{net.androidbootcamp.concerttickets/net.androidbootcamp.concerttickets.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.app.ActivityThread.access$700(ActivityThread.java:150)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.os.Looper.loop(Looper.java:176)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.app.ActivityThread.main(ActivityThread.java:5279)
08-14 17:19:35.340: E/AndroidRuntime(20330): at java.lang.reflect.Method.invokeNative(Native Method)
08-14 17:19:35.340: E/AndroidRuntime(20330): at java.lang.reflect.Method.invoke(Method.java:511)
08-14 17:19:35.340: E/AndroidRuntime(20330): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
08-14 17:19:35.340: E/AndroidRuntime(20330): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
08-14 17:19:35.340: E/AndroidRuntime(20330): at dalvik.system.NativeStart.main(Native Method)
08-14 17:19:35.340: E/AndroidRuntime(20330): Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:110)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.support.v7.app.ActionBarActivityDelegateICS.onCreate(ActionBarActivityDelegateICS.java:57)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:99)
08-14 17:19:35.340: E/AndroidRuntime(20330): at net.androidbootcamp.concerttickets.MainActivity.onCreate(MainActivity.java:26)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.app.Activity.performCreate(Activity.java:5267)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
08-14 17:19:35.340: E/AndroidRuntime(20330): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
08-14 17:19:35.340: E/AndroidRuntime(20330): ... 11 more
The LogCat output shows that you aren't using the theme correctly. in particular, it wants you to use a compatibility theme. You can do that by altering/including a theme attribute for the activity in your manifest file.
If you're not actually going to use an action bar, your could also just change the parent of your activity from ActionbarActivity to just Activity like this:
public class MainActivity extends Activity {

android.view.InflateException: Binary XML file line #10: Error inflating class fragment

I created an app by following the tutorial at http://www.techotopia.com/index.php/Using_Fragments_in_Android_-_A_Worked_Example,
but I have a error.
LogCat:
05-02 08:16:22.044: D/dalvikvm(1846): Late-enabling CheckJNI
05-02 08:16:22.080: D/AndroidRuntime(1846): Shutting down VM
05-02 08:16:22.080: W/dalvikvm(1846): threadid=1: thread exiting with uncaught exception (group=0xa4d81b20)
05-02 08:16:22.096: E/AndroidRuntime(1846): FATAL EXCEPTION: main
05-02 08:16:22.096: E/AndroidRuntime(1846): Process: com.example.myfragmentexample, PID: 1846
05-02 08:16:22.096: E/AndroidRuntime(1846): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfragmentexample/com.example.myfragmentexample.MainActivity}: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.os.Handler.dispatchMessage(Handler.java:102)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.os.Looper.loop(Looper.java:136)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-02 08:16:22.096: E/AndroidRuntime(1846): at java.lang.reflect.Method.invokeNative(Native Method)
05-02 08:16:22.096: E/AndroidRuntime(1846): at java.lang.reflect.Method.invoke(Method.java:515)
05-02 08:16:22.096: E/AndroidRuntime(1846): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-02 08:16:22.096: E/AndroidRuntime(1846): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-02 08:16:22.096: E/AndroidRuntime(1846): at dalvik.system.NativeStart.main(Native Method)
05-02 08:16:22.096: E/AndroidRuntime(1846): Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
05-02 08:16:22.096: E/AndroidRuntime(1846): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.Activity.setContentView(Activity.java:1929)
05-02 08:16:22.096: E/AndroidRuntime(1846): at com.example.myfragmentexample.MainActivity.onCreate(MainActivity.java:12)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.Activity.performCreate(Activity.java:5231)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-02 08:16:22.096: E/AndroidRuntime(1846): ... 11 more
05-02 08:16:22.096: E/AndroidRuntime(1846): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.fragmentexample.ToolbarFragment: make sure class name exists, is public, and has an empty constructor that is public
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.Fragment.instantiate(Fragment.java:597)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.Fragment.instantiate(Fragment.java:561)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.Activity.onCreateView(Activity.java:4778)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
05-02 08:16:22.096: E/AndroidRuntime(1846): ... 21 more
05-02 08:16:22.096: E/AndroidRuntime(1846): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.fragmentexample.ToolbarFragment" on path: DexPathList[[zip file "/data/app/com.example.myfragmentexample-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.myfragmentexample-1, /system/lib]]
05-02 08:16:22.096: E/AndroidRuntime(1846): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
05-02 08:16:22.096: E/AndroidRuntime(1846): at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
05-02 08:16:22.096: E/AndroidRuntime(1846): at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
05-02 08:16:22.096: E/AndroidRuntime(1846): at android.app.Fragment.instantiate(Fragment.java:583)
05-02 08:16:22.096: E/AndroidRuntime(1846): ... 24 more
MainActivity.java:
package com.example.myfragmentexample;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements
ToolbarFragment.ToolbarListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtononClick(int fontsize, String text) {
TextFragment textfragment = (TextFragment) getSupportFragmentManager()
.findFragmentById(R.id.text_fragment);
textfragment.zmienWlasciwosci(fontsize, text);
}
}
activity_main.xml:
<RelativeLayout 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=".MainActivity" >
<fragment
android:id="#+id/toolbar_fragment"
android:name="com.example.fragmentexample.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/toolbar_fragment" />
<fragment
android:id="#+id/text_fragment"
android:name="com.example.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/text_fragment" />
</RelativeLayout>
ToolbarFragment.java:
package com.example.myfragmentexample;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ToolbarFragment extends Fragment implements
OnSeekBarChangeListener {
private static int seekvalue = 10;
private static EditText edittext;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtononClick(int position, String text);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (ToolbarListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ToolbarListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.toolbar_fragment, container,
false);
edittext = (EditText) view.findViewById(R.id.editText);
SeekBar seekbar = (SeekBar) view.findViewById(R.id.seekBar);
seekbar.setOnSeekBarChangeListener(this);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked(v);
}
});
return view;
}
public void buttonClicked(View view) {
activityCallback.onButtononClick(seekvalue, edittext.getText()
.toString());
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
seekvalue = arg1;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
toolbar_fragment.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" >
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="text">
<requestFocus />
</EditText>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText"
android:layout_marginTop="14dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:layout_below="#+id/seekBar"
android:text="#string/button_text" />
</RelativeLayout>
TextFragment.java:
package com.example.myfragmentexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends Fragment {
private static TextView textview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.text_fragment, container, false);
textview = (TextView) view.findViewById(R.id.textView1);
return view;
}
public void zmienWlasciwosci (int fontsize, String text){
textview.setTextSize(fontsize);
textview.setText(text);
}
}
text_fragment.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/text_label"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfragmentexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfragmentexample.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I read a lot of posts about this error, but I couldn't find anything wrong in my code. I extended android.support.v4.app.FragmentActivity.
Caused by: java.lang.ClassNotFoundException: Didn't find class
"com.example.fragmentexample.ToolbarFragment" on path:
DexPathList[[zip file
"/data/app/com.example.myfragmentexample-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.myfragmentexample-1,
/system/lib]]
This
android:name="com.example.fragmentexample.ToolbarFragment"
Must be
android:name="com.example.myfragmentexample.ToolbarFragment"
cause package name for ToolbarFragment.java is
package com.example.myfragmentexample;
Similarly for TextFragment
android:name="com.example.myfragmentexample.TextFragment"
Try adding correct layouts at correct place like ex. in my case I was putting colors.xml in values-w820p then it was giving runtime exception of classtype. I changed the folder from this to simple value and... taddda!! it worked! :)
I am also new to Android and encountered the same error today. I could not find a solution that worked for me but one thing was clear to me that this issue occurs when android is not able to resolve a mandatory attribute of one of the elements in layout xml.
So I checked my layout thoroughly and found that by mistake I created an ID
<item type="id" name="login"/>
in ids.xml. This Id was conflicting with attribute
android:imeActionId="#+id/login"
of EditText element.
Hope this helps someone.
In my case Google Maps were not correctly initialized. A message in log console printed about it. I had to add
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
to <application> inside AndroidManifest.

Android Geolocation Google Maps Crashing On Start Up

I posted my code below my application shows no errors int eh debug menu, when I run it logcat shows one error I posted it below. When I try to run the app on my phone it closes and stops responding and im not sure why. I was following an online tutorial and did it exactly how it said. Please help.
10-07 14:50:02.901: I/Process(11653): Sending signal. PID: 11653 SIG: 9
10-07 14:50:06.124: W/dalvikvm(11801): VFY: unable to resolve static field 1346 (MapAttrs) in Lcom/google/android/gms/R$styleable;
10-07 14:50:06.124: D/dalvikvm(11801): VFY: replacing opcode 0x62 at 0x000e
10-07 14:50:06.134: D/AndroidRuntime(11801): Shutting down VM
10-07 14:50:06.134: W/dalvikvm(11801): threadid=1: thread exiting with uncaught exception (group=0x4129bac8)
10-07 14:50:06.134: E/AndroidRuntime(11801): FATAL EXCEPTION: main
10-07 14:50:06.134: E/AndroidRuntime(11801): java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable
10-07 14:50:06.134: E/AndroidRuntime(11801): at com.google.android.gms.maps.GoogleMapOptions.createFromAttributes(Unknown Source)
10-07 14:50:06.134: E/AndroidRuntime(11801): at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:284)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:682)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.view.LayoutInflater.inflate(LayoutInflater.java:495)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
10-07 14:50:06.134: E/AndroidRuntime(11801): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:327)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.app.Activity.setContentView(Activity.java:1928)
10-07 14:50:06.134: E/AndroidRuntime(11801): at com.example.gloc.MainActivity.onCreate(MainActivity.java:30)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.app.Activity.performCreate(Activity.java:5250)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2297)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.app.ActivityThread.access$700(ActivityThread.java:152)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.os.Handler.dispatchMessage(Handler.java:99)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.os.Looper.loop(Looper.java:137)
10-07 14:50:06.134: E/AndroidRuntime(11801): at android.app.ActivityThread.main(ActivityThread.java:5328)
10-07 14:50:06.134: E/AndroidRuntime(11801): at java.lang.reflect.Method.invokeNative(Native Method)
10-07 14:50:06.134: E/AndroidRuntime(11801): at java.lang.reflect.Method.invoke(Method.java:511)
10-07 14:50:06.134: E/AndroidRuntime(11801): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
10-07 14:50:06.134: E/AndroidRuntime(11801): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
10-07 14:50:06.134: E/AndroidRuntime(11801): at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
package com.example.gloc;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
//Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
//dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#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;
}
}
Layout
<RelativeLayout 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=".MainActivity" >
<TextView
android:id="#+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tv_location"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gloc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="18" />
<permission
android:name="in.wptrafficanalyzer.locationingooglemapv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="in.wptrafficanalyzer.locationingooglemapv2.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="IEARASEDTHSITOHIDEIT"/>
<activity
android:name="com.example.gloc.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You can't change the map options in onCreate, as it has not yet been instantiated. Try doing all of the stuff in OnLocationChanged to your GoogleMap object in onResume() instead of onCreate().

Fatal Exception on starting activity Android

I have created new activity that my MainActivity Should lunch, some why the application is crashing on the start of the new activity (called GamePlayActivity).
Here is the java code:
Intent startGameDrill = new Intent(MainActivity.this, GamePlayActivity.class);
startActivity(startGameDrill);
Here is the startGameDrill:
package com.simplemathgame;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class GamePlayActivity extends MainActivity {
int addDrills;
int subDrils;
int mulDrills;
int divDrills;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_play);
try {
numberOfAddDrills = (TextView) findViewById(R.id.add_drills_number);
numberOfSubDrills = (TextView) findViewById(R.id.sub_drills_number);
numberOfMulDrills = (TextView) findViewById(R.id.mul_drills_number);
numberOfDivDrills = (TextView) findViewById(R.id.div_drills_number);
minBoundText = (TextView) findViewById(R.id.min_text);
maxBoundText = (TextView) findViewById(R.id.max_text);
} catch (Exception e1) {
// TODO Auto-generated catch block
Log.w("game","error");
}
try {
addDrills = Integer.parseInt((String) numberOfAddDrills.getText());
subDrils = Integer.parseInt((String) numberOfSubDrills.getText());
mulDrills = Integer.parseInt((String) numberOfMulDrills.getText());
divDrills = Integer.parseInt((String) numberOfDivDrills.getText());
} catch (NumberFormatException e) {
Log.w("GameDrills","string to int");
}
Log.w("add", "" + addDrills);
Log.w("add", "" + subDrils);
Log.w("add", "" + mulDrills);
Log.w("add", "" + divDrills);
}
}
Here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.simplemathgame"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:theme="#style/AppTheme" >
<activity
android:name="com.simplemathgame.Splash"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.simplemathgame.MainActivity"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="com.simplemathgame.MainActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.simplemathgame.GamePlayActivity"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
</activity>
</application>
</manifest>
here is the logCat:
12-21 22:05:53.949: D/dalvikvm(610): GC_EXTERNAL_ALLOC freed 42K, 53% free 2546K/5379K, external 1917K/2137K, paused 41ms
12-21 22:06:32.809: D/AndroidRuntime(610): Shutting down VM
12-21 22:06:32.809: W/dalvikvm(610): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-21 22:06:32.818: E/AndroidRuntime(610): FATAL EXCEPTION: main
12-21 22:06:32.818: E/AndroidRuntime(610): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.simplemathgame/com.simplemathgame.GamePlayActivity}: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.os.Handler.dispatchMessage(Handler.java:99)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.os.Looper.loop(Looper.java:123)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-21 22:06:32.818: E/AndroidRuntime(610): at java.lang.reflect.Method.invokeNative(Native Method)
12-21 22:06:32.818: E/AndroidRuntime(610): at java.lang.reflect.Method.invoke(Method.java:507)
12-21 22:06:32.818: E/AndroidRuntime(610): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-21 22:06:32.818: E/AndroidRuntime(610): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-21 22:06:32.818: E/AndroidRuntime(610): at dalvik.system.NativeStart.main(Native Method)
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610): at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-21 22:06:32.818: E/AndroidRuntime(610): ... 11 more
Here is the layout of the GamePlayActivity:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#000044">
<TableRow
android:layout_marginTop="10dp"
android:gravity="center_vertical" >
<TextView
android:textColor="#FFFFFFFF"
android:textSize="16sp"
android:textStyle="bold"
android:text="Addition Drills:"/>
</TableRow>
</TableLayout>
Why does it crashes?
Have a look here:
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610): at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)
Line 31 of GamePlayActivity.java is this line:
addDrills = Integer.parseInt((String) numberOfAddDrills.getText());
Since the only thing on this line that you reference a member or method of is numberOfAddDrills, then it must be null.
Consider that you are checking for exceptions when using findViewById; however, if the view is not found it will just return null, not throw an exception.
Have a look at the activity_game_play.xml you posted; there is no TextView with android:id="#+id/add_drills_number". You need to create it, and the same deal for the other five TextViews.
Oh, and a hint: Don't just catch generic exceptions with } catch (Exception e1) {, especially if you have no intent of reading the logs. I can't tell you how many times people have missed errors from doing this.
If you want to pass values from another layout, you have two options: keep a reference to the View objects (this is a bit silly, don't do this); or pass the data you need from them to your new Activity:
startGameDrill.putExtra("myIntExtra", 5); // For example
Then, in GamePlayActivity.onCreate(), you can fetch it using getIntent()'s extras:
Bundle extras = getIntent().getExtras();
int myIntExtra = extras.getInt("myIntExtra");
Then use that value instead of relying on the view in the previous layout. There is a fuller example in this answer.
Follow the stacktrace until you find some references to your classes:
It shows:
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610): at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)
So you are creating a NullPointerException at line 31 in GamePlayActivity.java
Line 31:
addDrills = Integer.parseInt((String) numberOfAddDrills.getText());
so maybe numberOfAddDrills is null?

Android App crashing in Emulator [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm a novice android app developer. I wrote an application which fetches Bible Readings from online. I wrote the separate Java class for fetching the reading and I tested it and it's working fine. But when I tried to use that in my Android App, my app crashed and stops working. I've understood from the logs that it's throwing a null pointer exception, but I don't how to fix that. I've also checked the internet and I can't find an exact solution for this. I'm attaching the logs and file related to my application below. Could anyone go through my code and throw some light on fixing the error. I appreciate your time on my behalf and many thanks in advance.
10-25 09:49:23.243: E/AndroidRuntime(620): FATAL EXCEPTION: main
10-25 09:49:23.243: E/AndroidRuntime(620): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mgocsm/com.mgocsm.EveningKymthaPrayers}: java.lang.NullPointerException: println needs a message
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.os.Handler.dispatchMessage(Handler.java:99)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.os.Looper.loop(Looper.java:137)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-25 09:49:23.243: E/AndroidRuntime(620): at java.lang.reflect.Method.invokeNative(Native Method)
10-25 09:49:23.243: E/AndroidRuntime(620): at java.lang.reflect.Method.invoke(Method.java:511)
10-25 09:49:23.243: E/AndroidRuntime(620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-25 09:49:23.243: E/AndroidRuntime(620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-25 09:49:23.243: E/AndroidRuntime(620): at dalvik.system.NativeStart.main(Native Method)
10-25 09:49:23.243: E/AndroidRuntime(620): Caused by: java.lang.NullPointerException: println needs a message
10-25 09:49:23.243: E/AndroidRuntime(620): at android.util.Log.println_native(Native Method)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.util.Log.d(Log.java:138)
10-25 09:49:23.243: E/AndroidRuntime(620): at com.mgocsm.BibleReader.getVerses(BibleReader.java:44)
10-25 09:49:23.243: E/AndroidRuntime(620): at com.mgocsm.EveningKymthaPrayers.onCreate(EveningKymthaPrayers.java:25)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.Activity.performCreate(Activity.java:5008)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-25 09:49:23.243: E/AndroidRuntime(620): ... 11 more
EveningKymthaPrayers.java (Activitiy from where I call the Java class to fetch readings)
=========================
.
public class EveningKymthaPrayers extends Activity {
AssetManager am;
FileReader f;
TextView kymtha_prayer;
BibleReader bible;
//ReadingList rl = new ReadingList();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.evening_kymtha);
am = getAssets();
f = new FileReader(am,"kymtha.txt");
kymtha_prayer = (TextView) findViewById(R.id.show_kymtha);
kymtha_prayer.setMovementMethod(new ScrollingMovementMethod());
bible = new BibleReader("John 3:16-17");
kymtha_prayer.setText(bible.getVerses());
//kymtha_prayer.setText(f.readFile());
//kymtha_prayer.setText(setText);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
BibleReader.java (Java class for fetching Bible verses)
public class BibleReader {
public static final String URL="http://labs.bible.org/api/?passage=";
String verse;
String logName = "BibleReader";
String line;
StringBuilder recText;
private static final int BUFFER_SIZE = 1024 * 10;
private final byte[] dataBuffer = new byte[BUFFER_SIZE];
public BibleReader(String verse) {
// TODO Auto-generated constructor stub
this.verse = verse;
this.verse = this.verse.toString().replaceAll(" ", "%20");
}
public String getVerses()
{
String body = null;
try{
URL url = new URL(URL+this.verse);
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(dataBuffer)) != -1) {
baos.write(dataBuffer, 0, len);
}
body = new String(baos.toByteArray(), encoding);
Log.d(logName, "Fetched Verse"+body);
}
catch(Exception e){
Log.d(logName, e.getMessage());
}
return body.toString();
}
}
AndroidMainfest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mgocsm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DailyPrayers" android:label="#string/app_name"></activity>
<activity android:name=".EveningPrayers" android:label="#string/app_name"></activity>
<activity android:name=".EveningKymthaPrayers" android:label="#string/app_name"></activity>
</application>
</manifest>
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
switch(v.getId()){
case R.id.daily_prayers:
startActivity(new Intent(getApplicationContext(),DailyPrayers.class));
break;
}
}
}
DailyPrayers.java
public class DailyPrayers extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_prayers);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
switch(v.getId()){
case R.id.home:
startActivity(new Intent(getApplicationContext(),MainActivity.class));
break;
case R.id.evening_prayers:
startActivity(new Intent(getApplicationContext(),EveningPrayers.class));
break;
}
}
}
EveningPrayers.java
public class EveningPrayers extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.evening_prayers);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
switch(v.getId()){
case R.id.kymtha_evening:
startActivity(new Intent(getApplicationContext(),EveningKymthaPrayers.class));
break;
case R.id.sleeba_evening:
break;
}
}
}
The body that you are trying to print is getting null as a value.Check first you receive any value in body or not.
What i have noticed in your code:
bible.getVerses() is returning null
It seems INTERNET permission is not included in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Don't make a web call on Main thread. Instead you can use AsyncTask or AsyncTaskLoader
Instead of using:
this.verse = this.verse.toString().replaceAll(" ", "%20");
You must use:
String webURL = URLEncoder.encode("your web url", "utf-8");
What are you logging at this place: com.mgocsm.BibleReader.getVerses(BibleReader.java:44)
?
You are probably passing a Null.
Add this permission in your Manifest
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
body = new String(baos.toByteArray(), encoding);
Log.d(logName, "Fetched Verse"+body);
your Body is getting null value that is why ur log is giving nullpointer exception

Categories