I've looked around on SOF and haven't been able to find anything helpful.
First off, I'll say what is happening. When I run my widget, it all works fine until I hit a checkbox on a listView item and run this coding:
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
final int DEST_IMAGE_WIDTH = 100;
final int DEST_IMAGE_HEIGHT = 100;
ApplicationInfo appInfo = mContext.getApplicationInfo();
Drawable appIcon = pm.getApplicationIcon(appInfo);
Bitmap appBmp = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888);
// Creates a new canvas based on the image specification
// created just above.
Canvas canvas = new Canvas(appBmp);
// (optional) Fills the entire canvas
canvas.drawColor(Color.WHITE);
// You need to set bounds otherwise a 0,0 sized image would be drawn.
appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT);
appIcon.draw(canvas);
/// Let's save to a .jpg file ...
File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
FileOutputStream out;
try
{
file.createNewFile();
out = mContext.getApplicationContext().openFileOutput("BitmapImage", Context.MODE_PRIVATE);
appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
Log.i("AppInfoAdapter", "the icon(s) have been saved");
out.close();
// Load back the image file to confirm it works
// Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath() );
// ImageView imageV = (ImageView)findViewById(R.id.);
// imageV.setImageBitmap(bitmap);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e2)
{
e2.printStackTrace();
}
Intent intent = new Intent (v.getContext(), GridViewAdapter.class);
v.getContext().startActivity(intent);
Log.i("AppInfoAdapter", "New intent started to send icon bitmap");
} else {
System.out.println("Un-Checked");
}
Everything works great and I even get the Log message that "New intent started to send icon bitmap". However, as soon as this is done, I get this error:
12-14 13:47:54.413: E/AndroidRuntime(1785): FATAL EXCEPTION: main
12-14 13:47:54.413: E/AndroidRuntime(1785): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.awesomefilebuilderwidget/com.example.awesomefilebuilderwidget.GridViewAdapter}: java.lang.InstantiationException: com.example.awesomefilebuilderwidget.GridViewAdapter
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1746)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1854)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.access$1500(ActivityThread.java:135)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1041)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.os.Handler.dispatchMessage(Handler.java:99)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.os.Looper.loop(Looper.java:150)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.main(ActivityThread.java:4333)
12-14 13:47:54.413: E/AndroidRuntime(1785): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 13:47:54.413: E/AndroidRuntime(1785): at java.lang.reflect.Method.invoke(Method.java:507)
12-14 13:47:54.413: E/AndroidRuntime(1785): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-14 13:47:54.413: E/AndroidRuntime(1785): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-14 13:47:54.413: E/AndroidRuntime(1785): at dalvik.system.NativeStart.main(Native Method)
12-14 13:47:54.413: E/AndroidRuntime(1785): Caused by: java.lang.InstantiationException: com.example.awesomefilebuilderwidget.GridViewAdapter
12-14 13:47:54.413: E/AndroidRuntime(1785): at java.lang.Class.newInstanceImpl(Native Method)
12-14 13:47:54.413: E/AndroidRuntime(1785): at java.lang.Class.newInstance(Class.java:1409)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.Instrumentation.newActivity(Instrumentation.java:1040)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1738)
12-14 13:47:54.413: E/AndroidRuntime(1785): ... 11 more
This is the class in question:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class GridViewAdapter extends BaseAdapter {
private Context Context;
// Keep all Images in array list
public ArrayList<Integer> drawables = new ArrayList<Integer>();
CheckBox mCheckBox=null;
// Constructor
public GridViewAdapter(Context c){
Context = c;
Log.d("GridViewAdapter", "Constructor is set");
drawables.add(R.drawable.pattern1);
Log.d("GridViewAdapter", "pattern1 added");
drawables.add(R.drawable.pattern2);
Log.d("GridViewAdapter", "pattern2 added");
drawables.add(R.drawable.trashcan);
Log.d("GridViewAdapter", "trashcan added");
drawables.add(R.drawable.ic_launcher);
Log.d("GridViewAdapter", "ic_launcher added");
}
public void setCheckBox(CheckBox checkbox){
mCheckBox=checkbox;
}
#Override
// How many items are in the data set represented by this Adapter
public int getCount() {
return drawables.size();
}
#Override
// Get the data item associated with the specified position in the
// data set
public Object getItem(int position) {
return drawables.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public boolean isSdReadable() {
boolean mExternalStorageAvailable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = true;
Log.i("isSdReadable", "External storage card is readable.");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.i("isSdReadable", "External storage card is readable.");
mExternalStorageAvailable = true;
} else {
// Something else is wrong. It may be one of many other
// states, but all we need to know is we can neither read nor write
mExternalStorageAvailable = false;
}
return mExternalStorageAvailable;
}
public Bitmap getThumbnail() {
final String APP_PATH_SD_CARD = "/TEST/";
final String APP_THUMBNAIL_PATH_SD_CARD = "thumbnails";
String filename = "AFBWIcon.png";
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD + APP_THUMBNAIL_PATH_SD_CARD;
Bitmap thumbnail = null;
// Look for the file on the external storage
try {
if (isSdReadable() == true) {
thumbnail = BitmapFactory.decodeFile(fullPath + "/" + filename);
}
} catch (Exception e) {
Log.e("getThumbnail() on external storage", e.getMessage());
}
// If no file on external storage, look in internal storage
if (thumbnail == null) {
try {
File filePath = Context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
}
return thumbnail;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked == true){
isSdReadable();
try {
Log.i("GridViewAdapter", "checkbox is checked");
FileInputStream in = Context.openFileInput("BitmapImage");
// Load back the image file to confirm it works
Bitmap bitmap = BitmapFactory.decodeStream(in);
view.setImageBitmap(bitmap);
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// getThumbnail();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e("GridView", "Icons not for use/checkbox not checked");
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
}
Also, this is my Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.awesomefilebuilderwidget"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="com.example.awesomefilebuilderwidget.AFBWidget" android:label="#string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="#xml/widget_stuff"/>
</receiver>
<activity android:name="com.example.awesomefilebuilderwidget.WidgetConfig" android:label="#string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
<activity android:name="com.example.awesomefilebuilderwidget.Drag_and_Drop_App" android:label="#string/app_name" android:windowSoftInputMode="stateHidden" android:screenOrientation="portrait"></activity>
<activity android:name="com.example.awesomefilebuilderwidget.AppInfoAdapter" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.Feedback" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.GridView" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.SendMessageActivity" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.Utilities" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.Personalize" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.SwipeDetector" android:label="#string/app_name"></activity>
<activity android:name="com.example.awesomefilebuilderwidget.GridViewAdapter" android:label="#string/app_name"></activity>/
</application>
</manifest>
I was told that since it is an adapter, not an activity, I should remove it from my Manifest. But, when I do this, I get this error:
12-14 12:57:04.047: E/AndroidRuntime(708): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.awesomefilebuilderwidget/com.example.awesomefilebuilderwidget.GridViewAdapter}; have you declared this activity in your AndroidManifest.xml?
It seems as though I am stuck between the choice of having the class or not.
I haven't had this issue up until now and I have tried cleaning my project.
Please help!
I was told that since it is an adapter, not an activity, I should remove it from my Manifest.
Correct.
But, when I do this, I get this error:
That would be because in your code shown above, you are calling startActivity() incorrectly, trying to start GridViewAdapter as an activity. GridViewAdapter is not an activity. If you want to start an activity, write an activity, add it to the manifest, and then call startActivity() for your newly-written activity.
You can learn more about activities in the documentation.
Related
I tried to share an image loaded into the imageview from glide following this guide, it gives me a illegal argument exception. I've posted the code and stacktrace below, it
MainAcitvity.xml
public class MainActivity extends AppCompatActivity {
private EditText editText;
private ShareActionProvider myShareActionProvider;
//private Bitmap bitmap;
private Uri uri;
private Intent shareIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
String hi = "http://37n98a43dqtb4bua9n28nidp.wpengine.netdna-cdn.com/wp-content/uploads/2016/09/MyFriendPikachu.jpg";
Glide
.with(this)
.load(hi)
.listener(new RequestListener<String, GlideDrawable>() {
#Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
prepareShareIntent(((GlideBitmapDrawable) resource).getBitmap());
attachShareIntentAction();
return false;
}
})
.placeholder(R.drawable.ic_action_name)
.error(R.drawable.ic_img_error)
.centerCrop()
.into(imageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.img_menu, menu);
MenuItem item = menu.findItem(R.id.action_share);
myShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
attachShareIntentAction();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public void prepareShareIntent(Bitmap drawableImage) {
Uri bmpUri = getBitmapFromDrawable(drawableImage);
shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
}
public void attachShareIntentAction() {
if (myShareActionProvider != null && shareIntent != null)
myShareActionProvider.setShareIntent(shareIntent);
}
public Uri getBitmapFromDrawable(Bitmap bmp) {
Uri bmpUri = null;
try {
//also tried getExternalDir(Environment.DIRECTORY_PICTURES)
File file = new File(Environment.getExternalStorageDirectory(), "images" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = FileProvider.getUriForFile(MainActivity.this, "com.example.imnobody.sampleprojectnetwork.fileprovider", file); // use this version for API >= 24
// **Note:** For API < 24, you may use bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
}
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.imnobody.sampleprojectnetwork">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.imnobody.sampleprojectnetwork.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/fileprovider" />
</provider>
</application>
</manifest>
fileprovider.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-file-path
name="images"
path="Pictures" />
</paths>
Stacktrace
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/sdcard0/images1502651207040.png
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
at com.example.imnobody.sampleprojectnetwork.MainActivity.getBitmapFromDrawable(MainActivity.java:134)
at com.example.imnobody.sampleprojectnetwork.MainActivity.prepareShareIntent(MainActivity.java:95)
at com.example.imnobody.sampleprojectnetwork.MainActivity$1.onResourceReady(MainActivity.java:59)
at com.example.imnobody.sampleprojectnetwork.MainActivity$1.onResourceReady(MainActivity.java:51)
at com.bumptech.glide.request.GenericRequest.onResourceReady(GenericRequest.java:522)
at com.bumptech.glide.request.GenericRequest.onResourceReady(GenericRequest.java:507)
at com.bumptech.glide.load.engine.EngineJob.handleResultOnMainThread(EngineJob.java:158)
at com.bumptech.glide.load.engine.EngineJob.access$100(EngineJob.java:22)
at com.bumptech.glide.load.engine.EngineJob$MainThreadCallback.handleMessage(EngineJob.java:202)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeS
First, in your metadata, change external-file-path to external-files-path, adding the missing s.
Second, /storage/sdcard0/images1502651207040.png will not match that repaired metadata. The metadata is expecting you to be using getExternalFilesDir(), and specifically a Pictures directory under there. Your path does not resemble that.
According to the documentation:
<external-path name="name" path="path" />
Represents files in the root
of the external storage area. The root path of this subdirectory is
the same as the value returned
byEnvironment.getExternalStorageDirectory().
You are calling a reference from your external storage root (/storage/sdcard0) but you need to reference your package root at /storage/sdcard0/Android/data/your.package.name/Pictures instead.
I am having a problem with my Android Flashlight App. The app crashes when I try to press the home button of the device while the app is opened then resuming (by clicking the app icon on home screen not recent apps button). After I terminate the app from the recent apps list then opening again, it does not crash anymore using the same instructions above.
Please see code below.
public class MainActivity extends Settings {
public Camera camera;
public Camera.Parameters parameters;
public ImageButton flashLightButton;
boolean isFlashLightOn = false;
MediaPlayer mySound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flashLightButton = (ImageButton)findViewById(R.id.flashlight_button);
flashLightButton.setOnClickListener(new FlashOnOffListener());
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
mySound = MediaPlayer.create(this, R.raw.balloon_snap);
if (isFlashSupported()) {
camera = Camera.open();
parameters = camera.getParameters();
} else {
showNoFlashAlert();
}
Settings.active = false;
//super.onCreate(savedInstanceState);
//Set layout we created
//setContentView(R.layout.activity_main);
//Register the receiver which triggers event
//when battery charge is changed
}
public void settings(View view)
{
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
this.finish();
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
//When Event is published, onReceive method is called
public void onReceive(Context c, Intent i) {
//Get Battery %
int level = i.getIntExtra("level", 0);
//Find the progressbar creating in main.xml
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
//Set progress level with battery % value
pb.setProgress(level);
//Find textview control created in main.xml
TextView tv = (TextView) findViewById(R.id.textfield);
//Set TextView with text
tv.setText("" + Integer.toString(level) + "");
}
};
public class FlashOnOffListener implements View.OnClickListener{
SharedPreferences sharedPrefs = getSharedPreferences("VibrateSettings", MODE_PRIVATE);
Boolean vibration = sharedPrefs.getBoolean("VibrateSet", false);
SharedPreferences sharedPrefs2 = getSharedPreferences("SoundSettings", MODE_PRIVATE);
Boolean sound = sharedPrefs2.getBoolean("SoundSet", false);
#Override
public void onClick(View v) {
if(isFlashLightOn){
flashLightButton.setImageResource(R.drawable.flashlight_off);
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
isFlashLightOn = false;
if(vibration == true){
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(20);
}
else {
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(00);
}
if (sound == true){
mySound.start();
}
}else{
flashLightButton.setImageResource(R.drawable.flashlight_on);
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isFlashLightOn = true;
if(vibration == true){
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(20);
}
else {
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(00);
}
if (sound == true){
mySound.start();
}
}
}
}
private void showNoFlashAlert() {
new AlertDialog.Builder(this)
.setMessage("Your device hardware does not support flashlight!")
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("Error")
.setPositiveButton("Ok", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}).show();
}
private boolean isFlashSupported() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
#Override
protected void onDestroy() {
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
super.onDestroy();
}}
AndroidManifest.xml
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.BATTERY_STATS"/>
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/btn_switch_on"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Settings"
android:label="#string/app_name">
</activity>
</application>
logcat
E/AndroidRuntime(22941): FATAL EXCEPTION: main
E/AndroidRuntime(22941): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.johncarlo.flashlight/com.example.johncarlo.flashlight.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
E/AndroidRuntime(22941): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
E/AndroidRuntime(22941): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
E/AndroidRuntime(22941): at android.app.ActivityThread.access$600(ActivityThread.java:145)
E/AndroidRuntime(22941): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
E/AndroidRuntime(22941): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(22941): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(22941): at android.app.ActivityThread.main(ActivityThread.java:5099)
E/AndroidRuntime(22941): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(22941): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(22941): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
E/AndroidRuntime(22941): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
E/AndroidRuntime(22941): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(22941): Caused by: java.lang.RuntimeException: Fail to connect to camera service
E/AndroidRuntime(22941): at android.hardware.Camera.native_setup(Native Method)
E/AndroidRuntime(22941): at android.hardware.Camera.<init>(Camera.java:365)
E/AndroidRuntime(22941): at android.hardware.Camera.open(Camera.java:338)
E/AndroidRuntime(22941): at com.example.johncarlo.flashlight.MainActivity.onCreate(MainActivity.java:49)
E/AndroidRuntime(22941): at android.app.Activity.performCreate(Activity.java:5117)
E/AndroidRuntime(22941): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
E/AndroidRuntime(22941): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
E/AndroidRuntime(22941): ... 11 more
W/ActivityManager( 786): Force finishing activity com.example.johncarlo.flashlight/.MainActivity
Remove below line from onCreate and write it in onResume and it might not crash after doing so.
#Override
protected void onResume() {
super.onResume();
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
I have two issues
1) Annotation not work
2) I want read online pdf document
I build MuPDF using this link
http://mupdf.com/doc/how-to-build-mupdf-for-android
1) I get project mupdf/platform/android
I run that default app annotation working fine but i create that project to library file they asking want to save but annotation not save.
2) It will read local file but i want read online file also. my android code
pdf = (TextView) findViewById(R.id.pdf);
onPdf = (TextView) findViewById(R.id.onPdf);
pdf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Uri uri = Uri.parse(path);
Intent intent = new Intent(context, MuPDFActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
});
onPdf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Uri uri = Uri.parse(netPath);
Intent intent = new Intent(context, MuPDFActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
});
Modified MuPDFActivity - I change all file are open openBuffer method
private MuPDFCore openBuffer(byte buffer[]) {
System.out.println("Trying to open byte buffer");
try {
String magic = "";
core = new MuPDFCore(this, buffer, magic);
// New file: drop the old outline data
OutlineActivityData.set(null);
} catch (Exception e) {
System.out.println(e);
return null;
}
return core;
}
My mainfest
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".PdfTestActivity"
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.artifex.mupdfdemo.MuPDFActivity"
android:label="#string/app_name"
android:theme="#style/AppBaseTheme" >
</activity>
<activity
android:name="com.artifex.mupdfdemo.OutlineActivity"
android:label="#string/outline_title"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
<activity
android:name="com.artifex.mupdfdemo.PrintDialogActivity"
android:label="#string/print"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
</activity>
</application>
My stacktrace
12-25 19:02:41.544: E/TAG(22925): /sample.pdf: open failed: ENOENT (No such file or directory)
12-25 19:02:41.544: E/tag(22925): file
12-25 19:02:41.546: I/System.out(22925): Trying to open /sample.pdf
12-25 19:02:41.549: D/dalvikvm(22925): Trying to load lib /mnt/asec/com.example.testnew-1/lib/libmupdf.so 0x41792e10
12-25 19:02:41.576: D/dalvikvm(22925): Added shared lib /mnt/asec/com.example.testnew-1/lib/libmupdf.so 0x41792e10
12-25 19:02:41.576: D/dalvikvm(22925): No JNI_OnLoad found in /mnt/asec/com.example.testnew-1/lib/libmupdf.so 0x41792e10, skipping init
12-25 19:02:41.577: I/libmupdf(22925): Opening document...
12-25 19:02:41.577: E/libmupdf(22925): error: cannot open /sample.pdf: No such file or directory
12-25 19:02:41.577: E/libmupdf(22925): error: cannot load document '/sample.pdf'
12-25 19:02:41.577: E/libmupdf(22925): error: Cannot open document: '/sample.pdf'
12-25 19:02:41.577: E/libmupdf(22925): Failed: Cannot open document: '/sample.pdf'
12-25 19:02:41.580: I/System.out(22925): java.lang.Exception: Cannot open file: /sample.pdf
I download PDF file and convert to Bytes and open in MuPDF Core.
Download file
byte buffer[] = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) urls[0].openConnection();
urlConnection.setReadTimeout(TIMEOUT_READ);
InputStream inputStream = urlConnection.getInputStream();
int len = inputStream.available();
buffer = new byte[len];
// inputStream.read(buffer, 0, len);
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
Log.e("Length", "" + byteBuffer.size());
inputStream.close();
// and then we can return your byte array.
} catch (Exception e) {
e.printStackTrace();
});
Open core
RelativeLayout mupdfWrapper;
MuPDFCore core;
public byte[] buffer;
mupdfWrapper = (RelativeLayout) viewRoot
.findViewById(R.id.mupdf_wrapper);
// Intent intent =new Intent(getActivity(),MuPDFActivity.class);
// startActivity(intent);
core = new MuPDFCore(getActivity(), buffer, "");
MuPDFReaderView mDocView = new MuPDFReaderView(getActivity());
mDocView.setAdapter(new MuPDFPageAdapter(getActivity(), core));
mupdfWrapper.addView(mDocView, new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
MANIFEST:(partial view)
MainActivity, program immediately terminates and issues the messages in the Log.
It should have started showing the buttons to select options to continue execution.
After days of researching this forum, I found postings that suggest to place the BackupDb inside the application in the Manifest.
After doing that, I ended up with the message in the log.
Having exhausted my research venues, I'd like to know what could be the problem and how to solve it.
MANIFEST:(partial view)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.peter.databasetest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<supports-screens
android:xlargeScreens="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="false"
/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
**android:name="com.peter.databasetest.BackupDB">**
<activity
android:name="com.peter.databasetest.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=".CheckDatabase"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CHECKDATABASE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".CheckSDcard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CHECKSDCARD" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.peter.databasetest.Insert"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.peter.databasetest.INSERT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity: Calls checkSDcard and CheckDatabase. Checks if there is SDCard present and the database in main, exists.
public class MainActivity extends Activity implements OnClickListener {
DBAdapter db;
Button insertButton; //ADD A NEW RECORD
Button listAllButton; //LIST ALL
Button cancelButton; //CANCEL PGM
Button backupDbButton; //REQUEST BACKUP DB TO SDCARD
Button restoreButton; //RESTORE DB FROM SDCARD TO MAIN
Button memsizeButton; //SHOW MEMORY SIZES ON DEVICE
int retcode;
int chk;
String message;
public Context context;
public static final String NO_DB ="Database does not exist. Backup is not possible";
public static final String DB_PB ="ERROR- Check log";
public static final String UNWR_SDCARD ="Your SDCard must be set to writable. Check the card lock";
public static final String NO_SDCARD ="No SDcard detected. No backup is possible";
public static final String BKP_OK = "Backup was SUCCESSFUL.";
public static final String BKP_NOK = "Backup FAILED. ";
static final int SD_CHECK = 1;
static final int DB_CHECK = 2;
static final int BK_CHECK = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insertButton = (Button) findViewById(R.id.insertButton);
listAllButton = (Button) findViewById(R.id.listAllButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
backupDbButton = (Button) findViewById(R.id.backupDbButton);
restoreButton = (Button) findViewById(R.id.restoreButton);
memsizeButton = (Button) findViewById(R.id. memsizeButton);
insertButton.setOnClickListener(this); //insert record into DB
listAllButton.setOnClickListener(this); //list ALL records from DB
cancelButton.setOnClickListener(this); //cancel the program
backupDbButton.setOnClickListener(this); //request backup to sdcard
restoreButton.setOnClickListener(this); //request restore from sdcard
memsizeButton.setOnClickListener(this); //Get Meory sizes
public void onClick(View v ) {
if (v == insertButton) {
startActivity(new Intent(getApplicationContext(), Insert.class));
}else if (v == listAllButton){
startActivity (new Intent(MainActivity.this, ListDr.class));
}else if (v == backupDbButton){
**Intent checksd = new Intent(this,CheckSDcard.class);**
**startActivityForResult(checksd, SD_CHECK);**
}else if (v == restoreButton) {
startActivity (new Intent(MainActivity.this,RestoreDB.class));
}else if (v == memsizeButton) {
startActivity (new Intent(MainActivity.this,GetMemorySizes.class));
}else if (v == cancelButton){
finish();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SD_CHECK && resultCode == RESULT_OK) {
Intent checkdb = new Intent(MainActivity.this,CheckDatabase.class);
startActivityForResult(checkdb, DB_CHECK);
}else if (requestCode == DB_CHECK && resultCode == RESULT_OK){
**Intent backup = new Intent(MainActivity.this,BackupDB.class);**
**startActivityForResult(backup, BK_CHECK);**
}else if (requestCode == BK_CHECK && resultCode == RESULT_OK){
message = BKP_OK;
SendMessageDialog(message);
finish();
}
if(resultCode == RESULT_CANCELED && resultCode == -1){
message = NO_DB;
SendMessageDialog(message);
finish();
}else if(resultCode == RESULT_CANCELED && resultCode == -2) {
message = DB_PB;
SendMessageDialog(message);
finish();
}
}
BackupDb: Copies the database to the SDCARD.
package com.peter.databasetest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import com.peter.databasetest.DBAdapter;
public class BackupDB extends AsyncTask<Void, Void, Integer> {
DBAdapter db;
intrc= -10;
intretcode;
intchk;
Stringmessage;
String mypackage;
public Context context;
public static String FOLDER_NAME = "DBfolder";
public static final String DATABASE_NAME = "UserDB.db";
public static final String DATABASE_BACKUP= "UserDB.db";
public static final String BKP_OK = "Backup was SUCCESSFUL.";
public static final String BKP_NOK = "Backup FAILED. ";
#Override
protected void onPreExecute() {
// GET PACKAGE NAME
mypackage = context.getApplicationContext().getPackageName() ;
}
// START BACKUP TO SDCARD
#Override
protected Integer doInBackground(Void... params) {
// DOING BACKUP
Log.i("00000" , "STARTING BACKUP...BACKUP ");
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
CREATE A FOLDER /mnt/sdcard<packagename>FOLDER_NAME if it does not exist
File folder = new File(Environment.getExternalStorageDirectory()
+ "/"
+ mypackage
+ "/"
+ FOLDER_NAME);
if(!folder.exists()) {
if (folder.mkdirs()) ;
}
// GET THE PATH OF THE BACKUP ON THE SDCARD
FilefileBackupDir = new File(Environment.getExternalStorageDirectory()
+ "/"
+mypackage
+ "/"
+ FOLDER_NAME
+"/"
+ DATABASE_BACKUP) ;
// IF WE HAVE A BACKUP ON SDCARD, DELETE IT TO MAKE ROOM FOR THE NEW BACKUP
if (fileBackupDir.exists()) {
fileBackupDir.delete();
}else {
* DO NOTHING */
}
// GET CURRENT DB PATH FOR THE COPY
String currentDBPath = "/data/" + mypackage + "/databases/"+ DATABASE_NAME;
// GET CURRENT DB PATH FOR THE BACKUP
String backupDBPath = "/" + mypackage + "/" +FOLDER_NAME + "/" + DATABASE_BACKUP;
FilecurrDB = new File(data, currentDBPath) ;
FilebkpDB = new File(sd, backupDBPath);
FileChannel from = null;
try {
from = new FileInputStream(currDB).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileChannel to = null;
try {
to = new FileOutputStream(bkpDB).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
to.transferFrom(from, 0, from.size());
} catch (IOException e) {
e.printStackTrace();
}
try {
from.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
to.close();
} catch (IOException e) {
e.printStackTrace();
}
retcode = 0;
returnretcode;
// end DoInBackgroung
protectedvoid onPostExecute(Integer retcode, String message) {
if(retcode == 0) {
message = BKP_OK;
SendMessageDialog(message);
}else {
message = BKP_NOK;
SendMessageDialog(message);
}
}
public void SendMessageDialog(String message) {
if (message == BKP_OK ) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Database")
.setMessage(message) // Title of the dialog
.setCancelable(true) // Does allow the use of Back Button on the hardware
.setIcon(R.drawable.ecg)// da picture
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Database")
.setMessage(message) // Title of the dialog
.setCancelable(true) // Does allow the use of Back Button on the hardware
.setIcon(R.drawable.bad)// da picture
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
}
Logcat:
02-12 07:36:06.015: E/AndroidRuntime(987): FATAL EXCEPTION: main
02-12 07:36:06.015: E/AndroidRuntime(987): java.lang.RuntimeException: Unable to instantiate application com.peter.databasetest.BackupDB:
: com.peter.databasetest.BackupDB cannot be cast to android.app.Application
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.LoadedApk.makeApplication(LoadedApk.java:501)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4124)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.access$1300(ActivityThread.java:130)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1255)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.os.Looper.loop(Looper.java:137)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 07:36:06.015: E/AndroidRuntime(987): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 07:36:06.015: E/AndroidRuntime(987): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 07:36:06.015: E/AndroidRuntime(987): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 07:36:06.015: E/AndroidRuntime(987): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 07:36:06.015: E/AndroidRuntime(987): at dalvik.system.NativeStart.main(Native Method)
02-12 07:36:06.015: E/AndroidRuntime(987): Caused by: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Application
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.Instrumentation.newApplication(Instrumentation.java:982)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.Instrumentation.newApplication(Instrumentation.java:967)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
02-12 07:36:06.015: E/AndroidRuntime(987): ... 11 more
Comment:
I removed the BackupDb from the application and reinstated it as activity.
<activity
android:name=".BackupDB"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.peter.databasetest.BACKUPDB" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
The program now brings up the buttons as expected, but when trying the backup I still get the same message as in the earlier log. (Catch-22?)
Most current log:
02-12 13:00:16.569: W/dalvikvm(30656): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
02-12 13:00:16.650: E/AndroidRuntime(30656): FATAL EXCEPTION: main
02-12 13:00:16.650: E/AndroidRuntime(30656): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.peter.databasetest/com.peter.databasetest.BackupDB}: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Activity
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.os.Looper.loop(Looper.java:137)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 13:00:16.650: E/AndroidRuntime(30656): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 13:00:16.650: E/AndroidRuntime(30656): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 13:00:16.650: E/AndroidRuntime(30656): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 13:00:16.650: E/AndroidRuntime(30656): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 13:00:16.650: E/AndroidRuntime(30656): at dalvik.system.NativeStart.main(Native Method)
02-12 13:00:16.650: E/AndroidRuntime(30656): Caused by: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Activity
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
02-12 13:00:16.650: E/AndroidRuntime(30656): ... 11 more
>Question:
>Is there any known limitation calling an AsyncTask by way of startActivityForResult?
>Could this be a factor?
The problem is in the Manifest file, you are setting your application:name to be te BackupDB class and this class is only an AsyncTask not an Application.
As can be seen on the explanation of "android:name":
An optional name of a class implementing the overall
android.app.Application for this package. [string]
Thing is my application used to run PERFECTLY but then i wanted to change packages names and classes names so i created another project and copy pasted my code and did the changes there. no error in eclipse but app crashes now !! here's whats my app is about:
public class LocationMobileUser implements LocationListener {
Context gContext;
boolean gps_enabled=false;
boolean network_enabled=false;
public LocationMobileUser(Context gContext){
this.gContext = gContext;
}
public static final String URL =
"http://www.ip2phrase.com/ip2phrase.asp?template=%20%3CISP%3E";
public void XML (View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
public class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
public String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
int x =1;
try {
InputStream stream = getHttpConnection(url);
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(stream));
String line = "";
int lineNo;
for (lineNo = 1; lineNo < 90; lineNo++) {
if (lineNo == x) {
line = lnr.readLine();
//output.append(line);
Pattern p = Pattern.compile(">(.*?)<");
Matcher m = p.matcher(line);
if (m.find()) {
output.append(m.group(1)); // => "isp"
}
} else
lnr.readLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
public InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
public String getSimOperator() {
TelephonyManager telephonyManager = (TelephonyManager)gContext.getSystemService(Context.TELEPHONY_SERVICE);
String operator = telephonyManager.getSimOperatorName();
return operator;
}
public GsmCellLocation getCellLocation() {
//String Context=Context.Telephony_SERVICE;
TelephonyManager telephonyManager = (TelephonyManager)gContext.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation CellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
return CellLocation;
}
public Location getLocation(){
String provider = null;
LocationManager locationManager;
Location gps_loc=null;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)gContext.getSystemService(context);
gps_loc=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
if(gps_enabled && gps_loc != null){
provider = LocationManager.GPS_PROVIDER;
}
else{
provider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
return location;
}
public String getProvider(Location location){
String provider = null;
LocationManager locationManager;
Location gps_loc=null;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)gContext.getSystemService(context);
gps_loc=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
if(gps_enabled && gps_loc != null ){
provider = LocationManager.GPS_PROVIDER;
}
else{
provider = LocationManager.NETWORK_PROVIDER;
}
return provider;
}
public String CellLacLocation(GsmCellLocation CellLocation){
String cidlacString;
if (CellLocation != null) {
int cid = CellLocation.getCid();
int lac = CellLocation.getLac();
cidlacString = "CellID:" + cid + "\nLAC:" + lac;}
else {
cidlacString="No Cell Location Available";
}
return cidlacString;
}
public String updateWithNewLocation(Location location) {
String latLongString;
if (location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Latitude:" + lat + "\nLongitude:" + lng;
}else{
latLongString = "No Location available";
}
return latLongString;
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
this app will be exported into a JAR file and then included into another app as a library using build path; and here's what i wrote in this new app:
public class LocationTheApp extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationMobileUser LMU = new LocationMobileUser (this);
Location location = LMU.getLocation();
GsmCellLocation CellLocation = LMU.getCellLocation();
String URL = LocationMobileUser.URL;
LocationMobileUser.GetXMLTask xmlp = LMU.new GetXMLTask();
String Provider = LMU.getProvider(location);
String isp = xmlp.getOutputFromUrl(URL);
String latLongString = LMU.updateWithNewLocation(location);
String cidlacString = LMU.CellLacLocation(CellLocation);
String operator = LMU.getSimOperator();
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
myLocationText.setText("Your current GPS position is:\n" + latLongString);
TextView myprovider = (TextView)findViewById(R.id.myprovider);
myprovider.setText("\nYour GPS position is provided by:\n" + Provider);
TextView myCellLocation = (TextView)findViewById(R.id.mycelllocation);
myCellLocation.setText("\nYour current Cell position is:\n" + cidlacString);
TextView myOperator = (TextView)findViewById(R.id.myoperator);
myOperator.setText("\nYour GSM operator is:\n" + operator);
TextView myispText = (TextView)findViewById(R.id.myispText);
myispText.setText("\nYour current ISP is:\n" + isp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Code contains no errors !!
if its any use here's my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationmobileuser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.locationtheapp.LocationTheApp"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Tried to toggle the package name in the Manifest between locationmobileuser and locationtheapp but still app crashes !!
As i said used to work like a charm in my previous projects !!
LOG:
06-18 05:36:54.502: E/Trace(992): error opening trace file: No such file or directory (2)
06-18 05:36:54.852: D/dalvikvm(992): newInstance failed: no <init>()
06-18 05:36:54.862: D/AndroidRuntime(992): Shutting down VM
06-18 05:36:54.862: W/dalvikvm(992): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-18 05:36:55.002: E/AndroidRuntime(992): FATAL EXCEPTION: main
06-18 05:36:55.002: E/AndroidRuntime(992): java.lang.RuntimeException: Unable toinstantiate activity ComponentInfo{com.example.locationmobileuser/com.example.locationmobileuser.LocationMobileUser}: java.lang.InstantiationException: can't instantiate class com.example.locationmobileuser.LocationMobileUser; no empty constructor
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.os.Looper.loop(Looper.java:137)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.reflect.Method.invokeNative(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.reflect.Method.invoke(Method.java:511)
06-18 05:36:55.002: E/AndroidRuntime(992): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-18 05:36:55.002: E/AndroidRuntime(992): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-18 05:36:55.002: E/AndroidRuntime(992): at dalvik.system.NativeStart.main(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): Caused by: java.lang.InstantiationException: can't instantiate class com.example.locationmobileuser.LocationMobileUser; no empty constructor
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.Class.newInstanceImpl(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.Class.newInstance(Class.java:1319)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
06-18 05:36:55.002: E/AndroidRuntime(992): ... 11 more
Any help would be really appreciated !!
see the package name of menifest
package="com.example.locationmobileuser
and activity package name both should be same change this package
<activity
android:name="com.example.locationtheapp.LocationTheApp"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
you need to add empty constructor in your locationmobileuser class.
public LocationMobileUser(){
}
don't need to do all these things , just go to old project and right click on the project ->> refactor to rename project name or package name