Android intent error null object reference [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hello im new in stackover flow i want to try these website and ask for someones help in my android when i change the intent there's an error in my android monitor in android studio here is it.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kim.checkerv3, PID: 2970
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kim.checkerv3/com.example.kim.checkerv3.BudgetOutput}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at com.example.kim.checkerv3.BudgetOutput.onCreate(BudgetOutput.java:22)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
i didn't understand this i'd tried researching for solution and im still stuck on it.
Here the intent will be pass to other java class.
package com.example.kim.checkerv3;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by KIM-PC on 12/5/2016.
*/
public class BudgetFragment extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_budget, container, false);
final EditText etCash = (EditText) v.findViewById(R.id.etCash);
final Button bBudget = (Button) v.findViewById(R.id.bBudget);
bBudget.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
SharedPreferences sharedpref = getContext().getSharedPreferences("user_id", MODE_PRIVATE);
String id = sharedpref.getString("user_id","");
final int budgeted = Integer.parseInt(etCash.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray arr = jsonResponse.getJSONArray("message");
boolean success = jsonResponse.getBoolean("success");
System.out.println(budgeted/arr.length());
int total = budgeted/arr.length();
if (success) {
Intent intent = new Intent(getContext(), BudgetOutput.class);
Bundle b = new Bundle();
b.putString("total", String.valueOf(total));
getContext().startActivity(intent);
if (arr != null) {
int sum = 0;
for(int i = 0;i<arr.length();i++){
//listdata.add(arr.get(i).toString());
String money = arr.getJSONObject(i).getString("amount");
sum += Integer.parseInt(money);
}
SharedPreferences sharedPref1 = getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref1.edit();
editor.putInt("TotalSum", sum);
editor.commit();
System.out.println(sum);
//arrayAdapter.notifyDataSetChanged();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Failed to fetch. Try again.")
.setNegativeButton("OK", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RecordRequest recordRequest = new RecordRequest(id, responseListener);
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(recordRequest);
}
});
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
SharedPreferences sharedpref1 = getContext().getSharedPreferences("mypref", MODE_PRIVATE);
int budgeted = sharedpref1.getInt("TotalSum", 0);
System.out.println(budgeted/2);
}
}
and the class where the intent will be get.
package com.example.kim.checkerv3;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by KIM-PC on 12/6/2016.
*/
public class BudgetOutput extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);
final TextView tvOutput = (TextView) findViewById(R.id.tvoutput);
Bundle b = getIntent().getExtras();
String output=b.getString("total");
if(b !=null)
output = b.getString("total");
tvOutput.setText(output+" Per cheque record.");
}
}
if there is someone who could solve i appreciate and give my thanks to you.

Well, you forgot to add your Bundle to the Intent
Intent intent = new Intent(getContext(), BudgetOutput.class);
Bundle b = new Bundle();
b.putString("total", String.valueOf(total));
intent.putExtras(b);
getContext().startActivity(intent);

Related

'void android.webkit.WebView.addJavascriptInterface(java.lang.Object, java.lang.String)' on a null object

I am trying to set up Firebase to log events for Google Analytics on my Android App and I get the error above.
I followed the tutorial but I think maybe since I am using ReactActivity instead of AppCompatActivity, maybe this is why it does nor work.
I am very new to java and would really appreciate some help!
Here is MainActivity.java
package com.app;
import com.facebook.react.ReactActivity;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.app.AnalyticsWebInterface;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Build;
import android.webkit.WebView;
import android.util.Log;
#SuppressLint({ "AddJavascriptInterface", "SetJavaScriptEnabled" })
public class MainActivity extends ReactActivity {
private static final String TAG = "MainActivity";
private FirebaseAnalytics mFirebaseAnalytics;
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ATTENTION: This was auto-generated to handle app links.
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mWebView.addJavascriptInterface(
new AnalyticsWebInterface(this), AnalyticsWebInterface.TAG);
} else {
Log.w(TAG, "Not adding JavaScriptInterface, API Version: " + Build.VERSION.SDK_INT);
}
logSearchEvent();
logPurchaseEvent();
}
/**
* Returns the name of the main component registered from JavaScript. This is
* used to schedule
* rendering of the component.
*/
#Override
protected String getMainComponentName() {
return "App";
}
private void logPurchaseEvent() {
String transactionId = "transactionId";
String value = "1.99";
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.TRANSACTION_ID, transactionId);
bundle.putString(FirebaseAnalytics.Param.VALUE, value);
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.PURCHASE, bundle);
}
private void logSearchEvent() {
String searchTerm = "searchTerm";
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.SEARCH_TERM, searchTerm);
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SEARCH, bundle);
}
}
and my Logcat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.addJavascriptInterface(java.lang.Object, java.lang.String)' on a null object reference
As you can see it seems that new AnalyticsWebInterface(this)is null although I imported it.
Anybody knows what is causing this error ?
Thanks!

Cannot instance a View Model because the table is empty

I'm creating a view model in my activity in order to add an object to the database via method. But the view model is representing an empty table, and it's causing this stack trace and complete crash of the application:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gmproxy.pastilarma, PID: 9827
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gmproxy.pastilarma/com.gmproxy.pastilarma.UserAddScreen}: java.lang.RuntimeException: Cannot create an instance of class com.gmproxy.Util.PathologyUserViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.gmproxy.Util.PathologyUserViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.gmproxy.pastilarma.UserAddScreen.onCreate(UserAddScreen.java:84)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
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:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
at com.gmproxy.pastilarma.UserAddScreen.onCreate(UserAddScreen.java:84) 
at android.app.Activity.performCreate(Activity.java:8000) 
at android.app.Activity.performCreate(Activity.java:7984) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
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:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
at androidx.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:385)
at androidx.room.RoomDatabase.query(RoomDatabase.java:441)
at androidx.room.util.DBUtil.query(DBUtil.java:83)
at com.gmproxy.DAO.PathologyUserDAO_Impl.getAllObjects(PathologyUserDAO_Impl.java:154)
at com.gmproxy.DAO.PathologyUserRepository.getAllObjects(PathologyUserRepository.java:19)
at com.gmproxy.Util.PathologyUserViewModel.<init>(PathologyUserViewModel.java:19)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:343) 
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267) 
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
at com.gmproxy.pastilarma.UserAddScreen.onCreate(UserAddScreen.java:84) 
at android.app.Activity.performCreate(Activity.java:8000) 
at android.app.Activity.performCreate(Activity.java:7984) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
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:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
This is happening as soon as I enter said activity. The other view models that have records in the database are created with no problem, but the other ones that lack any object in the database fail to create too. Do I purposedly need to add a record in order to create those?
This is the activity and view model code respectively:
Activity:
package com.gmproxy.pastilarma;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.lifecycle.ViewModelProvider;
import com.gmproxy.DAO.PathologyUserDAO;
import com.gmproxy.DAO.UserDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import com.gmproxy.Util.AlarmUserViewModel;
import com.gmproxy.Util.ImageConverter;
import com.gmproxy.Util.PathologyUserViewModel;
import com.gmproxy.Util.UserViewModel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserAddScreen extends AppCompatActivity {
Button gotoBack, addObservation, saveUser, addPathologies;
EditText addUsername, addSurname, addAge, addRoomNumber;
Spinner addGender;
ImageView selectImage;
String obs;
Pathology paths;
Context context;
UserViewModel userViewModel;
PathologyUserViewModel pathologyUserViewModel;
int pathAct = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
context = this.getApplicationContext();
Bundle bundle = new Bundle();
pathAct = getIntent().getIntExtra("path-record",0);
if (pathAct == 1){
onRestoreInstanceState(bundle);
}
setContentView(R.layout.activity_user_add_screen);
gotoBack = findViewById(R.id.GotoBack);
addObservation = findViewById(R.id.AddObservation);
saveUser = findViewById(R.id.SaveUser);
addPathologies = findViewById(R.id.AddPathologies);
addUsername = findViewById(R.id.AddUsername);
addSurname = findViewById(R.id.AddSurname);
addAge = findViewById(R.id.AddAge);
addRoomNumber = findViewById(R.id.AddRoomNumber);
addGender = findViewById(R.id.AddGender);
selectImage = findViewById(R.id.SelectImage);
userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
pathologyUserViewModel = new ViewModelProvider(this).get(PathologyUserViewModel.class);
List<String> genderList = new ArrayList<>();
genderList.add("M");
genderList.add("F");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,genderList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addGender.setAdapter(adapter);
obs = intent.getStringExtra("observation");
paths = (Pathology) intent.getSerializableExtra("paths");
}
public void gotoBack(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
}
public void addObservation(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserObservationScreen.class);
startActivity(mainAct);
}
public void addPathology(View view) {
Intent mainAct = new Intent(UserAddScreen.this, PathologiesSearchScreen.class);
startActivity(mainAct);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("Nombre_usuario",addUsername.getText().toString());
savedInstanceState.putString("Apellido_usuario",addSurname.getText().toString());
savedInstanceState.putString("Edad_usuario",addAge.getText().toString());
savedInstanceState.putString("Habitacion_usuario",addRoomNumber.getText().toString());
savedInstanceState.putInt("Sexo_usuario",addGender.getSelectedItemPosition());
savedInstanceState.putString("Observacion-usuario", obs);
savedInstanceState.putSerializable("Patologia-usuario", paths);
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
addUsername.setText(savedInstanceState.getString("Nombre_usuario"));
addSurname.setText(savedInstanceState.getString("Apellido_usuario"));
addAge.setText(savedInstanceState.getString("Edad_usuario"));
addRoomNumber.setText(savedInstanceState.getString("Habitacion_usuario"));
addGender.setSelection(savedInstanceState.getInt("Sexo_usuario"));
obs = savedInstanceState.getString("Observacion-usuario");
paths = (Pathology) savedInstanceState.getSerializable("Patologia-usuario");
}
public void selectImageAction(View view) {
final CharSequence[] options = {"Hacer una foto", "Elegir de la galería", "Usar una genérica" , "Cancelar"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserAddScreen.this);
builder.setTitle("¡Añade una foto!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Hacer una foto")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivity(intent);
} else if (options[item].equals("Elegir de la galería")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivity(intent);
} else if (options[item].equals("Cancelar")) {
dialog.dismiss();
} else if(options[item].equals("Usar una genérica")){
selectImage.setImageResource(R.drawable.ic_user_generic_foreground);
selectImage.setBackgroundResource(R.drawable.ic_user_generic_foreground);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
selectImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("..******************...", picturePath + "");
ImageView viewImage;
selectImage.setImageBitmap(thumbnail);
}
}
}
public void saveUser(View view) {
//Just this to turn the image into a blob
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.id.SelectImage);
ImageConverter imgCon = new ImageConverter();
byte[] bytearray = imgCon.bitmapToBiteArray(bitmap);
Toast.makeText(this, "Usuario creado.", Toast.LENGTH_SHORT).show();
User user = new User(addUsername.getText().toString(), addSurname.getText().toString(), addAge.getText().toString(),
Integer.parseInt(addRoomNumber.getText().toString()), addGender.getSelectedItem().toString(), obs, bytearray);
userViewModel.insert(user);
pathologyUserViewModel.insert(userViewModel.getIdByNameAndSurname(addUsername.getText().toString(),addSurname.getText().toString()), paths.getId_pathology());
Toast.makeText(this, "Patología " + paths.getPathologyName() + " añadida", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
}
}
View Model:
package com.gmproxy.Util;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import com.gmproxy.DAO.PathologyUserRepository;
import com.gmproxy.Entities.PathologyUser;
import java.util.List;
public class PathologyUserViewModel extends AndroidViewModel {
private PathologyUserRepository repository;
public List<PathologyUser> pathologyUsers;
public PathologyUserViewModel(Application application) {
super(application);
repository = new PathologyUserRepository(application);
pathologyUsers = repository.getAllObjects();
}
List<PathologyUser> getAll() { return pathologyUsers; }
public List<PathologyUser> getAllFromUser(int i) { return repository.getAllFromUser(i); }
public void insert(int i, int j) { repository.insertObject(i,j); }
public void delete(PathologyUser obj) { repository.deleteObject(obj); }
}
I don't quite remember anything about not being able to create view models with empty tables in the documentation, maybe I'm missing something?
Instead of the line:
pathologyUserViewModel = new ViewModelProvider(this).get(PathologyUserViewModel.class);
You can use:
pathologyUserViewModel = new ViewModelProvider
.AndroidViewModelFactory(this.getApplication())
.create(PathologyUserViewModel.class);
Or,
pathologyUserViewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory(application)
).get(PathologyUserViewModel::class.java)
If you look through the log, you are trying to access the database on the main thread :-
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time
at the line :-
pathologyUsers = repository.getAllObjects();
You either need to run this on another thread OR alternately (and not recommended) allow it to run on the main thread which can be done by using:-
.allowMainThreadQueries()
when building the room database. e.g. :-
Room.databaseBuilder(context, TheDatabase::class.java, "thedatabasefile.db")
.allowMainThreadQueries() //<<<<<<<<<< allow main thread run
.build()
Do I purposedly need to add a record in order to create those?
As long as you are handling the returned Lists correctly and not assuming they are not empty, there should be no problem.

How can I redirect 2 buttons to different intents in android?

enter image description here
I put a listener on each button that takes me to different activities.
The login button works perfectly, but the register button stops the app when I click on it.
I've tried to put a Toast message in the _btnreg listener, and it worked...
I got this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.virtualshelter, PID: 24128
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.virtualshelter/com.example.android.virtualshelter.register}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
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.example.android.virtualshelter.register.onCreate(register.java:35)
at android.app.Activity.performCreate(Activity.java:6754)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6247) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
package com.example.android.virtualshelter;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity
{
Button _btnreg, _btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_btnlogin = findViewById(R.id.btnlogin);
_btnreg = findViewById(R.id.btnreg);
_btnreg.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,register.class);
startActivity(intent);
}
});
_btnlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,login.class);
startActivity(intent);
}
});
}
}
My register.java code
package com.example.android.virtualshelter;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class register extends AppCompatActivity
{
SQLiteOpenHelper openHelper;
SQLiteDatabase db;
Button _btnReg;
EditText _txtfname, _txtlname, _txtpass, _txtemail, _txtphone;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
openHelper = new DatabaseHelper(register.this);
_txtfname = findViewById(R.id.txtfname);
_txtlname = findViewById(R.id.txtlname);
_txtpass = findViewById(R.id.txtpass);
_txtemail = findViewById(R.id.txtemail);
_txtphone = findViewById(R.id.txtphone);
_btnReg = findViewById(R.id.btnreg);
_btnReg.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
db = openHelper.getWritableDatabase();
String fname = _txtfname.getText().toString();
String lname = _txtlname.getText().toString();
String pass = _txtpass.getText().toString();
String email = _txtemail.getText().toString();
String phone = _txtphone.getText().toString();
insertdata(fname, lname, pass, email, phone);
Toast.makeText(getApplicationContext(), "register successfully", Toast.LENGTH_LONG).show();
}
});
}
public void insertdata(String fname, String lname, String pass, String email, String phone)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_2, fname);
contentValues.put(DatabaseHelper.COL_3, lname);
contentValues.put(DatabaseHelper.COL_4, pass);
contentValues.put(DatabaseHelper.COL_5, email);
contentValues.put(DatabaseHelper.COL_6, phone);
long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
}
I expect to go to activity register.java, but the app is crashing
My hunch is, you are not able find the button, causing a NPE when setting the listner. Could be that you don't have the button defined in R.layout.activity_main, but in a different layout.

ClassCastException : Fragment cannot be cast to Fragment

I have that app when, in MainActivity(which here is LoginActivity) first is replaced with a fragment(LoginFragment), for the sake of good code.
If a user want to signup, is redirected to a new SignUpFragment directly from mainActivity supportFragment manager:
//setting the first fragment in onCreate
fragmentManager = getSupportFragmentManager();
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);
if(fragment == null){
fragment = LoginFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
//Opening new registration fragment in LoginFragment.java
signUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((LoginActivity)getActivity()).loadSignUpFragment();
}
});
//In LoginActvity.java
public void loadSignUpFragment(){
SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
all good, is working at first opening. Trying to register a new user, is working
But, after applying some minor code changes(like showing a snackbar if login fails), i got that error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.minimalart.studentlife/com.minimalart.studentlife.activities.LoginActivity}: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519)
at android.app.ActivityThread.-wrap19(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
at com.minimalart.studentlife.activities.LoginActivity$override.onCreate(LoginActivity.java:38)
at com.minimalart.studentlife.activities.LoginActivity$override.access$dispatch(LoginActivity.java)
at com.minimalart.studentlife.activities.LoginActivity.onCreate(LoginActivity.java:0)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519) 
at android.app.ActivityThread.-wrap19(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
why i got that?
i'm switching and opening fragments only from my main activity
Thanks.
all LoginActivity.java:
package com.minimalart.studentlife.activities;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.minimalart.studentlife.R;
import com.minimalart.studentlife.fragments.LoginFragment;
import com.minimalart.studentlife.fragments.SignUpFragment;
public class LoginActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
fragmentManager = getSupportFragmentManager();
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);
if(fragment == null){
fragment = LoginFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
}
public void loadSignUpFragment(){
SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
public void signUpNewUser(String email, String pass, String firstName, String secName, String age){
firebaseAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
}
else{
Snackbar.make(findViewById(R.id.signUpLinearLayout), task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
// ...
}
});
}
public void logInUser(String email, String pass){
}
}
I solved this, i found that the problem is at declaring main fragment
replaced
LoginFragment fragment = (LoginFragment)fragmentManager.findFragmentById(R.id.activity_main_content);
with
Fragment fragment = fragmentManager.findFragmentById(R.id.activity_main_content);
thanks #Selvin for your hint :)

App crashes during Bluetooth discovery

What I'm trying to do
I'm trying to create an app that searches all the Bluetooth devices nearby and connects to the ones user wishes to connect to.
I'm trying to create a Connect button in one activity that starts the discovery function in another activity
How I'm trying to do it
So I have this MainActivity.java class / activity that has the Connect button. Upon clicking this button, it should do three things:
Check if the Bluetooth on my Smartphone is on & if it's not, turn it on.
Display a TOAST message to show whether BT has been successfully turned on or not
Start this new activity, called SearchBTDevice.java that looks for nearby BT devices & list them in a ListView
The first two are perfectly working since they're on MainActivity.java & that's where my button has been created.
Problem comes when it creates the new activity & tries to do the 3rd one. The app crashes.
This is what my MainActivity.java looks like
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import static java.lang.Thread.sleep;
public class MainActivity extends AppCompatActivity {
public BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQ_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void connect(View v)
{
if(BA == null)
Toast.makeText(MainActivity.this, "System Doesn't Support Bluetooth", Toast.LENGTH_SHORT).show();
else if(!BA.isEnabled())
{
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQ_CODE);
}
else {
Toast.makeText(MainActivity.this, "ALREADY ON!!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode!=RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "TURNED ON!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
else
Toast.makeText(MainActivity.this,"FAILED TO ENABLE BLUETOOTH", Toast.LENGTH_LONG).show();
}
public void searchBTDevices()
{
Thread searchThread = new Thread() {
#Override
public void run() {
Intent searchBT = new Intent(getApplicationContext(), SearchBTDevice.class);
startActivity(searchBT);
}
};
searchThread.start();
}
}
This is what my SearchBTDevice.java looks like
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Set;
public class SearchBTDevice extends AppCompatActivity {
public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
public ArrayAdapter PairedArrayAdapter, BTArrayAdapter;
public IntentFilter filter = new IntentFilter();
public ListView devicesFound;
public Set<BluetoothDevice> pairedDevices;
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(!BTArrayAdapter.isEmpty())
BTArrayAdapter.clear();
searchBTDevices();
}
public void searchBTDevices()
{
pairedDevices = BlueAdapter.getBondedDevices();
if(pairedDevices.size()>0)
for(BluetoothDevice device: pairedDevices)
PairedArrayAdapter.add(device.getName() + "\t\t" + device.getAddress() + "\n");
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
}
}
};
BlueAdapter.startDiscovery();
devicesFound = (ListView)findViewById(R.id.searchpagelistView);
devicesFound.setAdapter(BTArrayAdapter);
}
}
This is what the logcat shows when my app crashes
03-17 11:51:40.120 19178-19178/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: main
Process: vertex2016.mvjce.edu.bluealert, PID: 19178
java.lang.RuntimeException: Unable to start activity ComponentInfo{vertex2016.mvjce.edu.bluealert/vertex2016.mvjce.edu.bluealert.SearchBTDevice}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
at vertex2016.mvjce.edu.bluealert.SearchBTDevice.onCreate(SearchBTDevice.java:57)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
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:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
So these are my questions:
Where am I going wrong & what should I do?
Is there any way I can retrieve the BluetoothAdapter, which was created in my MainActivity.java, in my new activity called SearchBTDevice.java?
Is there anyway I can set the onClick operation of a button defined in one activity from another activity?
Thank you for your time!
Define your BTArrayAdapter object in SearchBTDevice class. It is null while you call BTArrayAdapter.isEmpty() in onCreate().

Categories

Resources