Recently I have been working on android studio, I built a python image classification model and want to integrate it with an app. But when I click on predict button, the app crashes. Would be helpful if I can get the idea as to where things are going wrong.
Attached is the code and the error it throws -
Activitymain.java :-
package com.example.uni;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.uni.ml.ConvertedModel;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
public class MainActivity extends AppCompatActivity {
private ImageView imgView;
private Button predict;
private Button select;
private TextView tv;
private Bitmap img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
tv = (TextView) findViewById(R.id.textView);
select = (Button) findViewById(R.id.button);
predict = (Button) findViewById(R.id.button2);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,12);
}
});
predict.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img = Bitmap.createScaledBitmap(img,
500,
500,
true);
try {
ConvertedModel model = ConvertedModel.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 500, 500, 3}, DataType.FLOAT32);
TensorImage tensorImage = new TensorImage(DataType.FLOAT32);
tensorImage.load(img);
ByteBuffer byteBuffer = tensorImage.getBuffer();
inputFeature0.loadBuffer(byteBuffer);
// Runs model inference and gets result.
ConvertedModel.Outputs outputs = model.process(inputFeature0);
TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
// Releases model resources if no longer used.
model.close();
tv.setText((int) outputFeature0.getFloatArray()[0]);
} catch (IOException e) {
/* TODO Handle the exception */
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100)
{
imgView.setImageURI(data.getData());
Uri uri = data.getData();
try {
img = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In logcat I see this -
2021-11-05 13:23:38.040 24027-24027/com.example.uni I/tflite: Initialized TensorFlow Lite runtime.
2021-11-05 13:23:38.090 24027-24027/com.example.uni E/libc: Access denied finding property "ro.hardware.chipname"
2021-11-05 13:23:38.081 24027-24027/com.example.uni W/com.example.uni: type=1400 audit(0.0:232245): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=14249 scontext=u:r:untrusted_app:s0:c48,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2021-11-05 13:23:38.841 24027-24027/com.example.uni E/com.example.un: Invalid ID 0x00000000.
2021-11-05 13:23:38.842 24027-24027/com.example.uni D/AndroidRuntime: Shutting down VM
2021-11-05 13:23:38.843 24027-24027/com.example.uni E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.uni, PID: 24027
android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:381)
at android.content.res.MiuiResources.getText(MiuiResources.java:97)
at android.widget.TextView.setText(TextView.java:6397)
at com.example.uni.MainActivity$2.onClick(MainActivity.java:85)
at android.view.View.performClick(View.java:7189)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:819)
at android.view.View$PerformClick.run(View.java:27682)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
2021-11-05 13:23:38.887 24027-24027/com.example.uni I/Process: Sending signal. PID: 24027 SIG: 9
Need suggestions as to what's going on and how to resolve it. I'm using android studio arctic fox 2020.3.1 patch 3.
The logcat already told you that it crashed at the setText() call. You called
tv.setText((int) outputFeature0.getFloatArray()[0]);
The int in setText(int) refers to a Resource ID defined in the string.xml (R.string.xxx).
If you are not getting the string from res, you should use setText(CharSequence) instead.
You probably want
tv.setText(String.format("%f",outputFeature0.getFloatArray()[0]));
(change "%f" to any decimal points or format you want)
Related
There is no error when gradle. When it is install on the virtual machine, the program cannot run and the following error is displayed. This is the code. This is Android development.
MainActivity.java
package com.example.app;
import java.util.List;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.esri.arcgisruntime.data.ArcGISFeature;
import com.esri.arcgisruntime.data.FeatureEditResult;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.IdentifyLayerResult;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.google.android.material.snackbar.Snackbar;
import android.app.ProgressDialog;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private MapView mMapView;
private Callout mCallout;
private ArcGISFeature mSelectedArcGISFeature;
private static final String TAG = MainActivity.class.getSimpleName();
private android.graphics.Point mClickPoint;
private Snackbar mSnackbarSuccess;
private Snackbar mSnackbarFailure;
private String mSelectedArcGISFeatureAttributeValue;
private boolean mFeatureUpdated;
private View mCoordinatorLayout;
private ProgressDialog mProgressDialog;
private ServiceFeatureTable mServiceFeatureTable;
private FeatureLayer mFeatureLayer;
#SuppressLint("ClickableViewAccessibility")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = findViewById(R.id.mapView);
String url = "http://map.geoq.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer";
ArcGISTiledLayer arcGISTiledLayer = new ArcGISTiledLayer(url);
Basemap basemap = new Basemap(arcGISTiledLayer);
ArcGISMap arcGISMap = new ArcGISMap(basemap);
mCallout = mMapView.getCallout();
ServiceFeatureTable mServiceFeatureTable = new ServiceFeatureTable("http://192.168.1.103:6080/arcgis/rest/services/huda1/MapServer/0");
FeatureLayer featureLayer = new FeatureLayer(mServiceFeatureTable);
arcGISMap.getOperationalLayers().add(featureLayer);
mFeatureLayer.setOpacity(0.8f);*/
mMapView.setMap(arcGISMap);
mMapView.setViewpoint(new Viewpoint(30.577421, 114.331955, 10000));
//set an on touch listener to listen for click events
// set an on touch listener to listen for click events
mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// get the point that was clicked and convert it to a point in map coordinates
mClickPoint = new android.graphics.Point((int) e.getX(), (int) e.getY());
// clear any previous selection
mFeatureLayer.clearSelection();
mSelectedArcGISFeature = null;
mCallout.dismiss();
// identify the GeoElements in the given layer
final ListenableFuture<IdentifyLayerResult> identifyFuture = mMapView
.identifyLayerAsync(mFeatureLayer, mClickPoint, 5, false, 1);
// add done loading listener to fire when the selection returns
identifyFuture.addDoneListener(() -> {
try {
// call get on the future to get the result
IdentifyLayerResult layerResult = identifyFuture.get();
List<GeoElement> resultGeoElements = layerResult.getElements();
if (!resultGeoElements.isEmpty()) {
if (resultGeoElements.get(0) instanceof ArcGISFeature) {
mSelectedArcGISFeature = (ArcGISFeature) resultGeoElements.get(0);
// highlight the selected feature
mFeatureLayer.selectFeature(mSelectedArcGISFeature);
// show callout with the value for the attribute "typdamage" of the selected feature
mSelectedArcGISFeatureAttributeValue = (String) mSelectedArcGISFeature.getAttributes()
.get("typdamage");
showCallout(mSelectedArcGISFeatureAttributeValue);
Toast.makeText(MainActivity.this, "Tap on the info button to change attribute value",
Toast.LENGTH_SHORT).show();
}
} else {
// none of the features on the map were selected
mCallout.dismiss();
}
} catch (Exception e1) {
Log.e(TAG, "Select feature failed: " + e1.getMessage());
}
});
return super.onSingleTapConfirmed(e);
}
});
mSnackbarSuccess = Snackbar
.make(mCoordinatorLayout, "Feature successfully updated", Snackbar.LENGTH_LONG)
.setAction("UNDO", view -> {
String snackBarText = updateAttributes(mSelectedArcGISFeatureAttributeValue) ?
"Feature is restored!" :
"Feature restore failed!";
Snackbar snackbar1 = Snackbar.make(mCoordinatorLayout, snackBarText, Snackbar.LENGTH_SHORT);
snackbar1.show();
});
mSnackbarFailure = Snackbar.make(mCoordinatorLayout, "Feature update failed", Snackbar.LENGTH_LONG);
}
/**
* Function to read the result from newly created activity
*/
#Override
protected void onActivityResult(int requestCode,
int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
// display progress dialog while updating attribute callout
mProgressDialog.show();
updateAttributes(data.getStringExtra("typdamage"));
}
}
/**
* Applies changes to the feature, Service Feature Table, and server.
*/
private boolean updateAttributes(final String typeDamage) {
// load the selected feature
mSelectedArcGISFeature.loadAsync();
// update the selected feature
mSelectedArcGISFeature.addDoneLoadingListener(() -> {
if (mSelectedArcGISFeature.getLoadStatus() == LoadStatus.FAILED_TO_LOAD) {
Log.e(TAG, "Error while loading feature");
}
// update the Attributes map with the new selected value for "typdamage"
mSelectedArcGISFeature.getAttributes().put("typdamage", typeDamage);
try {
// update feature in the feature table
ListenableFuture<Void> mapViewResult = mServiceFeatureTable.updateFeatureAsync(mSelectedArcGISFeature);
/*mServiceFeatureTable.updateFeatureAsync(mSelectedArcGISFeature).addDoneListener(new Runnable() {*/
mapViewResult.addDoneListener(() -> {
// apply change to the server
final ListenableFuture<List<FeatureEditResult>> serverResult = mServiceFeatureTable.applyEditsAsync();
serverResult.addDoneListener(() -> {
try {
// check if server result successful
List<FeatureEditResult> edits = serverResult.get();
if (!edits.isEmpty()) {
if (!edits.get(0).hasCompletedWithErrors()) {
Log.e(TAG, "Feature successfully updated");
mSnackbarSuccess.show();
mFeatureUpdated = true;
}
} else {
Log.e(TAG, "The attribute type was not changed");
mSnackbarFailure.show();
mFeatureUpdated = false;
}
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
// display the callout with the updated value
showCallout((String) mSelectedArcGISFeature.getAttributes().get("typdamage"));
}
} catch (Exception e) {
Log.e(TAG, "applying changes to the server failed: " + e.getMessage());
}
});
});
} catch (Exception e) {
Log.e(TAG, "updating feature in the feature table failed: " + e.getMessage());
}
});
return mFeatureUpdated;
}
/**
* Displays Callout
*
* #param title the text to show in the Callout
*/
private void showCallout(String title) {
// create a text view for the callout
RelativeLayout calloutLayout = new RelativeLayout(getApplicationContext());
TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setId(R.id.textview);
calloutContent.setTextColor(Color.BLACK);
calloutContent.setTextSize(18);
calloutContent.setPadding(0, 10, 10, 0);
calloutContent.setText(title);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeParams.addRule(RelativeLayout.RIGHT_OF, calloutContent.getId());
// create image view for the callout
ImageView imageView = new ImageView(getApplicationContext());
imageView
.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_info_outline_black_18dp));
imageView.setLayoutParams(relativeParams);
imageView.setOnClickListener(new ImageViewOnclickListener());
calloutLayout.addView(calloutContent);
calloutLayout.addView(imageView);
mCallout.setGeoElement(mSelectedArcGISFeature, null);
mCallout.setContent(calloutLayout);
mCallout.show();
}
#Override
protected void onPause() {
mMapView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.resume();
}
#Override
protected void onDestroy() {
mMapView.dispose();
super.onDestroy();
}
/**
* Defines the listener for the ImageView clicks
*/
private class ImageViewOnclickListener implements View.OnClickListener {
#Override public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, DamageTypesListActivity.class);
startActivityForResult(myIntent, 100);
}
}
}
DamageTypesListActivity.java
package com.example.app;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Displays the Damage type options in a ListView.
*/
public class DamageTypesListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.damage_types_listview);
final String[] damageTypes = getResources().getStringArray(R.array.damage_types);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(new ArrayAdapter<>(this, R.layout.damage_types, damageTypes));
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent();
myIntent.putExtra("typdamage", damageTypes[position]); //Optional parameters
setResult(100, myIntent);
finish();
}
});
}
#Override
public void onBackPressed() {
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.DisplayAMapJava">
<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=".DamageTypesListActivity"
android:label="#string/select_damage_Type">
</activity>
</application>
</manifest>
strings.xml
<resources>
<string name="app_name">Display a map java</string>
<string name="select_damage_Type">"Select new damage type"</string>
<!-- Progress dialog messages -->
<string name="progress_title">Updating attribute type</string>
<string name="progress_message">Please wait…</string>
<!-- Sample Strings -->
<string name="sample_service_url">https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0</string>
<string-array name="damage_types">
<item>Destroyed</item>
<item>Major</item>
<item>Minor</item>
<item>Affected</item>
<item>Inaccessible</item>
</string-array>
</resources>
below is logcat message
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app, PID: 21571
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
at com.google.android.material.snackbar.Snackbar.make(Snackbar.java:158)
at com.example.app.MainActivity.onCreate(MainActivity.java:137)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Initialize the CoordinatorLayout (mCoordinatorLayout) before using it in Snackbar.make()
Use findViewById to initialize mCoordinatorLayout
mCoordinatorLayout = findViewById(layout_id)
Having problems debugging an android networking application. I think I might have some problems with the import but I don't know which. If you can see the problem, please do let me know. Thank you.
MainActivity.java
package com.example.networkingfinals;
import androidx.appcompat.app.AppCompatActivity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<BookInfo>> {
private String url;
private String input;
private BookAdapter bookAdapter;
private int LOADER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.input);
input = String.valueOf(editText.getText());
url = "https://www.googleapis.com/books/v1/volumes?q="+input+"&maxResults=3";
}
});
LoaderManager loaderManager = getLoaderManager();
getLoaderManager().initLoader(LOADER_ID, null, this);//Set loader manager to call asyncloader in onCreateLoader
//TODO: Implement AsyncTaskLoader and LoadManager fetching network data on parallel thread
}
#Override
public Loader<List<BookInfo>> onCreateLoader(int id, Bundle args) {
Loader<List<BookInfo>> books = new BookAsync(this, url);
return books;
//Call oncreate Loader , fetching List of Book Info
}
#Override
public void onLoadFinished(Loader<List<BookInfo>> loader, List<BookInfo> data) {
Log.v("onLoadFinished", "Return " + data);
bookAdapter.addAll(data);
}
#Override
public void onLoaderReset(Loader loader) {
bookAdapter.clear();
}
Logcat
2021-01-10 18:44:55.950 13590-13590/com.example.networkingfinals V/onCreateLoader: Return BookAsync{814c192 id=0}
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals V/onLoadFinished: Return null
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals D/AndroidRuntime: Shutting down VM
2021-01-10 18:44:56.055 13590-13590/com.example.networkingfinals E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.networkingfinals, PID: 13590
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:61)
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:17)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:497)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:465)
at android.content.Loader.deliverResult(Loader.java:157)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:274)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:97)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
2021-01-10 18:44:56.138 13590-13590/com.example.networkingfinals I/Process: Sending signal. PID: 13590 SIG:
I think I don't understand how onCreateLoader() and onLoadFinished() works. I tried and find that onCreateLoader return non-null data but in onLoadFinished() the data passed into it was null.
This error is because your adapter is not initialized yet you need to initialize it in onCreate
this.bookAdapter = new BookAdapter();
the error message says
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
that means is your adapter is null and you call addAll from the null object reference
I have created an app that basically takes a picture and saves it to the gallery. The only problem is that after the picture is taken it takes you to the screen where you can preview it with the two buttons that say okay and cancel. Once you click okay, the app quits. The image is still saved to the gallery but I want the app to stay open. I also want the app to display a bitmap of the image on an imageView that I have.
Here is my MainActivity.java
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity { <- Line 22
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(); <- Line 34
}
});
}
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
// I AM UNSURE WHAT CODE TO PUT HERE. DOES ANYONE KNOW WHAT I SHOULD BE PUTTING HERE?
}
// Continue only if the File was successfully created
if (photoFile != null) {
//This is where the error is occurring but I do not know why.
Line 56 -> Uri photoURI = FileProvider.getUriForFile(this, "com.example.app", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(imageBitmap);
}
}
String currentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
Here is my error message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app, PID: 22357
java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.example.app
at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:606)
at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
--> at com.example.app.MainActivity.dispatchTakePictureIntent(MainActivity.java:56)
--> at com.example.app.MainActivity.access$000(MainActivity.java:22)
--> at com.example.app.MainActivity$1.onClick(MainActivity.java:34)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14966)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29315)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7777)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
I/Process: Sending signal. PID: 22357 SIG: 9
I want to show the floating layout on top of the screen when service Alarm or Call happened. Normally, when the app opens or it is in the background (before swiping it out) it shows and works well. even if I kill the app it still shows (kill = swipe the app)and it is still working. but, if the app is killed and not opened it tries to show (from service of alarm for example) it crashes and I cant even see the crash log in the android studio after terminating the app.
how can I fix that or find the issue?
my code Alarm BroadCast where it called: (the alarm broadcast called as needed)
public class BroadcastManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent = new Intent(context,FloatingWindow.class);
startService(intent);
}
my floating view code :
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.greenbook.greenlids.MainActivity;
import com.example.greenbook.greenlids.R;
public class FloatingWindow extends Service {
private WindowManager windowManager;
private LinearLayout layout;
private TextView txt;
private Button bttn1 , exitBttn;
private Context context;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layout = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setBackgroundColor(Color.argb(255,0,0,255));
layout.setLayoutParams(layoutParams);
final WindowManager.LayoutParams windowParams;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
windowParams.x = 0;
windowParams.y = 0;
windowParams.gravity = Gravity.CENTER;
}else{
windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
windowParams.x = 0;
windowParams.y = 0;
windowParams.gravity = Gravity.CENTER;
}
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
if (layoutInflater != null) {
layout = (LinearLayout) layoutInflater.inflate(R.layout.linear_layout_floating_window, null);
}
layout.setBackgroundColor(Color.argb(255,240,240,255));
bttn1 = layout.findViewById(R.id.LLbutton);
exitBttn = layout.findViewById(R.id.exitBttn);
txt = layout.findViewById(R.id.noteTxt);
txt.setTextSize(18);
txt.setText("Natan");
exitBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
windowManager.removeView(layout);
stopSelf();
}
});
bttn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean handler = new Handler().postDelayed(new Runnable() {
#Override
public void run() {
txt.setText("Natan The King");
}
}, 1000*5);
}
});
windowManager.addView(layout,windowParams);
layout.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams updateParam = windowParams;
int x , y;
float touchedX , touchedY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
x = updateParam.x;
y = updateParam.y;
touchedX = event.getRawX();
touchedY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
updateParam.x = (int) (x+event.getRawX() - touchedX);
updateParam.y = (int) (y+event.getRawY() - touchedY);
windowManager.updateViewLayout(layout,updateParam);
break;
}
return false;
}
});
}
}
logcat updated:
06-18 11:59:00.263 6722-6722/? E/Zygote: isWhitelistProcess - Process is Whitelisted
06-18 11:59:00.264 6722-6722/? E/libpersona: scanKnoxPersonas
Couldn't open the File - /data/system/users/0/personalist.xml - No such file or directory
06-18 11:59:00.268 6722-6722/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[2], Con:u:r:zygote:s0 RAM:SEPF_SM-G935F_8.0.0_0007, [-1 -1 -1 -1 0 1]
06-18 11:59:00.269 6722-6722/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.example.greenbook.greenlids
06-18 11:59:00.275 6722-6722/? I/zygote64: Late-enabling -Xcheck:jni
06-18 11:59:00.341 6722-6722/? D/TimaKeyStoreProvider: TimaKeyStore is not enabled: cannot add TimaSignature Service and generateKeyPair Service
06-18 11:59:00.341 6722-6722/? D/ActivityThread: Added TimaKeyStore provider
06-18 11:59:00.422 6722-6722/com.example.greenbook.greenlids I/zygote64: no shared libraies, dex_files: 1
06-18 11:59:00.723 6722-6722/com.example.greenbook.greenlids I/InstantRun: starting instant run server: is main process
06-18 11:59:00.750 6722-6722/com.example.greenbook.greenlids D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-18 11:59:00.755 6722-6722/com.example.greenbook.greenlids E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.greenbook.greenlids, PID: 6722
java.lang.RuntimeException: Unable to start receiver com.example.greenbook.greenlids.models.BroadcastManager: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.example.greenbook.greenlids/.floating_window.FloatingWindow }: app is in background uid UidRecord{1651455 u0a451 RCVR idle procs:1 seq(0,0,0)}
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3399)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.example.greenbook.greenlids/.floating_window.FloatingWindow }: app is in background uid UidRecord{1651455 u0a451 RCVR idle procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1538)
at android.app.ContextImpl.startService(ContextImpl.java:1484)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at android.content.ContextWrapper.startService(ContextWrapper.java:663)
at com.example.greenbook.greenlids.models.BroadcastManager.onReceive(BroadcastManager.java:40)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3392)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1780)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that's visible to the user, such as:
Handling a high-priority Firebase Cloud Messaging (FCM) message.
Receiving a broadcast, such as an SMS/MMS message.
Executing a PendingIntent from a notification.
Starting a VpnService before the VPN app promotes itself to the foreground.
taked from the link below
i found the answer here:
https://stackoverflow.com/a/46445436/8675712
https://stackoverflow.com/a/47654126/8675712
i am new to android development and i am writing an app for my college project .The app transmits a string of data stored in shared preferences .The data is stored by one time setup screen which is never shown again.The issue is after first time,when app is started again it shows that "app has unfortunately stopped working "and when i click ok the app starts.Can anybody tell me why this is happening?
Code:
package com.example.homeautomation.zigbeehomeauto;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainScreen extends ActionBarActivity {
NdefMessage msg;
NfcAdapter nfcadapter;
public static final String PREFS_NAME = "MyPrefsFile";
public String pass2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
SharedPreferences check = getSharedPreferences(PREFS_NAME, 0);
String Pass = check.getString("Str", "Nothing");
pass2 = Pass;
nfcadapter = NfcAdapter.getDefaultAdapter(this);
if (nfcadapter == null) {
Toast.makeText(this, "NFC is not available User", Toast.LENGTH_LONG)
.show();
finish();
}
}
public void ExApp(View v) {
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void Nsend(View v)
{
byte[] stringBytes = pass2.getBytes();
nfcadapter.setNdefPushMessage(msg = new NdefMessage(new NdefRecord[]{NdefRecord.createMime("text/plain", stringBytes)
}),this);
}
}
Logcat Ouput:
04-07 12:04:38.478 10836-10836/com.example.homeautomation.zigbeehomeauto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.homeautomation.zigbeehomeauto, PID: 10836
android.util.SuperNotCalledException: Activity {com.example.homeautomation.zigbeehomeauto/com.example.homeautomation.zigbeehomeauto.SetupScreen} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2603)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5752)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Check in your SetupScreen.java do you have super.onCreate(savedInstanceState);
after onCreate() Method is starts .
post your SetupScreen.java code also ..
Your onCreate() method of class SetupScreen do not call the super.onCreate(). Add the statement and the error should go away.