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
Related
When I run my application I get these errors, I'mm trying to make an app with RSS
Photo2.java
package com.otticafotobenzi.ofbshop;
import com.otticafotobenzi.R;
public class Photo2 extends ActionBarActivity implements View.OnClickListener {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private ViewFlipper mViewFlipper;
private Context mContext;
Button buttonCan;
Button buttonFuj;
Button buttonNik;
Button buttonOly;
Button buttonPana;
Button buttonPen;
Button buttonSon;
#SuppressWarnings("deprecation")
private final GestureDetector detector = new GestureDetector(
new SwipeGestureDetector());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo2);
buttonCan = (Button) findViewById(R.id.buttonCan);
buttonFuj = (Button) findViewById(R.id.buttonFuj);
buttonNik = (Button) findViewById(R.id.buttonNik);
buttonOly = (Button) findViewById(R.id.buttonOly);
buttonPana = (Button) findViewById(R.id.buttonPana);
buttonPen = (Button) findViewById(R.id.buttonPen);
buttonSon = (Button) findViewById(R.id.buttonSon);
buttonCan.setOnClickListener(this);
buttonFuj.setOnClickListener(this);
buttonNik.setOnClickListener(this);
buttonOly.setOnClickListener(this);
buttonPana.setOnClickListener(this);
buttonPen.setOnClickListener(this);
buttonSon.setOnClickListener(this);
mContext = this;
mViewFlipper = (ViewFlipper) this.findViewById(R.id.view_flipper);
mViewFlipper.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(final View view, final MotionEvent event) {
detector.onTouchEvent(event);
return true;
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonCan:
Intent loader_rssnik = new Intent(this, RssService.class); //problem here
startActivity(loader_rssnik);
break;
case R.id.buttonFuj:
Intent loader_rsscan = new Intent(this, RssService.class);
startActivity(loader_rsscan);
break;
case R.id.buttonNik:
Intent loader_rssfuji = new Intent(this, RssServiceNik.class);
startActivity(loader_rssfuji);
break;
case R.id.buttonOly:
Intent loader_rssoly = new Intent(this, RssService.class);
startActivity(loader_rssoly);
break;
case R.id.buttonPana:
Intent loader_rsspen = new Intent(this, RssService.class);
startActivity(loader_rsspen);
break;
case R.id.buttonPen:
Intent loader_rsspan = new Intent(this, RssService.class);
startActivity(loader_rsspan);
break;
case R.id.buttonSon:
Intent loader_rssson = new Intent(this, RssService.class);
startActivity(loader_rssson);
break;
}
}
class SwipeGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(
mContext, R.anim.left_in));
mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
mContext, R.anim.left_out));
mViewFlipper.showNext();
return true;
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(
mContext, R.anim.right_in));
mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
mContext, R.anim.right_out));
mViewFlipper.showPrevious();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.photography, 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);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.otticafotobenzi"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity android:name=".ofbshop.Loader"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ofbshop.Home"
android:label="#string/title_activity_home">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ofbshop.Photography"
android:label="#string/title_activity_photography">
</activity>
<activity android:name=".ofbshop.Photo2"
android:label="#string/title_activity_photography">
</activity>
<activity android:name=".ofbshop.Optics"
android:label="#string/title_activity_optics">
</activity>
<activity android:name=".rss.Constants" />
<activity android:name=".rss.MainActivity" />
<activity android:name=".rss.RssAdapter" />
<activity android:name=".rss.RssFragment" />
<activity android:name=".rss.RssItem" />
<activity android:name=".rss.RssParser" />
<activity android:name=".rss.RssService" />
<activity android:name=".rss.RssServiceNik" />
</application>
RssService.java
package com.otticafotobenzi.rss;
public class RssService extends IntentService {
private static final String RSS_LINK = "http://feeds.feedburner.com/PhotoRumors?format=xml";
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService() {
super("RssService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try {
RssParser parser = new RssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
} catch (XmlPullParserException e) {
Log.w(e.getMessage(), e);
} catch (IOException e) {
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link) {
try {
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e) {
Log.w(Constants.TAG, "Exception while retrieving the input stream",
e);
return null;
}
}
}
and this is the error in logcat with genymotion emulator android 4.4
02-12 17:04:50.552: E/AndroidRuntime(2044): FATAL EXCEPTION: main
02-12 17:04:50.552: E/AndroidRuntime(2044): Process: com.otticafotobenzi, PID: 2044
02-12 17:04:50.552: E/AndroidRuntime(2044): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.otticafotobenzi/com.otticafotobenzi.rss.RssService}: java.lang.ClassCastException: com.otticafotobenzi.rss.RssService cannot be cast to android.app.Activity
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.os.Handler.dispatchMessage(Handler.java:102)
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.os.Looper.loop(Looper.java:136)
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.app.ActivityThread.main(ActivityThread.java:5001)
02-12 17:04:50.552: E/AndroidRuntime(2044): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 17:04:50.552: E/AndroidRuntime(2044): at java.lang.reflect.Method.invoke(Method.java:515)
02-12 17:04:50.552: E/AndroidRuntime(2044): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
02-12 17:04:50.552: E/AndroidRuntime(2044): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
02-12 17:04:50.552: E/AndroidRuntime(2044): at dalvik.system.NativeStart.main(Native Method)
02-12 17:04:50.552: E/AndroidRuntime(2044): Caused by: java.lang.ClassCastException: com.otticafotobenzi.rss.RssService cannot be cast to android.app.Activity
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
02-12 17:04:50.552: E/AndroidRuntime(2044): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
02-12 17:04:50.552: E/AndroidRuntime(2044): ... 11 more
Change
<activity android:name=".rss.RssService" />
to
<service android:name=".rss.RssService" />
And if you want to start service use method
startService(Intent);
by
startActivity(Intent);
You need to call a different method for services:
Intent loader_rssnik = new Intent(this, RssService.class);
startService(loader_rssfuji);
I'm trying unzip some files in background, so I use IntentService like in google's tutorial. My service class declared in AndroidManifest like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.osmdroid">
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<application
android:configChanges="orientation|screenSize|keyboardHidden"
android:hardwareAccelerated="true"
android:icon="#drawable/ecn_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MapActivity"
android:icon="#drawable/ecn_icon"
android:label="test" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings">
</activity>
<service
android:name=".UnZipService"
android:exported="false"/>
</application>
In activity, I have
IntentFilter intentFilter = new IntentFilter(DownloadManager
.ACTION_DOWNLOAD_COMPLETE);
receiverDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long reference = intent.getLongExtra(DownloadManager
.EXTRA_DOWNLOAD_ID, -1);
if (myDownloadReference == reference) {
...
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
Intent mServiceIntent = new Intent(context, UnZipService.class);
mServiceIntent.setData(Uri.parse(savedFilePath));
startActivity(mServiceIntent);
break;
...
}
cursor.close();
}
}
};
registerReceiver(receiverDownloadComplete, intentFilter);
And service here:
public class UnZipService extends IntentService {
public UnZipService() {
super("UnZipService");
}
#Override
protected void onHandleIntent(Intent workIntent) {
String dataString = workIntent.getDataString();
Log.v("IntentURI", dataString);
Toast.makeText(this, "Installing....", Toast.LENGTH_SHORT).show();
}
It should show toast just for test, but I always get an error:
01-29 19:08:25.740 15521-15521/org.osmdroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.DOWNLOAD_COMPLETE flg=0x10 pkg=org.osmdroid (has extras) } in org.osmdroid.SettingsActivity$1#21292650
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:768)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5147)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {org.osmdroid/org.osmdroid.UnZipService}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1618)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
at android.app.Activity.startActivityForResult(Activity.java:3404)
at android.app.Activity.startActivityForResult(Activity.java:3365)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
at android.app.Activity.startActivity(Activity.java:3600)
at android.app.Activity.startActivity(Activity.java:3568)
at org.osmdroid.SettingsActivity$1.onReceive(SettingsActivity.java:148)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:758)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5147)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Both (class and activity) in same folder (org.osmdroid). Seems like paths is ok, but the problem appears and I have no more ideas...
You are starting a service as an activity
Change
Intent mServiceIntent = new Intent(context, UnZipService.class);
mServiceIntent.setData(Uri.parse(savedFilePath));
startActivity(mServiceIntent);
to
Intent mServiceIntent = new Intent(context, UnZipService.class);
mServiceIntent.setData(Uri.parse(savedFilePath));
startService(mServiceIntent); // Only this line is changed
Please declared this activity in your AndroidManifest.xml
I have a problem launching my application in my emulator. When I run it, I get the message "Sorry MyApp has stopped unexpectedly"
This is what I get in my LogCat:
12-22 06:59:42.196: D/AndroidRuntime(1083): Shutting down VM
12-22 06:59:42.196: W/dalvikvm(1083): threadid=1: thread exiting with uncaught exception (group=0xb60294f0)
12-22 06:59:42.285: E/AndroidRuntime(1083): FATAL EXCEPTION: main
12-22 06:59:42.285: E/AndroidRuntime(1083): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.helloworld5/com.example.helloworld5.MainActivity}: java.lang.NullPointerException
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.os.Handler.dispatchMessage(Handler.java:99)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.os.Looper.loop(Looper.java:130)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.reflect.Method.invokeNative(Native Method)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.reflect.Method.invoke(Method.java:507)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-22 06:59:42.285: E/AndroidRuntime(1083): at dalvik.system.NativeStart.main(Native Method)
12-22 06:59:42.285: E/AndroidRuntime(1083): Caused by: java.lang.NullPointerException
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.Activity.findViewById(Activity.java:1647)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.example.helloworld5.MainActivity.<init>(MainActivity.java:14)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.Class.newInstanceImpl(Native Method)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.Class.newInstance(Class.java:1409)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
12-22 06:59:42.285: E/AndroidRuntime(1083): ... 11 more
So I looked in my Manifest file and changed
<activity
android:name=".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>
<activity
to:
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.helloworld5.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
However when I run it after the change I get No launch activity found!.
This is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld5"
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="#style/AppTheme" >
<activity
android:name=".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>
<activity
android:name=".Floor"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.helloworld5.FLOOR" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
This is my MainActivity code:
MainActivity.java
package com.example.helloworld5;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
//String name;
DrawView drawView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText dest = (EditText)findViewById(R.id.y_editText2);
//final String roomName = dest.getText().toString();
final Button openFloor = (Button)findViewById(R.id.y_button1);
openFloor.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
drawView.setRoomName(dest.getText().toString());
startActivity(new Intent("com.example.helloworld5.FLOOR"));
}
});
}
#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);
}
}
DrawView.java:
public class DrawView extends View {
Paint paint = new Paint();
float ux, dx, rx,lx;
String roomName2 ;
public DrawView(Context context) {
super(context);
paint.setColor(Color.RED);
//roomName2 = drawView.getTag();
}
public void setRoomName(String name) {
this.roomName2 = name;
}
public String getRoomName(){
return roomName2;
}
public void setCoordinates(){
};
#Override
public void onDraw(Canvas canvas) {
String roomName = getRoomName();
if(roomName == "C154"){
ux =90;
dx = 250;
rx = 90;
lx = 400;
}else {
ux =76;
dx = 98;
rx = 140;
lx = 300;
}
canvas.drawLine(90, 250 , 90, 400, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawCircle(150, 400, 30, paint);
}
}
How can I fix this crash?
According to this
12-22 06:59:42.285: E/AndroidRuntime(1083): Caused by: java.lang.NullPointerException
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.Activity.findViewById(Activity.java:1647)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.example.helloworld5.MainActivity.<init>(MainActivity.java:14)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.Class.newInstanceImpl(Native Method)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.Class.newInstance(Class.java:1409)
You are calling findViewById in the constructor of your activity. However, by then, the layout hasnt been inflated. Move the method call to onCreate:
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
dest = (EditText)findViewById(R.id.y_editText2);
//et cetera
}
EDIT:
Also, you're setting String roomName = dest.getText().toString(); on a null reference now. set the onClickListener like this:
openFloor.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
drawView.setRoomName(dest.getText().toString);
startActivity(new Intent("com.example.helloworld5.FLOOR"));
}
});
EDIT2: Your second NPE is because DrawView is not initialized, initialize it as well:
public void onCreate(Bundle b) {
super.onCreate(b);
//...your other stuff
this.drawView = (DrawView) findViewById(R.id.myDrawView);
}
You should move
EditText dest = (EditText)findViewById(R.id.y_editText2);
inside onCreate(...) after setContentView(...)
Issue is:
12-22 06:59:42.285: E/AndroidRuntime(1083): Caused by: java.lang.NullPointerException
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.Activity.findViewById(Activity.java:1647)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.example.helloworld5.MainActivity.<init>(MainActivity.java:14)
Put
EditText dest = (EditText)findViewById(R.id.y_editText2);
after your setContentView
This will just resolve current crash.
PLUS
put your
String roomName = dest.getText().toString();
in button click call.
If you will keep it in global variale section, it will give you NullPointerException for dest. And if you put this line in onCreate just after findViewById, it will just give you roomName = "" as at that time view has just been initialized. User entered value won't be there.
Your activity should be like this.
public class MainActivity extends ActionBarActivity {
DrawView drawView;
String roomName;
EditText dest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dest = (EditText)findViewById(R.id.y_editText2);
final Button openFloor = (Button)findViewById(R.id.y_button1);
openFloor.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
roomName = dest.getText().toString();
drawView.setRoomName(roomName);
startActivity(new Intent("com.example.helloworld5.FLOOR"));
}
});
}
}
What i am doing:: I am trying to use Myapplication class to send the data to next activity
Problem i am facing:: Having class cast exception
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
Button btn;
String TYPE_FILTER;
StringBuilder result;
MyApplication mApplication;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApplication = (MyApplication)getApplication();
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
result = new StringBuilder();
for (int i = 0; i < arraylist.size(); i++) {
if (adapter.mysparse.get(i) == true) {
result.append(arraylist.get(i).get(BLD_IndividualListOfItems_Starters.NAME));
result.append("\n");
}
}
Intent n = new Intent(BLD_IndividualListOfItems_Starters.this, ResultActivity.class);
n.putExtra("buffer", result.toString());
startActivity(n);
}
});
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(BLD_IndividualListOfItems_Starters.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
mApplication.setArrayListMapData(arraylist);
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
ResultActivity.java
public class ResultActivity extends ListActivity {
ListView lstView;
ArrayList<HashMap<String,String>> arraylist = new ArrayList<HashMap<String,String>>();
String myName;
MyApplication mApplication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for(int i=0;i<10;i++)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("key", "value"+i);
arraylist.add(map);
}
String[] from = { "key" };
int[] to = { R.id.textView1 };
SimpleAdapter adapter= new SimpleAdapter(this, arraylist,R.layout.custom_single_list, from, to);
setListAdapter(adapter);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multitabcheckboxselection"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_MainCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_SideCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Others" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Desert" />
<activity android:name="com.example.multitabcheckboxselection.ResultActivity" />
</application>
<application
android:name="com.android.app.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
</application>
</manifest>
ListViewAdapterForAtomicListItemtype.java
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements OnCheckedChangeListener {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
SparseBooleanArray mysparse;
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
mysparse = new SparseBooleanArray(data.size());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
CheckBox chk;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
chk = (CheckBox) itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);
// Capture position and set results to the TextViews
name.setText(resultp.get(BLD_IndividualListOfItems_Starters.NAME));
chk.setTag(position);
chk.setChecked(mysparse.get(position, false));
chk.setOnCheckedChangeListener(this);
return itemView;
}
public boolean isChecked(int position) {
return mysparse.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mysparse.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
mysparse.put((Integer) buttonView.getTag(), isChecked);
}
}
Log::
01-03 13:30:12.828: D/AndroidRuntime(461): Shutting down VM
01-03 13:30:12.828: W/dalvikvm(461): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-03 13:30:12.868: E/AndroidRuntime(461): FATAL EXCEPTION: main
01-03 13:30:12.868: E/AndroidRuntime(461): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters}: java.lang.ClassCastException: android.app.Application
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.os.Looper.loop(Looper.java:123)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-03 13:30:12.868: E/AndroidRuntime(461): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 13:30:12.868: E/AndroidRuntime(461): at java.lang.reflect.Method.invoke(Method.java:521)
01-03 13:30:12.868: E/AndroidRuntime(461): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-03 13:30:12.868: E/AndroidRuntime(461): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-03 13:30:12.868: E/AndroidRuntime(461): at dalvik.system.NativeStart.main(Native Method)
01-03 13:30:12.868: E/AndroidRuntime(461): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters}: java.lang.ClassCastException: android.app.Application
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2503)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:651)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.widget.TabHost.setCurrentTab(TabHost.java:323)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.widget.TabHost.addTab(TabHost.java:213)
01-03 13:30:12.868: E/AndroidRuntime(461): at com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems.onCreate(BreakfastLunchDinnerIndividualListOfItems.java:36)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-03 13:30:12.868: E/AndroidRuntime(461): ... 11 more
01-03 13:30:12.868: E/AndroidRuntime(461): Caused by: java.lang.ClassCastException: android.app.Application
01-03 13:30:12.868: E/AndroidRuntime(461): at com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters.onCreate(BLD_IndividualListOfItems_Starters.java:47)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-03 13:30:12.868: E/AndroidRuntime(461): ... 20 more
01-03 13:30:15.563: I/Process(461): Sending signal. PID: 461 SIG: 9
{Edit}
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
Button btn;
String TYPE_FILTER;
StringBuilder result;
MyApplication mApplication;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApplication = (MyApplication)getApplicationContext();
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
result = new StringBuilder();
for (int i = 0; i < arraylist.size(); i++) {
if (adapter.mysparse.get(i) == true) {
result.append(arraylist.get(i).get(BLD_IndividualListOfItems_Starters.NAME));
result.append("\n");
}
}
Intent n = new Intent(BLD_IndividualListOfItems_Starters.this, ResultActivity.class);
n.putExtra("buffer", result.toString());
startActivity(n);
}
});
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(BLD_IndividualListOfItems_Starters.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
mApplication.setArrayListMapData(arraylist);
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
MyApplication.java
package com.example.multitabcheckboxselection;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Application;
public class MyApplication extends Application {
ArrayList<HashMap<String, String>> arraylist;
#Override
public void onCreate() {
super.onCreate();
}
public void setArrayListMapData(ArrayList<HashMap<String, String>> setData)
{
arraylist = setData;
}
public ArrayList<HashMap<String, String>> getArrayListMapData()
{
return arraylist;
}
}
{Edit-3}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multitabcheckboxselection"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_MainCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_SideCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Others" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Desert" />
<activity android:name="com.example.multitabcheckboxselection.ResultActivity" />
</application>
<application
android:allowBackup="true"
android:name="com.example.multitabcheckboxselection.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
</application>
</manifest>
MyApplication.java
package com.example.multitabcheckboxselection;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Application;
public class MyApplication extends Application {
ArrayList<HashMap<String, String>> arraylist;
#Override
public void onCreate() {
super.onCreate();
}
public void setArrayListMapData(ArrayList<HashMap<String, String>> setData)
{
arraylist = setData;
}
public ArrayList<HashMap<String, String>> getArrayListMapData()
{
return arraylist;
}
}
Log::
01-03 14:13:14.509: E/AndroidRuntime(681): FATAL EXCEPTION: main
01-03 14:13:14.509: E/AndroidRuntime(681): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters}: java.lang.ClassCastException: android.app.Application
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.os.Looper.loop(Looper.java:123)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-03 14:13:14.509: E/AndroidRuntime(681): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 14:13:14.509: E/AndroidRuntime(681): at java.lang.reflect.Method.invoke(Method.java:521)
01-03 14:13:14.509: E/AndroidRuntime(681): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-03 14:13:14.509: E/AndroidRuntime(681): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-03 14:13:14.509: E/AndroidRuntime(681): at dalvik.system.NativeStart.main(Native Method)
01-03 14:13:14.509: E/AndroidRuntime(681): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters}: java.lang.ClassCastException: android.app.Application
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2503)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:651)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.widget.TabHost.setCurrentTab(TabHost.java:323)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.widget.TabHost.addTab(TabHost.java:213)
01-03 14:13:14.509: E/AndroidRuntime(681): at com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems.onCreate(BreakfastLunchDinnerIndividualListOfItems.java:36)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-03 14:13:14.509: E/AndroidRuntime(681): ... 11 more
01-03 14:13:14.509: E/AndroidRuntime(681): Caused by: java.lang.ClassCastException: android.app.Application
01-03 14:13:14.509: E/AndroidRuntime(681): at com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters.onCreate(BLD_IndividualListOfItems_Starters.java:47)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-03 14:13:14.509: E/AndroidRuntime(681): ... 20 more
Move the attribute
android:name="com.android.app.MyApplication"
to the first application element in the manifest and delete the second application element.
Btw. is your MyApplication class really in the package com.android.app?
EDIT: you use a different package, so the line should be
android:name="com.example.multitabcheckboxselection.MyApplication"
EDIT2+3: you have put it as an activity now. remove the activity, the attribute must go into the application tag.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multitabcheckboxselection"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="com.example.multitabcheckboxselection.MyApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_MainCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_SideCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Others" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Desert" />
<activity android:name="com.example.multitabcheckboxselection.ResultActivity" />
</application>
</manifest>
Normally one would do like this
class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
static public MyApplication getInstance() { return mInstance; }
static private MyApplication mInstance;
}
Then from elsewhere
MyApplication myApp = MyApplication.getInstance();
Change
mApplication = (MyApplication)getApplication();
To
mApplication = ((MyApplication) getApplicationContext());
And in Manifest.xml define android:name="MyApplication"
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="MyApplication" >
Edit
Remove this
<application
android:name="com.android.app.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
</application>
Each application will have only one <application> Tag
Change to
mApplication = (MyApplication)getApplicationContext();
Edit:
Delete the second application tag and move this to the first
android:name="com.android.app.MyApplication"
Edit:
public class MyApplication extends Application {
private static MyApplication singleton;
public MyApplication getInstance(){
return singleton;
}
public void onCreate() {
super.onCreate();
singleton = this;
}
// other methods
}
Then in Activity
mApplication = MyApplication.getInstance();
Example:
public class Main extends Activity{
ArrayList<HashMap<String,String>> arraylist = new ArrayList<HashMap<String,String>>();
MyApplication mapp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapp = MyApplication.getInstance();
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("My String from Application class is"+mapp.hello);
for(int i=0;i<10;i++)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("key", "value"+i);
arraylist.add(map);
}
mapp.setArrayListMapData(arraylist);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Main.this,MainActivity.class));
}
});
}
main.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_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="51dp"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
MainActivity
public class MainActivity extends ListActivity
{
ListView lstView;
ArrayList<HashMap<String,String>> arraylist;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MyApplication mApplication = MyApplication.getInstance();
Log.i("................",""+mApplication.hello);
lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
arraylist= mApplication.getArrayListMapData();
String[] from = { "key" };
int[] to = { R.id.textView1 };
SimpleAdapter adapter= new SimpleAdapter(this, arraylist,R.layout.row, from, to);
setListAdapter(adapter);
}
}
MyApplication
public class MyApplication extends Application {
ArrayList<HashMap<String, String>> arraylist;
private static MyApplication instance = null;
public String hello= "Hello global Application";
#Override
public void onCreate() {
super.onCreate();
}
public static MyApplication getInstance() {
if(instance == null) {
instance = new MyApplication();
}
return instance;
}
public void setArrayListMapData(ArrayList<HashMap<String, String>> setData)
{
arraylist = setData;
}
public ArrayList<HashMap<String, String>> getArrayListMapData()
{
return arraylist;
}
}
Manifest file
<application
android:allowBackup="true"
android:name="com.example.testlistactivity.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.testlistactivity.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.testlistactivity.MainActivity"
android:label="#string/app_name" >
</activity>
</application>
Snap1
Snap2
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);