Java.lang.NullPointerException at getapplicationContext() while initiating adapter - java

While running the project on Android emulator,I face the exception as java.lang.NullPointerException at getApplicationContext.Please help me to resolve this issue.
Error
07-19 15:08:07.811: D/AndroidRuntime(366): Shutting down VM
07-19 15:08:07.811: W/dalvikvm(366): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-19 15:08:07.841: E/AndroidRuntime(366): FATAL EXCEPTION: main
07-19 15:08:07.841: E/AndroidRuntime(366): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{org.TfsMutualFund/org.TfsMutualFund.loading}: java.lang.NullPointerException
07-19 15:08:07.841: E/AndroidRuntime(366): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-19 15:08:07.841: E/AndroidRuntime(366): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-19 15:08:07.841: E/AndroidRuntime(366): Caused by: java.lang.NullPointerException
07-19 15:08:07.841: E/AndroidRuntime(366): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
07-19 15:08:07.841: E/AndroidRuntime(366): at org.TfsMutualFund.loading.<init>(loading.java:23)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.TfsMutualFund">
<uses-sdk android:targetSdkVersion="8" />
<application android:name=".globalAdapter" android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".loading"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar"
android:configChanges="orientation|keyboard|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".TFSManinActivity"
android:configChanges="orientation|keyboard|keyboardHidden"/>
</application>
loading.java
package org.TfsMutualFund;
public class loading extends Activity{
private static ArrayAdapter<String> adapter;
private globalAdapter adpt = ((globalAdapter)getApplicationContext());
private String ServicePath = adpt.getServicePath();
private String ServiceName = adpt.getServiceName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading);
if(isOnline())
new AsyncLoad().execute();
else

Don't initialize it before OnCreate(), you can't get Context with there, do it in onCreate().
private globalAdapter adpt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading);
adpt = ((globalAdapter)getApplicationContext());
...
}

1. Dont initialize the below before the onCreate, let the views get their ids first
private globalAdapter adpt = ((globalAdapter)getApplicationContext());
private String ServicePath = adpt.getServicePath();
private String ServiceName = adpt.getServiceName();
2. Just Declare them....
private globalAdapter adpt;
private String ServicePath;
private String ServiceName;
3. Its because when the Activity is not formed, how can you get the Context to that activity, cause you are using the getApplicationContext() to get the current Activity context.

Related

Unable to find explicit activity class {}; have you declared this activity in your AndroidManifest.xml

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

Unable to instantiate activity ComponentInfo, android using java

UPDATE
Like an idiot I did not pay attention to the logCat.
The problem was coming from the page I was navigating to, not the intent itself, I was declaring some code before the setContentView code has a chance to run within onContentLoad().
Thanks for all the help!
I know this question has been asked before, but I have followed numerous posts about this topic; but can't seem to find the right answer.
I am trying to navigate from my MainActivity page, to my ViewFeeds page; but it is throwing the above error.
The funny thing is, I have already got the code to navigate between pages, and it works. But when I come to duplicate this code for another class, it throws the above error.
MainActivity Code (The one I am navigating from):
public void btnFeedsClick(View v)
{
Button button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ViewFeeds.class);
MainActivity.this.startActivity(intent);
}
});
}
The ViewFeeds class (The one I am navigating to):
package com.example.rssapplication;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ViewFeeds extends Activity{
//The array which holds all of the data...
ArrayList<String> items = new ArrayList<String>();
ListView lv = (ListView) findViewById(R.id.listView1);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewfeeds);
ActionBar actionBar = getActionBar();
actionBar.hide();
items = new ArrayList<String>();
String ret = "";
try {
InputStream inputStream = openFileInput("Teams.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
// Toast.makeText(MainActivity.this, receiveString, Toast.LENGTH_LONG).show();
try {
while ( (receiveString = bufferedReader.readLine()) != null ) {
items.add(receiveString);
stringBuilder.append(receiveString + "\r\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputStream.close();
//ret holds each line of text from the file...
ret = stringBuilder.toString();
TextView txt = (TextView) findViewById(R.id.textView6);
txt.setText(ret);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
items);
lv.setAdapter(arrayAdapter);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The android Manifest (I have put a comment above the section in which I am declaring the reference):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rssapplication"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<application
android:allowBackup="true"
android:icon="#drawable/sportsoccericon"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:screenOrientation="portrait"
>
<activity
android:name="com.example.rssapplication.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="com.example.rssapplication.SelectTeams" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MainActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- This is where I am creating the intent to navigate from main, to viewfeeds -->
<activity android:name="com.example.rssapplication.ViewFeeds" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MainActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="com.example.rssapplication.ShowArticle" android:label="#string/app_name"
android:parentActivityName="com.example.rssapplication.MyAdapter"
>
<!-- <meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.rssapplication.MyAdapter" />-->
<!-- <intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter> -->
</activity>
</application>
</manifest>
This is he logcat:
08-07 16:27:02.512: E/AndroidRuntime(2321): FATAL EXCEPTION: main
08-07 16:27:02.512: E/AndroidRuntime(2321): Process: com.example.rssapplication, PID: 2321
08-07 16:27:02.512: E/AndroidRuntime(2321): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.rssapplication/com.example.rssapplication.ViewFeeds}: java.lang.NullPointerException
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.app.ActivityThread.access$900(ActivityThread.java:161)
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.os.Handler.dispatchMessage(Handler.java:102)
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.os.Looper.loop(Looper.java:157)
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.app.ActivityThread.main(ActivityThread.java:5356)
08-07 16:27:02.512: E/AndroidRuntime(2321): at java.lang.reflect.Method.invokeNative(Native Method)
08-07 16:27:02.512: E/AndroidRuntime(2321): at java.lang.reflect.Method.invoke(Method.java:515)
08-07 16:27:02.512: E/AndroidRuntime(2321): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-07 16:27:02.512: E/AndroidRuntime(2321): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-07 16:27:02.512: E/AndroidRuntime(2321): at dalvik.system.NativeStart.main(Native Method)
08-07 16:27:02.512: E/AndroidRuntime(2321): Caused by: java.lang.NullPointerException
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.app.Activity.findViewById(Activity.java:1965)
08-07 16:27:02.512: E/AndroidRuntime(2321): at com.example.rssapplication.ViewFeeds.<init>(ViewFeeds.java:20)
08-07 16:27:02.512: E/AndroidRuntime(2321): at java.lang.Class.newInstanceImpl(Native Method)
08-07 16:27:02.512: E/AndroidRuntime(2321): at java.lang.Class.newInstance(Class.java:1208)
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
08-07 16:27:02.512: E/AndroidRuntime(2321): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2222)
08-07 16:27:02.512: E/AndroidRuntime(2321): ... 11 more
Any help will be greatly appreciated!
Thanks,
Callum
The problem is this:
ListView lv = (ListView) findViewById(R.id.listView1);
You are calling findViewById() too early! You always have to be aware of the Activity Lifecycle! findViewById() can only be called after you set a layout with setContentView().
You should look for Views in onCreate() like this:
public class ViewFeeds extends Activity {
private ArrayList<String> items = new ArrayList<String>();
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewfeeds);
lv = (ListView) findViewById(R.id.listView1);
...
}
...
}
1st problem declare this inside onCreate(...) after setContentView(R.layout.ur_layout)
ListView lv = (ListView) findViewById(R.id.listView1);
2nd problem as your application's android:minSdkVersion="8" you should use
ActionBar actionBar = getSupportActionBar();
instead of Activity you have to extends ActionBarActivity of appcompat v7 support library
ActionbarActivity
How to import appcompat into your project

Having a classcast exception in android while using MyApplication class

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

NullPointerException while starting an activity in android

I am getting NullPointerException while starting a helloworld activity. I am starting this class from FileEvent.java class, which code I have put down here.
public class FileEvent extends Activity implements ObserverActivity{
public static String path2;
public String filename;
public String path;
public adapter info ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.info = new adapter(this);
}
public void insert(String path) {
// TODO Auto-generated method stub
// try{
this.info = new adapter(this);
this.filename = path;
System.out.println("Starting intent in fileevent");
try{
startActivity(new Intent(FileEvent.this,hello.class)); // In this line I am getting nullpointerexception was caught.
}
catch(Exception e)
{
Log.v("Caught in insert() of FileEvent : ",e.toString());
}
}
hello.class consists of a simple textview.
AndroidManifest.xml :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sample_fileobserver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.sample_fileobserver.hello"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.hello" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.sample_fileobserver.FileEvent"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.FIleEvent" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
The logcat shows the following message -
09-28 05:51:55.307: I/System.out(13542): Starting intent in fileevent
09-28 05:51:55.307: A/FileObserver(13542): Unhandled exception in FileObserver com.example.sample_fileobserver.MyFileObserver#b11bec18
09-28 05:51:55.307: A/FileObserver(13542): java.lang.NullPointerException
09-28 05:51:55.307: A/FileObserver(13542): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
09-28 05:51:55.307: A/FileObserver(13542): at android.content.ComponentName.<init>(ComponentName.java:75)
09-28 05:51:55.307: A/FileObserver(13542): at android.content.Intent.<init>(Intent.java:3662)
09-28 05:51:55.307: A/FileObserver(13542): at com.example.sample_fileobserver.FileEvent.insert(FileEvent.java:42)
09-28 05:51:55.307: A/FileObserver(13542): at com.example.sample_fileobserver.MyFileObserver.onEvent(MyFileObserver.java:70)
09-28 05:51:55.307: A/FileObserver(13542): at android.os.FileObserver$ObserverThread.onEvent(FileObserver.java:125)
09-28 05:51:55.307: A/FileObserver(13542): at android.os.FileObserver$ObserverThread.observe(Native Method)
09-28 05:51:55.307: A/FileObserver(13542): at android.os.FileObserver$ObserverThread.run(FileObserver.java:88)
Note :-
1) I have not declared setContentView() in FileEvent class, since it does not going to use UI.
2) Here onCreate() is not running, as I am calling insert() from another class of my application.
It might seem that, this question might be duplicate of many other questions, but I did not find the right solution from those questions.
Thanks in advance.
You are getting error because you are trying to call another activity with FileEvent class context. I think it is not possible.
If you are calling insert() method from another class, have to pass context of that class.
Try to pass Context of that class.
Your Method should be
public void insert(String path, Context context)
{
info = new adapter(context);
filename = path;
try
{
startActivity(new Intent(context,hello.class));
}
catch(Exception e)
{
Log.v("Caught in insert() of FileEvent : ",e.toString());
}
}
Hope it will help you.
Change your manifest:
<activity
android:name="com.example.sample_fileobserver.FileEvent"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

error- dalvik.system.PathClassLoader [data/app/com.my.appname-2.apk]

I searched a lot for similar kind of error, but I am not getting a solution for it. I am getting this error as soon as I start the app
03-21 10:33:08.100: E/AndroidRuntime(13098): FATAL EXCEPTION: main
03-21 10:33:08.100: E/AndroidRuntime(13098): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.airlife/com.example.airlife.MainActivity}: java.lang.ClassNotFoundException: com.example.airlife.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.airlife-2.apk]
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1785)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1893)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.access$1500(ActivityThread.java:135)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1054)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.os.Looper.loop(Looper.java:150)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.main(ActivityThread.java:4389)
03-21 10:33:08.100: E/AndroidRuntime(13098): at java.lang.reflect.Method.invokeNative(Native Method)
03-21 10:33:08.100: E/AndroidRuntime(13098): at java.lang.reflect.Method.invoke(Method.java:507)
03-21 10:33:08.100: E/AndroidRuntime(13098): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
03-21 10:33:08.100: E/AndroidRuntime(13098): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
03-21 10:33:08.100: E/AndroidRuntime(13098): at dalvik.system.NativeStart.main(Native Method)
03-21 10:33:08.100: E/AndroidRuntime(13098): Caused by: java.lang.ClassNotFoundException: com.example.airlife.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.airlife-2.apk]
03-21 10:33:08.100: E/AndroidRuntime(13098): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
03-21 10:33:08.100: E/AndroidRuntime(13098): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
03-21 10:33:08.100: E/AndroidRuntime(13098): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.Instrumentation.newActivity(Instrumentation.java:1040)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1777)
03-21 10:33:08.100: E/AndroidRuntime(13098): ... 11 more
MainActivity.java is like this
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends MapActivity implements OnClickListener{
private ImageButton mVid,mAgebtn,mWeightbtn,mPicbtn,mMsgbtn,mReqbtn,mHelibtn,mDocbtn,mContextbtn;
private MapView mapView;
private MyLocationOverlay myLocationOverlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView)findViewById(R.id.webview);
mapView.setBuiltInZoomControls(true);
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
mapView.postInvalidate();
// call convenience method that zooms map on our location
zoomToMyLocation();
mAgebtn = (ImageButton) findViewById(R.id.imageView36);
mWeightbtn = (ImageButton) findViewById(R.id.imageView4);
mPicbtn = (ImageButton) findViewById(R.id.imageView5);
mMsgbtn = (ImageButton) findViewById(R.id.imageView6);
mReqbtn = (ImageButton) findViewById(R.id.imageView32);
mHelibtn = (ImageButton) findViewById(R.id.btnsearch);
mDocbtn = (ImageButton) findViewById(R.id.btnprovide);
mVid = (ImageButton) findViewById(R.id.btnpost);
mContextbtn = (ImageButton) findViewById(R.id.btnsettings);
mAgebtn.setOnClickListener(this);
mWeightbtn.setOnClickListener(this);
mPicbtn.setOnClickListener(this);
mMsgbtn.setOnClickListener(this);
mReqbtn.setOnClickListener(this);
mHelibtn.setOnClickListener(this);
mDocbtn.setOnClickListener(this);
mVid.setOnClickListener(this);
mContextbtn.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
// when our activity resumes, we want to register for location updates
myLocationOverlay.enableMyLocation();
}
#Override
protected void onPause() {
super.onPause();
// when our activity pauses, we want to remove listening for location updates
myLocationOverlay.disableMyLocation();
}
/**
* This method zooms to the user's location with a zoom level of 10.
*/
private void zoomToMyLocation() {
GeoPoint myLocationGeoPoint = myLocationOverlay.getMyLocation();
if(myLocationGeoPoint != null) {
mapView.getController().animateTo(myLocationGeoPoint);
mapView.getController().setZoom(10);
}
else {
Toast.makeText(this, "Cannot determine location", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.airlife"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.airlife.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=".playvid" />
<activity android:name=".Display" />
<activity android:name=".Video" />
<activity android:name=".Documents" />
<activity android:name=".Contact" />
<activity android:name=".FixedMyLocationOverlay" />
</application>
</manifest>
Please tell me why I am getting this error, and how to solve this.
Got the solution. I had missed this code in my manifest file
<uses-library android:name="com.google.android.maps"/>
Class not found exception in MainActivity.
I think you've the wrong package, or that your APK doesn't have what you think it has.This is your package name.
com.example.airlife
Maku sure that it is imported in all activities as.
package com.example.airlife;
and don't forget to add entry in manifest file for every new activity.
If so, then make this change in manifest file. No need to mention your package name and remove allowBackUp
<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>
if not this try adding any library files you are using. missing library files may also cause this exception. see this link
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo after SDK update

Categories