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);
Related
How to solve this error:
revoked permission android.permission.CALL_PHONE
This is my Java code:
public class DetailContactActivity extends AppCompatActivity implements
OnClickListener {
private TextView phone, email;
private int id;
private ImageView call, btnEmail;
private ContactDB db;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_contact);
db = ContactDB.getInstance(this);
phone = (TextView) findViewById(R.id.txt_phone_number);
email = (TextView) findViewById(R.id.txt_email);
call = (ImageView) findViewById(R.id.btn_call);
btnEmail = (ImageView) findViewById(R.id.btn_email);
Bundle b = getIntent().getExtras();
if (b != null)
{
id = b.getInt("id");
phone.setText(b.getString("phone"));
getSupportActionBar().setTitle(b.getString("nama"));
if (!b.getString("email").equals("null"))
{
email.setText(b.getString("email"));
} else
{
email.setText("");
}
}
call.setOnClickListener(this);
btnEmail.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.detail_contact, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_edit:
Bundle b = new Bundle();
b.putInt("id", id);
b.putString("name", getSupportActionBar().getTitle().toString());
b.putString("email", email.getText().toString());
b.putString("phone", phone.getText().toString());
Intent i = new Intent(this, EditActivity.class);
i.putExtras(b);
startActivity(i);
finish();
return true;
case R.id.action_delete:
showSettingsAlert();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v)
{
if (v == btnEmail)
{
if (!email.getText().toString().equals(""))
{
Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts("mailto", email.getText().toString(),
null));
startActivity(Intent
.createChooser(emailIntent, "Send email..."));
}
} else if (v == call)
{
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phone.getText().toString()));
startActivity(callIntent);
//Uri call = Uri.parse("tel:" + phone.getText().toString());
//Intent surf = new Intent(Intent.ACTION_CALL, call);
//startActivity(surf);
}
}
private void showSettingsAlert()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Delete");
alert.setMessage("Contact akan dihapus");
alert.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
db.deleteContact(id);
startActivity(new Intent(DetailContactActivity.this,
MainActivity.class));
finish();
}
});
alert.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alert.show();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(DetailContactActivity.this, MainActivity.class));
finish();
}
Error:
01-02 02:05:41.493: D/AndroidRuntime(2927): Shutting down VM
01-02 02:05:41.493: D/AndroidRuntime(2927): --------- beginning of crash
01-02 02:05:41.616: E/AndroidRuntime(2927): FATAL EXCEPTION: main
01-02 02:05:41.616: E/AndroidRuntime(2927): Process: com.example.phonedb, PID: 2927
01-02 02:05:41.616: E/AndroidRuntime(2927): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxxxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{f5320c4 2927:com.example.phonedb/u0a69} (pid=2927, uid=10069) with revoked permission android.permission.CALL_PHONE
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.os.Parcel.readException(Parcel.java:1599)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.os.Parcel.readException(Parcel.java:1552)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2658)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1507)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.app.Activity.startActivityForResult(Activity.java:3917)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.app.Activity.startActivityForResult(Activity.java:3877)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:748)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.app.Activity.startActivity(Activity.java:4200)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.app.Activity.startActivity(Activity.java:4168)
01-02 02:05:41.616: E/AndroidRuntime(2927): at com.example.phonedb.DetailContactActivity.onClick(DetailContactActivity.java:127)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.view.View.performClick(View.java:5198)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.view.View$PerformClick.run(View.java:21147)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.os.Handler.handleCallback(Handler.java:739)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.os.Handler.dispatchMessage(Handler.java:95)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.os.Looper.loop(Looper.java:148)
01-02 02:05:41.616: E/AndroidRuntime(2927): at android.app.ActivityThread.main(ActivityThread.java:5417)
01-02 02:05:41.616: E/AndroidRuntime(2927): at java.lang.reflect.Method.invoke(Native Method)
01-02 02:05:41.616: E/AndroidRuntime(2927): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
01-02 02:05:41.616: E/AndroidRuntime(2927): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
here is the mainfest file,hope help::
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.phonedb"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="23" />
<uses-permission-sdk-m android:name="android.permission.READ_CONTACTS" />
<uses-permission-sdk-m android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.phonedb.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=".AddContactActivity"
android:label="#string/title_activity_add_contact" >
</activity>
<activity
android:name="com.example.phonedb.DetailContactActivity"
android:label="#string/title_activity_detail_contact" >
</activity>
<activity
android:name=".EditActivity"
android:label="#string/title_activity_edit" >
</activity>
</application>
Switch to DIAL_PHONE, as that does not need a permission.
Just replace this line
Intent callIntent = new Intent(Intent.ACTION_CALL);
to
Intent callIntent = new Intent(Intent.ACTION_DIAL);
Android 6 (SDK 23) allows users to revoke permissions from an app. I guess, thats what happened here. Your app must be able to cope with this situation.
Have a look at the documentation for the details.
In particular:
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.
Requsting permissions at runtime is described in detail here.
Add this permission in the manifest file:
<uses-permission android:name="android.permission.CALL_PHONE"/>
or else try this too.
<uses-permission android:name="android.permission.CALL_PRIVILEGED"/>
CALL_PRIVILEGED Allows an application to call any phone number,
including emergency numbers, without going through the Dialer user
interface for the user to confirm the call being placed.
Not for use by third-party applications.
i'm late. You must request permission dynamically.
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
more details at https://developer.android.com/training/permissions/requesting.html
Please change call_phone to dial phone. As you need to dial
the number.
Intent callIntent=new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:1234567890"));
startActivity(callIntent);
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
What i am doing:: I am trying to use Myapplication class to send the data to next activity
Problem i am facing:: Having class cast exception
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
Button btn;
String TYPE_FILTER;
StringBuilder result;
MyApplication mApplication;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApplication = (MyApplication)getApplication();
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
result = new StringBuilder();
for (int i = 0; i < arraylist.size(); i++) {
if (adapter.mysparse.get(i) == true) {
result.append(arraylist.get(i).get(BLD_IndividualListOfItems_Starters.NAME));
result.append("\n");
}
}
Intent n = new Intent(BLD_IndividualListOfItems_Starters.this, ResultActivity.class);
n.putExtra("buffer", result.toString());
startActivity(n);
}
});
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(BLD_IndividualListOfItems_Starters.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
mApplication.setArrayListMapData(arraylist);
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
ResultActivity.java
public class ResultActivity extends ListActivity {
ListView lstView;
ArrayList<HashMap<String,String>> arraylist = new ArrayList<HashMap<String,String>>();
String myName;
MyApplication mApplication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for(int i=0;i<10;i++)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("key", "value"+i);
arraylist.add(map);
}
String[] from = { "key" };
int[] to = { R.id.textView1 };
SimpleAdapter adapter= new SimpleAdapter(this, arraylist,R.layout.custom_single_list, from, to);
setListAdapter(adapter);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multitabcheckboxselection"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_MainCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_SideCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Others" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Desert" />
<activity android:name="com.example.multitabcheckboxselection.ResultActivity" />
</application>
<application
android:name="com.android.app.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
</application>
</manifest>
ListViewAdapterForAtomicListItemtype.java
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements OnCheckedChangeListener {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
SparseBooleanArray mysparse;
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
mysparse = new SparseBooleanArray(data.size());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
CheckBox chk;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
chk = (CheckBox) itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);
// Capture position and set results to the TextViews
name.setText(resultp.get(BLD_IndividualListOfItems_Starters.NAME));
chk.setTag(position);
chk.setChecked(mysparse.get(position, false));
chk.setOnCheckedChangeListener(this);
return itemView;
}
public boolean isChecked(int position) {
return mysparse.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mysparse.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
mysparse.put((Integer) buttonView.getTag(), isChecked);
}
}
Log::
01-03 13:30:12.828: D/AndroidRuntime(461): Shutting down VM
01-03 13:30:12.828: W/dalvikvm(461): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-03 13:30:12.868: E/AndroidRuntime(461): FATAL EXCEPTION: main
01-03 13:30:12.868: E/AndroidRuntime(461): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters}: java.lang.ClassCastException: android.app.Application
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.os.Looper.loop(Looper.java:123)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-03 13:30:12.868: E/AndroidRuntime(461): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 13:30:12.868: E/AndroidRuntime(461): at java.lang.reflect.Method.invoke(Method.java:521)
01-03 13:30:12.868: E/AndroidRuntime(461): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-03 13:30:12.868: E/AndroidRuntime(461): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-03 13:30:12.868: E/AndroidRuntime(461): at dalvik.system.NativeStart.main(Native Method)
01-03 13:30:12.868: E/AndroidRuntime(461): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters}: java.lang.ClassCastException: android.app.Application
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2503)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:651)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.widget.TabHost.setCurrentTab(TabHost.java:323)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.widget.TabHost.addTab(TabHost.java:213)
01-03 13:30:12.868: E/AndroidRuntime(461): at com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems.onCreate(BreakfastLunchDinnerIndividualListOfItems.java:36)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-03 13:30:12.868: E/AndroidRuntime(461): ... 11 more
01-03 13:30:12.868: E/AndroidRuntime(461): Caused by: java.lang.ClassCastException: android.app.Application
01-03 13:30:12.868: E/AndroidRuntime(461): at com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters.onCreate(BLD_IndividualListOfItems_Starters.java:47)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 13:30:12.868: E/AndroidRuntime(461): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-03 13:30:12.868: E/AndroidRuntime(461): ... 20 more
01-03 13:30:15.563: I/Process(461): Sending signal. PID: 461 SIG: 9
{Edit}
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
Button btn;
String TYPE_FILTER;
StringBuilder result;
MyApplication mApplication;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApplication = (MyApplication)getApplicationContext();
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
result = new StringBuilder();
for (int i = 0; i < arraylist.size(); i++) {
if (adapter.mysparse.get(i) == true) {
result.append(arraylist.get(i).get(BLD_IndividualListOfItems_Starters.NAME));
result.append("\n");
}
}
Intent n = new Intent(BLD_IndividualListOfItems_Starters.this, ResultActivity.class);
n.putExtra("buffer", result.toString());
startActivity(n);
}
});
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(BLD_IndividualListOfItems_Starters.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
mApplication.setArrayListMapData(arraylist);
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
MyApplication.java
package com.example.multitabcheckboxselection;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Application;
public class MyApplication extends Application {
ArrayList<HashMap<String, String>> arraylist;
#Override
public void onCreate() {
super.onCreate();
}
public void setArrayListMapData(ArrayList<HashMap<String, String>> setData)
{
arraylist = setData;
}
public ArrayList<HashMap<String, String>> getArrayListMapData()
{
return arraylist;
}
}
{Edit-3}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multitabcheckboxselection"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_MainCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_SideCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Others" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Desert" />
<activity android:name="com.example.multitabcheckboxselection.ResultActivity" />
</application>
<application
android:allowBackup="true"
android:name="com.example.multitabcheckboxselection.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
</application>
</manifest>
MyApplication.java
package com.example.multitabcheckboxselection;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Application;
public class MyApplication extends Application {
ArrayList<HashMap<String, String>> arraylist;
#Override
public void onCreate() {
super.onCreate();
}
public void setArrayListMapData(ArrayList<HashMap<String, String>> setData)
{
arraylist = setData;
}
public ArrayList<HashMap<String, String>> getArrayListMapData()
{
return arraylist;
}
}
Log::
01-03 14:13:14.509: E/AndroidRuntime(681): FATAL EXCEPTION: main
01-03 14:13:14.509: E/AndroidRuntime(681): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters}: java.lang.ClassCastException: android.app.Application
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.os.Looper.loop(Looper.java:123)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-03 14:13:14.509: E/AndroidRuntime(681): at java.lang.reflect.Method.invokeNative(Native Method)
01-03 14:13:14.509: E/AndroidRuntime(681): at java.lang.reflect.Method.invoke(Method.java:521)
01-03 14:13:14.509: E/AndroidRuntime(681): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-03 14:13:14.509: E/AndroidRuntime(681): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-03 14:13:14.509: E/AndroidRuntime(681): at dalvik.system.NativeStart.main(Native Method)
01-03 14:13:14.509: E/AndroidRuntime(681): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multitabcheckboxselection/com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters}: java.lang.ClassCastException: android.app.Application
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2503)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:651)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.widget.TabHost.setCurrentTab(TabHost.java:323)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.widget.TabHost.addTab(TabHost.java:213)
01-03 14:13:14.509: E/AndroidRuntime(681): at com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems.onCreate(BreakfastLunchDinnerIndividualListOfItems.java:36)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-03 14:13:14.509: E/AndroidRuntime(681): ... 11 more
01-03 14:13:14.509: E/AndroidRuntime(681): Caused by: java.lang.ClassCastException: android.app.Application
01-03 14:13:14.509: E/AndroidRuntime(681): at com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters.onCreate(BLD_IndividualListOfItems_Starters.java:47)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-03 14:13:14.509: E/AndroidRuntime(681): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-03 14:13:14.509: E/AndroidRuntime(681): ... 20 more
Move the attribute
android:name="com.android.app.MyApplication"
to the first application element in the manifest and delete the second application element.
Btw. is your MyApplication class really in the package com.android.app?
EDIT: you use a different package, so the line should be
android:name="com.example.multitabcheckboxselection.MyApplication"
EDIT2+3: you have put it as an activity now. remove the activity, the attribute must go into the application tag.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multitabcheckboxselection"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="com.example.multitabcheckboxselection.MyApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.multitabcheckboxselection.BreakfastLunchDinnerIndividualListOfItems"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Starters" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_MainCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_SideCourse" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Others" />
<activity android:name="com.example.multitabcheckboxselection.BLD_IndividualListOfItems_Desert" />
<activity android:name="com.example.multitabcheckboxselection.ResultActivity" />
</application>
</manifest>
Normally one would do like this
class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
static public MyApplication getInstance() { return mInstance; }
static private MyApplication mInstance;
}
Then from elsewhere
MyApplication myApp = MyApplication.getInstance();
Change
mApplication = (MyApplication)getApplication();
To
mApplication = ((MyApplication) getApplicationContext());
And in Manifest.xml define android:name="MyApplication"
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="MyApplication" >
Edit
Remove this
<application
android:name="com.android.app.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
</application>
Each application will have only one <application> Tag
Change to
mApplication = (MyApplication)getApplicationContext();
Edit:
Delete the second application tag and move this to the first
android:name="com.android.app.MyApplication"
Edit:
public class MyApplication extends Application {
private static MyApplication singleton;
public MyApplication getInstance(){
return singleton;
}
public void onCreate() {
super.onCreate();
singleton = this;
}
// other methods
}
Then in Activity
mApplication = MyApplication.getInstance();
Example:
public class Main extends Activity{
ArrayList<HashMap<String,String>> arraylist = new ArrayList<HashMap<String,String>>();
MyApplication mapp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapp = MyApplication.getInstance();
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("My String from Application class is"+mapp.hello);
for(int i=0;i<10;i++)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("key", "value"+i);
arraylist.add(map);
}
mapp.setArrayListMapData(arraylist);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Main.this,MainActivity.class));
}
});
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="51dp"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
MainActivity
public class MainActivity extends ListActivity
{
ListView lstView;
ArrayList<HashMap<String,String>> arraylist;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MyApplication mApplication = MyApplication.getInstance();
Log.i("................",""+mApplication.hello);
lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
arraylist= mApplication.getArrayListMapData();
String[] from = { "key" };
int[] to = { R.id.textView1 };
SimpleAdapter adapter= new SimpleAdapter(this, arraylist,R.layout.row, from, to);
setListAdapter(adapter);
}
}
MyApplication
public class MyApplication extends Application {
ArrayList<HashMap<String, String>> arraylist;
private static MyApplication instance = null;
public String hello= "Hello global Application";
#Override
public void onCreate() {
super.onCreate();
}
public static MyApplication getInstance() {
if(instance == null) {
instance = new MyApplication();
}
return instance;
}
public void setArrayListMapData(ArrayList<HashMap<String, String>> setData)
{
arraylist = setData;
}
public ArrayList<HashMap<String, String>> getArrayListMapData()
{
return arraylist;
}
}
Manifest file
<application
android:allowBackup="true"
android:name="com.example.testlistactivity.MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.testlistactivity.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.testlistactivity.MainActivity"
android:label="#string/app_name" >
</activity>
</application>
Snap1
Snap2
I get this error when I run my program. It starts up the first page, but when it's supposed to go to .Menu it crashes:
11-04 06:01:06.039: W/dalvikvm(949): threadid=11: thread exiting with uncaught exception (group=0x414c4700)
11-04 06:01:06.057: E/AndroidRuntime(949): FATAL EXCEPTION: Thread-87
11-04 06:01:06.057: E/AndroidRuntime(949): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.secondapp.MENU }
11-04 06:01:06.057: E/AndroidRuntime(949): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1632)
11-04 06:01:06.057: E/AndroidRuntime(949): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
11-04 06:01:06.057: E/AndroidRuntime(949): at android.app.Activity.startActivityForResult(Activity.java:3390)
11-04 06:01:06.057: E/AndroidRuntime(949): at android.app.Activity.startActivityForResult(Activity.java:3351)
11-04 06:01:06.057: E/AndroidRuntime(949): at android.app.Activity.startActivity(Activity.java:3587)
11-04 06:01:06.057: E/AndroidRuntime(949): at android.app.Activity.startActivity(Activity.java:3555)
11-04 06:01:06.057: E/AndroidRuntime(949): at com.example.secondapp.Splash$1.run(Splash.java:26)
Here's my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.secondapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
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=".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=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
And here are the .java files of my .Splash activity and my .Menu activity:
Splash
package com.example.secondapp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.happyman);
ourSong.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent startMain = new Intent("com.example.secondapp.MENU");
startActivity(startMain);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Menu
package com.example.secondapp;
public class Menu extends ListActivity {
String classes[] = {"MainActivity", "example1", "example2", "example3", "example4", "example5"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
String Cheese = classes[position];
super.onListItemClick(l, v, position, id);
try{
Class ourClass = Class.forName("com.example.secondapp." + Cheese);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
in your manifest the action should match. Change it with com.example.secondapp.MENU
It is in caps MENU should be Menu
Change to
Intent startMain = new Intent("com.example.secondapp.Menu");
coz your activity is public class Menu extends ListActivity { and in manifest you have
<activity
android:name=".Menu"
Edit:
Explicit intents designate the target component by its name (the
component name field, mentioned earlier, has a value set). Since
component names would generally not be known to developers of other
applications, explicit intents are typically used for
application-internal messages — such as an activity starting a
subordinate service or launching a sister activity.
Implicit intents do not name a target (the field for the component
name is blank). Implicit intents are often used to activate
components in other applications.
So Change to explicit intent
Intent startMain = new Intent(Splash.this,Menu.class); // in Splash.java
and in manifest
<activity
android:name="com.example.secondapp.Menu"
android:label="#string/app_name" >
</activity>
For more info check the docs
http://developer.android.com/guide/components/intents-filters.html
You need to set activity class in your manifest and you misspelled MENU
replace
<activity
android:name=".Menu"
android:label="#string/app_name" >
with
<activity
android:name=".MENU"
android:label="#string/app_name" >
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" />