Having a classcast exception in android while using MyApplication class - java

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

Related

cannot be cast to android.app.activity

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

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

Unable to instantiate activity ComponentInfo .. java.lang.NullPointerException

I'm trying to run a simple app using volley and a custom header, it builds with no error, I'm running it directly in my smartphone, but when the app start I get the following log:
06-24 16:35:35.653 1380-1380/com.rep E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.rep, PID: 1380
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.rep/com.rep.app.principal.InicioActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2135)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:230)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:43)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at com.representemais.app.principal.InicioActivity.<init>(InicioActivity.java:86)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1084)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2126)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.access$800(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5102)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
that's the InicioActivity:
package com.rep.app.principal;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.rep.R;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InicioActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AutenticacaoLocalTask mAutenticacaoLocalTask = new AutenticacaoLocalTask();
mAutenticacaoLocalTask.execute((Void) null);
}
private TextView txtDisplay;
RequestQueue queue = Volley.newRequestQueue(this);
public class AutenticacaoLocalTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://192.168.1.15/rep-api/api/clients";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-API-TOKEN", "99KI9Gj68CgCf70deM22Ka64chef2C40Gm2lFJ2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8");
return headers;
}
};
queue.add(jsonObjReq);
return true;
} catch (Exception e) {
Log.e("RM", e.getMessage());
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
}
#Override
protected void onCancelled() {
}
}
}
and the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rep"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<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.ACCESS_WIFI_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".app.principal.InicioActivity"
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=".app.login.LoginActivity"
android:configChanges="keyboardHidden"
android:label="#string/app_name">
</activity>
<activity
android:name=".app.principal.MainActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.cliente.ClienteDetalheActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.login.LoginTelaBloqueada"
android:label="#string/app_name"></activity>
</application>
</manifest>
Initialize your RequestQueue, using Volley.newRequestQueue(this);, in onCreate() after the super.onCreate() call. You are trying to use your Activity from an initializer, which frequently causes problems like this.
Step #1: Replace:
RequestQueue queue = Volley.newRequestQueue(this);
with:
RequestQueue queue = null;
Step #2: Change your onCreate() to be:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queue=Volley.newRequestQueue(this);
AutenticacaoLocalTask mAutenticacaoLocalTask = new AutenticacaoLocalTask();
mAutenticacaoLocalTask.execute((Void) null);
}

Why am I getting a force close? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I know I have already asked this question but no one answered after the first answer which I changed what he told me and still no result
HOME.java
package com.example.decrypter;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.AdapterView.OnItemSelectedListener;
public class Home extends Activity implements OnItemSelectedListener {
Button btn_start,btn_about,btn_exit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
btn_start = (Button) findViewById(R.id.btn_start);
btn_about = (Button) findViewById(R.id.btn_about);
btn_exit = (Button) findViewById(R.id.btn_exit);
btn_start.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v) {
Intent start = new Intent(Home.this, MainPage.class);
Home.this.startActivity(start);
}
});
btn_about.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
Intent about = new Intent(Home.this, about.class);
Home.this.startActivity(about);
}
});
btn_exit.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
System.exit(0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.home, menu);
return true;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
MainPage.java
package com.example.decrypter;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
public class MainPage extends Activity implements OnItemSelectedListener {
double random1,random2,random3,random4,random5;
int check1,check2,check3,check4,check5;
EditText textbox;
int guess;
String s1,s2,s3,s4,s5;
Spinner spinner1,spinner2,spinner3,spinner4,spinner5;
TextView display1,display2,display3,display4,display5;
Integer[] numbers = {1,2,3,4,5,6,7,8,9};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter <Integer> adapter1 = new ArrayAdapter <Integer>(this,
android.R.layout.simple_spinner_item, numbers);
setContentView(R.layout.activity_main_page);
spinner1 =(Spinner) findViewById(R.id.spinner01);
spinner2= (Spinner) findViewById(R.id.spinner02);
spinner3= (Spinner) findViewById(R.id.spinner03);
spinner4= (Spinner) findViewById(R.id.spinner04);
spinner5= (Spinner) findViewById(R.id.spinner05);
display1 = (TextView) findViewById(R.id.txtdisplay1);
display2 = (TextView) findViewById(R.id.txtdisplay2);
display3 = (TextView) findViewById(R.id.txtdisplay3);
display4 = (TextView) findViewById(R.id.txtdisplay4);
display5 = (TextView) findViewById(R.id.txtdisplay5);
Button btnrandom = (Button) findViewById(R.id.btnrandom);
Button btn1 = (Button) findViewById(R.id.btn1);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(this);
spinner2.setAdapter(adapter1);
spinner2.setOnItemSelectedListener(this);
spinner3.setAdapter(adapter1);
spinner3.setOnItemSelectedListener(this);
spinner4.setAdapter(adapter1);
spinner4.setOnItemSelectedListener(this);
spinner5.setAdapter(adapter1);
spinner5.setOnItemSelectedListener(this);
btnrandom.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
random1 = Math.floor(Math.random()*10);
random2 = Math.floor(Math.random()*10);
random3 = Math.floor(Math.random()*10);
random4 = Math.floor(Math.random()*10);
random5 = Math.floor(Math.random()*10);
//display.setText("random:" + random1);
/*check1 = Integer.parseInt(spinner1.getSelectedItem().toString()) ;
*/
}
});
btn1.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
if(check1==random1){
display1.setTextColor(Color.GREEN);
s1= Integer.toString(check1);
display1.setText(s1);
}
else{
display1.setTextColor(Color.RED);
s1= Integer.toString(check1);
display1.setText(s1);
}
if(check2==random2){
display2.setTextColor(Color.GREEN);
s2= Integer.toString(check2);
display2.setText(s2);
}
else{
display2.setTextColor(Color.RED);
s2= Integer.toString(check2);
display2.setText(s2);
}
if(check3==random3){
display3.setTextColor(Color.GREEN);
s3= Integer.toString(check3);
display3.setText(s3);
}
else{
display3.setTextColor(Color.RED);
s3= Integer.toString(check3);
display3.setText(s3);
}
if(check4==random4){
display4.setTextColor(Color.GREEN);
s4= Integer.toString(check4);
display4.setText(s4);
}
else{
display4.setTextColor(Color.RED);
s4= Integer.toString(check4);
display4.setText(s4);
}
if(check5==random5){
display5.setTextColor(Color.GREEN);
s5= Integer.toString(check5);
display5.setText(s5);
}
else{
display5.setTextColor(Color.RED);
s5= Integer.toString(check5);
display5.setText(s5);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.activity_main_page, menu);
return true;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
check1 = Integer.parseInt(spinner1.getSelectedItem().toString());
check2 = Integer.parseInt(spinner2.getSelectedItem().toString()) ;
check3 = Integer.parseInt(spinner3.getSelectedItem().toString()) ;
check4 = Integer.parseInt(spinner4.getSelectedItem().toString()) ;
check5 = Integer.parseInt(spinner5.getSelectedItem().toString()) ;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Splash.java
package com.example.decrypter;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
MediaPlayer splashSong;
#Override
protected void onCreate(Bundle splashpage) {
// TODO Auto-generated method stub
super.onCreate(splashpage);
setContentView(R.layout.splash);
splashSong = MediaPlayer.create(Splash.this, R.raw.splashsound);
splashSong.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
} finally {
Intent openHome = new Intent
("com.example.decrypter.HOME");
startActivity(openHome);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//splashSong.release();
finish();
}
}
Android Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.decrypter"
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" >
<activity
android:name=".Splash"
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=".Home"
android:label="#string/title_activity_home" >
<intent-filter>
<action android:name="com.example.decrypter.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".about"
android:label="about" >
<intent-filter>
<action android:name="com.example.decrypter.ABOUT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MainPage"
android:label="MainPage" >
<intent-filter>
<action android:name="com.example.decrypter.MAINPAGE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
LOGCAT ERROR
12-11 11:36:27.182: D/dalvikvm(336): GC_EXTERNAL_ALLOC freed 55K, 53% free 2570K/5379K, external 2131K/2137K, paused 53ms
12-11 11:36:27.271: D/AndroidRuntime(336): Shutting down VM
12-11 11:36:27.271: W/dalvikvm(336): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-11 11:36:27.291: E/AndroidRuntime(336): FATAL EXCEPTION: main
12-11 11:36:27.291: E/AndroidRuntime(336): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.decrypter/com.example.decrypter.Home}: java.lang.ClassCastException: android.widget.RelativeLayout
12-11 11:36:27.291: E/AndroidRuntime(336): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-11 11:36:27.291: E/AndroidRuntime(336): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-11 11:36:27.291: E/AndroidRuntime(336): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-11 11:36:27.291: E/AndroidRuntime(336): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-11 11:36:27.291: E/AndroidRuntime(336): at android.os.Handler.dispatchMessage(Handler.java:99)
12-11 11:36:27.291: E/AndroidRuntime(336): at android.os.Looper.loop(Looper.java:123)
12-11 11:36:27.291: E/AndroidRuntime(336): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-11 11:36:27.291: E/AndroidRuntime(336): at java.lang.reflect.Method.invokeNative(Native Method)
12-11 11:36:27.291: E/AndroidRuntime(336): at java.lang.reflect.Method.invoke(Method.java:507)
12-11 11:36:27.291: E/AndroidRuntime(336): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-11 11:36:27.291: E/AndroidRuntime(336): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-11 11:36:27.291: E/AndroidRuntime(336): at dalvik.system.NativeStart.main(Native Method)
12-11 11:36:27.291: E/AndroidRuntime(336): Caused by: java.lang.ClassCastException: android.widget.RelativeLayout
12-11 11:36:27.291: E/AndroidRuntime(336): at com.example.decrypter.Home.onCreate(Home.java:23)
12-11 11:36:27.291: E/AndroidRuntime(336): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-11 11:36:27.291: E/AndroidRuntime(336): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-11 11:36:27.291: E/AndroidRuntime(336): ... 11 more
First, try cleaning your project (e.g., Project > Clean from the Eclipse main menu). If that does not help, you have a RelativeLayout in activity_main_page.xml that has the wrong android:id value, apparently. Which ID it is using would be based on line 23 of your Home.java class, whichever line that is.
you don't deserve but:
12-11 11:36:27.291: E/AndroidRuntime(336): Caused by: java.lang.ClassCastException: android.widget.RelativeLayout
12-11 11:36:27.291: E/AndroidRuntime(336): at com.example.decrypter.Home.onCreate(Home.java:23)
that means... on com.example.decrypter.Home.OnCreate, on line 23 you're casting something to RelativeLayout, and it's NOT a relative layout!
learn to read, you must, young padwan!

RunTimeException when trying to implement GPS Locater

I am working on adding GPS location services to my app. However I get this error I just can't seem to fix. I have included all of my relevant coding. And if anybody has comments on any of my coding not related to the error I would appreciate them too.
Logcat
08-09 11:19:24.602: E/AndroidRuntime(715): FATAL EXCEPTION: main
08-09 11:19:24.602: E/AndroidRuntime(715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.com.proto1/com.example.com.proto1.menu}: android.view.InflateException: Binary XML file line #77: Error inflating class com.google.android.maps.MapView
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.os.Handler.dispatchMessage(Handler.java:99)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.os.Looper.loop(Looper.java:137)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Method.invokeNative(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Method.invoke(Method.java:511)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-09 11:19:24.602: E/AndroidRuntime(715): at dalvik.system.NativeStart.main(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: android.view.InflateException: Binary XML file line #77: Error inflating class com.google.android.maps.MapView
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createView(LayoutInflater.java:613)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Activity.setContentView(Activity.java:1867)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.example.com.proto1.menu.onCreate(menu.java:62)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Activity.performCreate(Activity.java:5008)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 11 more
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: java.lang.reflect.InvocationTargetException
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Constructor.constructNative(Native Method)
08-09 11:19:24.602: E/AndroidRuntime(715): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
08-09 11:19:24.602: E/AndroidRuntime(715): at android.view.LayoutInflater.createView(LayoutInflater.java:587)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 22 more
08-09 11:19:24.602: E/AndroidRuntime(715): Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity.
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:291)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:264)
08-09 11:19:24.602: E/AndroidRuntime(715): at com.google.android.maps.MapView.<init>(MapView.java:247)
08-09 11:19:24.602: E/AndroidRuntime(715): ... 25 more
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.proto1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/theeye"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".mainj"
android:label="#string/title_activity_mainj" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".menu"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Infoactive"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.INFOSCREEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VoicePrompts"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VOICEPROMPTS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VPon"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VPON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".VPoff"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VPOFF" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- android name must match the name of the java you want to use -->
<activity
android:name=".VoiceRecognition"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.RECOGNITIONMENU" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Recognition"
android:label="#string/app_name" >
<intent-filter>
<action android:name="ACTION_RECOGNIZE_SPEECH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SpeakingAndroid"
android:label="tts" >
<intent-filter>
<action android:name="android.intent.action.SPEAK" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyGPSActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="GPS_LOCATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<library
name="com.google.android.maps"
file="/system/framework/com.google.android.maps.jar" />
<uses-library android:name="com.google.android.maps" />
</application>
</manifest>
Main XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="100" >
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="5dp" >
</ListView>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:gravity="bottom"
android:orientation="horizontal"
android:weightSum="100" >
<Button
android:id="#+id/aboutbutton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/a"
android:textSize="25dp" />
<Button
android:id="#+id/talk"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="talk"
android:textSize="25dp" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:weightSum="100" >
<Button
android:id="#+id/voicebutton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/starttalking"
android:textSize="25dp" />
<Button
android:id="#+id/btn_speak"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="50"
android:gravity="center"
android:text="#string/start"
android:textSize="25dp" />
</LinearLayout>
<com.google.android.maps.MapView
android:id="#+id/myGMap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="API_Key_String"
android:clickable="true"
android:enabled="true" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
Menu(Main) Java
package com.example.com.proto1;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.example.com.proto1.MyGPSActivity.LocationResult;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
#SuppressWarnings("unused")
public class menu extends Activity implements TextToSpeech.OnInitListener,
OnClickListener {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// Got the location!
}
};
MyGPSActivity myLocation = new MyGPSActivity();
// defined
TextToSpeech mTts;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
// remember to include a listview on the xml or the voice recognition code
// will not work
public ListView mList;
// TTS object
Button speakButton, infoButton, voiceButton, talkButton;
// TTS object
public TextToSpeech myTTS;
// status check code
public int MY_DATA_CHECK_CODE = 0;
#Override
protected void onCreate(Bundle aboutmenu) {
super.onCreate(aboutmenu);
setContentView(R.layout.mainx);
SpeakingAndroid speak = new SpeakingAndroid();
VoiceRecognition voiceinput = new VoiceRecognition();
// get a reference to the button element listed in the XML layout
speakButton = (Button) findViewById(R.id.btn_speak);
infoButton = (Button) findViewById(R.id.aboutbutton);
voiceButton = (Button) findViewById(R.id.voicebutton);
talkButton = (Button) findViewById(R.id.talk);
// listen for clicks
infoButton.setOnClickListener(this);
speakButton.setOnClickListener(this);
talkButton.setOnClickListener(this);
// check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
// calling method
voiceinputbuttons();
// Check to see if a recognition activity is present
// if running on AVD virtual device it will give this message. The mic
// required only works on an actual android device//
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
voiceButton.setOnClickListener(this);
} else {
voiceButton.setEnabled(false);
voiceButton.setText("Recognizer not present");
}
}
// setup TTS
public void onInit(int initStatus) {
// check for successful instantiation
// returns a fail statement if speech doesn't work
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
public void informationmenu() {
speakWords("information screen");
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
public void voicemenu() {
speakWords("voice recognition menu");
startActivity(new Intent("android.intent.action.RECOGNITIONMENU"));
}
public void mainmenu() {
speakWords("main menu");
startActivity(new Intent("android.intent.action.MENU"));
}
// creating method
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
// respond to button clicks
public void onClick(View v) {
switch (v.getId()) {
// use switch case so each button does a different thing
// accurately(similar to an if statement)
case R.id.btn_speak:
String words1 = speakButton.getText().toString();
// speakwords(xxxx); is the piece of code that actually calls the
// text to speech
speakWords(words1);
myLocation.getLocation(this, locationResult);
break;
case R.id.aboutbutton:
String words2 = infoButton.getText().toString();
speakWords(words2);
Intent infoIntent = new Intent("android.intent.action.INFOSCREEN");
startActivity(infoIntent);
break;
case R.id.voicebutton:
speakWords("Speak Now");
startVoiceRecognitionActivity(); // call for voice recognition
// activity
break;
case R.id.talk:
speakWords("This is the main menu.");
break;
}
}
// speak the user text
// setting up the speakWords code
public void speakWords(String speech) {
// speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
/**
* Fire an intent to start the speech recognition activity.
*/
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
&& resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it
// could have heard
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, matches));
// matches is the result of voice input. It is a list of what the
// user possibly said.
// Using an if statement for the keyword you want to use allows the
// use of any activity if keywords match
// it is possible to set up multiple keywords to use the same
// activity so more than one word will allow the user
// to use the activity (makes it so the user doesn't have to
// memorize words from a list)
// to use an activity from the voice input information simply use
// the following format;
// if (matches.contains("keyword here") { startActivity(new
// == Intent("name.of.manifest.ACTIVITY")
if (matches.contains("information")) {
informationmenu();
}
if (matches.contains("info screen")) {
informationmenu();
}
if (matches.contains("info")) {
informationmenu();
}
if (matches.contains("about")) {
informationmenu();
}
if (matches.contains("home")) {
mainmenu();
}
if (matches.contains("menu")) {
mainmenu();
}
if (matches.contains("home screen")) {
mainmenu();
}
if (matches.contains("speak")) {
startActivity(new Intent("android.intent.action.SPEAK"));
}
if (matches.contains("close")) {
finish();
}
if (matches.contains("stop")) {
finish();
}
if (matches.contains("finish")) {
finish();
}
if (matches.contains("voice")) {
voicemenu();
}
if (matches.contains("recognition")) {
voicemenu();
}
if (matches.contains("voice recognition")) {
voicemenu();
}
}
// still in the onActivityResult: This is for the text to speech part
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
myTTS.shutdown();
}
}
GPS Java
package com.example.com.proto1;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class MyGPSActivity {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Put the following line in the application element of AndroidManifest.xml file.
<uses-library android:name="com.google.android.maps" />

Categories