I don't know why my android app keep crashing - java

I am building a voice recognition app that does something when I say a specific word such as "open" and it opens something etc. but the problem is that my app keep crashing when I run it on my phone (real device) and I tap the speak button. I don't know what else to do? I tried giving it internet and voice recognition permission but it still doesn't help
here is the code in java (android studio)
public class MainActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private TextView resultText;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakButton = (Button) findViewById(R.id.SpeakButton);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
startVoiceRecognitionActivity();
}
});
}
void startVoiceRecognitionActivity(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult (int requestCode,int resultCode, Intent data){
String wordStr = null;
String[] words = null;
String firstWord = null;
String secondWord = null;
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK)
{
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
wordStr = matches.get(0);
words = wordStr.split(" ");
firstWord = words[0];
secondWord = words[1];
}
if (firstWord.equals("open"))
{
resultText = (TextView)findViewById(R.id.ResultText);
resultText.setText("Results: Open Command Works");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.starlinginteractivesoftworks.musiccompanion">
<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">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I look at the log and it said:
08-07 20:12:57.813 14350-14350/? E/BoostFramework: BoostFramework() :
Exception_1 = java.lang.ClassNotFoundException: Didn't find class
"com.qualcomm.qti.Performance" on path:
DexPathList[[],nativeLibraryDirectories=[/system/lib64,
/vendor/lib64]] 08-07 20:12:58.509
14350-14350/com.starlinginteractivesoftworks.musiccompanion
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.starlinginteractivesoftworks.musiccompanion, PID: 14350
android.content.ActivityNotFoundException: No Activity found to handle
Intent { act=android.speech.action.RECOGNIZE_SPEECH
launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } (has
extras) }
at
android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1839)
at
android.app.Instrumentation.execStartActivity(Instrumentation.java:1531)
at android.app.Activity.startActivityForResult(Activity.java:4399)
at android.app.Activity.startActivityForResult(Activity.java:4358)
at
com.starlinginteractivesoftworks.musiccompanion.MainActivity.startVoiceRecognitionActivity(MainActivity.java:55)
at
com.starlinginteractivesoftworks.musiccompanion.MainActivity$1.onClick(MainActivity.java:43)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

The boost framework log is just a warning, no worry about it. The real problem is the
ActivityNotFoundException: No Activity found to handle Intent
It can come from:
a poor connectivity
the voice app is missing on your phone
Possible solutions
Ensure you have a recognition app installed (see ActivityNotFoundException: No Activity found to handle Intent (RECOGNIZE_SPEECH) for more details).
Try to enable offline mode as explained here:
On your device go to Settings -> Language and Input. Click on icon on Google voice input.
Under ALL tab select the language you want to download.
Once the language package downloaded, you can see it under INSTALLED tab.
Workarounds
Catch the exception and open a webview to download a recognition app:
try{
...
}
catch(ActivityNotFoundException e) {
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://market.android.com/details?id=APP_PACKAGE_NAME"));
startActivity(i);
}
Check that a recognition app is available before the startActivity (see https://stackoverflow.com/a/35290037/2667536):
PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0) {
//Then there is application can handle your intent
}else{
//No Application can handle your intent
}

Related

UsbDevice requestPermission is denied without showing the request dialog prompt

I'm trying to use usb camera devices connected to my android device. So initially i have got the details of the usb devices connected through UsbManager.getDeviceList() method. Then i iterated through every device and requested for permission if permission was already not granted.
Prior to requesting the permission i have registered a global BroadCastReceiver to listen to the response of the requested permission.
Here is the MainActivity.java:
public class MainActivity extends AppCompatActivity {
private UsbManager usbManager_;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
public PendingIntent permissionIntent;
private static String TAG = "testing";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// SurroundView surroundView = new SurroundView(this);
// setContentView(surroundView);
usbManager_ = (UsbManager) getSystemService(USB_SERVICE);
permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
requestUsbPermissions();
}
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "received intent by broadcast " + intent.getAction());
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
Log.i(TAG, "got the permission");
}
} else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
public void requestUsbPermissions(){
HashMap<String, UsbDevice> deviceList = usbManager_.getDeviceList();
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
this.registerReceiver(usbReceiver, filter);
Log.i(TAG, "registered broadcast receiver!");
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
Log.i(TAG,
"Camera: device Id " + device.getDeviceId() + " device mName : " + device.getDeviceName());
if (!usbManager_.hasPermission(device)) {
Log.i(TAG, "requesting permission");
usbManager_.requestPermission(device, permissionIntent);
}
}
}
}
So when i run the app it detects one usb device connected and requests permission for the same. But the dialog box which asks for user input never comes. Instead when the intent is received by the BroadCastReceiver the value of intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) will always be false which means the permission is already denied. Can anyone explain to me why the dialog box is not coming in the first place and why the permission is denied automatically.
Here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vision_sdk_testing">
<uses-feature android:name="android.hardware.usb.host" android:required="true"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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>
</application>
</manifest>
And below is the output log:
2020-05-01 17:56:05.282 30769-30769/com.example.vision_sdk_testing I/testing: registered broadcast receiver!
2020-05-01 17:56:05.283 30769-30769/com.example.vision_sdk_testing I/testing: Camera: device Id 1003 device mName : /dev/bus/usb/001/003
2020-05-01 17:56:05.283 30769-30769/com.example.vision_sdk_testing I/testing: requesting permission
2020-05-01 17:56:05.301 30769-30769/com.example.vision_sdk_testing I/testing: received intent by broadcast com.android.example.USB_PERMISSION
2020-05-01 17:56:05.302 30769-30769/com.example.vision_sdk_testing D/testing: permission denied for device UsbDevice[mName=/dev/bus/usb/001/003,mVendorId=1443,mProductId=38192,mClass=239,mSubclass=2,mProtocol=1,mManufacturerName=Sonix Technology Co., Ltd.,mProductName=USB 2.0 Camera,mVersion=1.00,mSerialNumberReader=android.hardware.usb.IUsbSerialReader$Stub$Proxy#d41ebfa,mConfigurations=[
UsbConfiguration[mId=1,mName=null,mAttributes=128,mMaxPower=128,mInterfaces=[
UsbInterface[mId=0,mAlternateSetting=0,mName=HD USB Camera,mClass=14,mSubclass=1,mProtocol=0,mEndpoints=[]]
UsbConfiguration[mId=3,mName=null,mAttributes=3,mMaxPower=88,mInterfaces=[]]
Any help is appreciated. Thanks!
For me, I had to go into the app's permissions in the settings menu and give my app the Camera permission. I'm guessing it's because my USB device is a camera? Once I granted this permission, the app worked just as described in the docs https://developer.android.com/guide/topics/connectivity/usb/host

Install apk in android device from java code

I am trying to make a simple application in Java to install an APK on Android devices connected via USB. Using ABD manually or installing from Android Studio it works fine, but I wanted to give a simple single button click install option within my application, I have tried following code but unfortunately, it is not working
abdsourcesync = apkpath;
progress.setString("sync in progress");
System.out.println("Starting Sync via adb with command " + "adb"
+ " install -r " + apkpath);
Process process = Runtime.getRuntime().exec(
"adb" + " install -r " + apkpath);
InputStreamReader reader = new InputStreamReader(
process.getInputStream());
Scanner scanner = new Scanner(reader);
scanner.close();
int exitCode = process.waitFor();
System.out.println("Process returned: " + exitCode);
I have searched around here but I have only found installing an APK from within an Android application or from the android studio, not from a core Java. or java web module
Your helping hand would be really appreciated ;
Do not forget about runtime permissions
This simple example works for me for API 28.
It opens an apk file to install from "Download folder"
For simplification:
Download the apk file for application you want to install to "Download" folder of your phone. (There are a lot of instructions to do it programmaticaly, ot you can do it manualy)
TO DO
Create new project
Add a button to MainActivity
Create xml folder in res folder and create a file_paths.xml file there
Use the code bellow
Enjoy =)
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.teko.testcleanopenfile">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<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"
tools:ignore="GoogleAppIndexingWarning">
<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="androidx.core.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
MainActivity
public class MainActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textView and button
textView = findViewById(R.id.textView);textView.setText("Hello updatable World\n");
(findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {RunAPK(getBaseContext());}
});
}
private void RunAPK(Context context){
requestPermissionsToRead();
}
private void requestPermissionsToRead() {
// ASK RUNTIME PERMISSIONS
ActivityCompat.requestPermissions(MainActivity.this, new String[]{READ_EXTERNAL_STORAGE},111);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (grantResults.length > 0) {
if (requestCode == 111 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
textView.append("Permission granted write\n");
// Create Uri
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file1 = new File (downloads + "//app-debug.apk");//downloads.listFiles()[0];
Uri contentUri1 = getUriForFile(this, BuildConfig.APPLICATION_ID, file1);
// Intent to open apk
Intent intent = new Intent(Intent.ACTION_VIEW, contentUri1);
intent.setDataAndType(contentUri1, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
}
}
}
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="download" path="."/>
</paths>
You can Install Application from Java code using below way.
File outputFile = null;
try {
outputFile = new File(<APK Path>);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", outputFile);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mContext.startActivity(intent);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
Uri apkUri = Uri.fromFile(outputFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}else {
Toast.makeText(mContext, "File not found.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}

Wrong activity displayed when implicit intent received from another app with Action.SEND

I have an app with two activities: MainActivity, which contains a URL entry field where the user can enter a YouTube video URL and press a submit button, to start the second activity, VideoActivity, which displays some information about this video (fetched from another web server).
The app also has a feature to receive intent via the Youtube application. When user presses the share button within the Youtube app, my app appears in the share list. Upon pressing share from the Youtube app, MainActivity should be brought to the front, and the URL should be posted within the MainActivity's URL field.
However, this only happens correctly on the first share. If the app is in the background when user shares from Youtube app, they are taken to whatever the last visible activity was, whether it is MainActivity or VideoActivity, (and even if it is MainActivity, the URL is not posted into the URL field, but the field is left in whatever state it was in when the app was last visible).
Here is my current AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.youcmt.youdmcapp">
<uses-permission android:name="android.permission.INTERNET"/>
<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"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
<activity
android:name=".VideoActivity"
android:parentActivityName=".MainActivity"/>
<service
android:name=".FetchVideoService"
android:exported="false"/>
</application>
</manifest>
Here is my MainActivity.java code:
public class MainActivity extends AppCompatActivity {
private ResponseReceiver mReceiver;
private EditText mUrlEditText;
private Button mSearchButton;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
mUrlEditText = findViewById(R.id.url_search_et);
Intent intent = getIntent();
if (intent.getType()!=null &&
intent.getType().equals("text/plain")) {
Bundle extras = getIntent().getExtras();
String value = extras.getString(Intent.EXTRA_TEXT);
if(value!=null)
{
mUrlEditText.setText(value);
}
}
mProgressBar = findViewById(R.id.progress_bar);
mSearchButton = findViewById(R.id.search_button);
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
askForVideo(mUrlEditText.getText().toString());
mSearchButton.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
} catch (Exception e) {
mUrlEditText.setText("");
mUrlEditText.setHint(e.getMessage());
e.printStackTrace();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
//register the ResponseReceiver
mReceiver = new ResponseReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(FETCH_VIDEO_INFO);
registerReceiver(mReceiver, intentFilter);
}
private void askForVideo (String url) throws Exception {
try {
Intent intent = FetchVideoService.newIntent(this, url);
startService(intent);
} catch (Exception e) {
mUrlEditText.setText(e.getMessage());
}
}
public class ResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_VIDEO_STATUS, FAIL);
mProgressBar.setVisibility(View.INVISIBLE);
mSearchButton.setVisibility(View.VISIBLE);
if(status==FAIL)
{
mUrlEditText.setText("");
mUrlEditText.setHint("Error retrieving video!");
}
else if(status==SUCCESS) {
Video video = intent.getParcelableExtra(EXTRA_VIDEO);
Intent videoActivityIntent =
VideoActivity.newIntent(getApplicationContext(), video);
startActivity(videoActivityIntent);
}
}
}
#Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
}
I do not think any of the other files will be useful in understanding the problem. Although this seems like something many app creators should have to deal with, I can find no answers to this problem. Please comment if you feel I should add any additional information and thank you in advance for any help!
Update: testing demonstrates that after the first use of "Share" from YouTube (and considering app remains in the background), the MainActivity no longer receives any new intent on further shares. However, my app is still brought to the foreground somehow. This is very confusing to me.
When you share from another app, your MainActivity is brought to the front and onNewIntent() is called on it. You don't override onNewIntent() so you never see the share Intent.

User location sender app crashes when button is pushed [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have developed an app that sends the user's location via SMS. When I starting building it there were no errors, but when it is being tested with an actual phone it crashes ... It would not open.
public class MainActivity extends AppCompatActivity {
EditText phone;
Button emergency;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone= (EditText) findViewById(R.id.number);
emergency= (Button) findViewById(R.id.emergency);
emergency.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GPStracker g = new GPStracker(getApplicationContext());
Location l = g.getLocation();
if (l != null) {
double lat = l.getLatitude();
double lon = l.getLongitude();
String message = "http://maps.google.com/maps?saddr=" + lat + "," + lon;
String number = "number";
SmsManager smsManager = SmsManager.getDefault();
StringBuffer smsBody = new StringBuffer();
smsBody.append(Uri.parse(message));
android.telephony.SmsManager.getDefault().sendTextMessage(number, null, smsBody.toString(), null, null);
}
}
});
}
AND ALSO HERE IS MY CLASS FOR GPS TRACKING
public class GPStracker implements LocationListener {
Context context;
public GPStracker(Context c){
context = c;
}
public Location getLocation(){
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,10,this);
Location l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return l;
}else{
Toast.makeText(context,"Please enable GPS", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
}
}
AND MY MANIFEST FILE
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.research.sos.smshelpcaller">
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
<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>
</application>
I ALREADY TRY EVERYTHING BUT I DON'T KNOW WHAT IS WRONG IN MY CODES OR IS THERE SOMETHING MISSING.
LASTLY HERE IS THE LOGS IN LOGCAT
04-03 13:55:56.472 31224-31224/com.research.sos.smshelpcaller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.research.sos.smshelpcaller, PID: 31224
java.lang.NullPointerException: Attempt to get length of null array
at android.os.Parcel.readException(Parcel.java:1546)
at android.os.Parcel.readException(Parcel.java:1493)
at com.android.internal.telephony.ISms$Stub$Proxy.sendText(ISms.java:1430)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:320)
at com.research.sos.smshelpcaller.MainActivity$1.onClick(MainActivity.java:37)
at android.view.View.performClick(View.java:5052)
at android.view.View$PerformClick.run(View.java:20162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5753)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
where is your layout file,
Give your xml reference to activity after super.onCreate(savedInstanceState);.
for example..
setContentView(R.layout.activity_main);
According to your log you try to invoke method on Null Pointer:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.research.sos.smshelpcaller.MainActivity.onCreate(MainActivity.java:23)
It means, that the code below does not resolve the R.id.emergency asset. It simply can't find it and the first line is set to null:
emergency= (Button) findViewById(R.id.emergency);
emergency.setOnClickListener(new View.OnClickListener() {...}
You should check if the name of the button you try to use is correct, if there is no spell mistakes, or even if the resource file (for example xml with view) exists.

Android getapplication() data

I am using getHotelName() and setHotelName() to store data in the application and then access it. In my main activity that is categorized as Launcher both the methods and the getApplication() works in this activity. But when I try to access the getApplication from a different activity which is called from the main activity it gives a force close error.
This is my manifest file :
<application android:icon="#drawable/icon" android:label="#string/app_short_name" android:name="RestaurantNetwork" android:allowClearUserData="true" android:theme="#android:style/Theme.Black" >
<activity android:name="RestaurantActivity"
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="NetworkCommunication"></activity>
<uses-permission android:name="android.permission.INTERNET" />
</application>
In the main activity
RestaurantNetwork application = (RestaurantNetwork) getApplication();
application.setHotelName(this.hotelname.getText().toString());
Intent intent = new Intent(view.getContext(), NetworkCommunication.class);
startActivity(intent);
In the NetworkCommunication activity
public class NetworkCommunication extends Activity {
RestaurantNetwork application = (RestaurantNetwork) getApplication();
String hotelname = application.getHotelName().toString();
#Override
public void onCreate(Bundle savedInstanceState) {
I solved it using intent.extra, yes i had to get rid of the getApplication(). Would still like to know why there was an error in the prev method
in my main activity
this.hotelname = (EditText) findViewById(R.id.HotelName);
//RestaurantNetwork application = (RestaurantNetwork)getApplication();
//application.setHotelName(this.hotelname.getText().toString());
Intent intent = new Intent(view.getContext(), NetworkCommunication.class);
intent.putExtra("hotelName",this.hotelname.getText().toString());
startActivity(intent);
in my second activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresults);
String value = null;
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
value = extras.getString("hotelName");
}
Toast.makeText(getApplicationContext(),value, Toast.LENGTH_SHORT).show();

Categories

Resources