This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I am making an app music player in Android Studio. After the installation was finished, an app on opening asks for media permission. The problem occurs after permission is granted, the app automatically closes.
I don't know why, but I found in logcat following message NullPointerException : Attempt to get length of null array
My class is :
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
runtimePermission();
}
public void runtimePermission()
{
Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
displaySong();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file)
{
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
assert files != null;
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findSong(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) {
arrayList.add(singleFile);
}
}
}
return arrayList;
}
void displaySong()
{
final ArrayList<File> mySongs = findSong(Environment.getStorageDirectory());
items = new String[mySongs.size()];
for (int i=0;i<mySongs.size();i++)
{
items[i] = mySongs.get(i).getName().toString().replace(".mp3","").replace(".wav","");
}
customAdapter customAdapter = new customAdapter();
listView.setAdapter(customAdapter);
}
class customAdapter extends BaseAdapter
{
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.id.list_item,null);
TextView txtSong = view.findViewById(R.id.txtSong);
txtSong.setSelected(true);
txtSong.setText(items[position]);
return view;
}
}
}
Where I can found issue?
here is logcat
2021-08-05 22:17:03.244 22457-22457/com.devilteched.rexplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.devilteched.rexplayer, PID: 22457
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.devilteched.rexplayer/com.devilteched.rexplayer.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3550)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3710)
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:2139)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8047)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:600)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.devilteched.rexplayer.MainActivity.findSong(MainActivity.java:66)
at com.devilteched.rexplayer.MainActivity.findSong(MainActivity.java:68)
at com.devilteched.rexplayer.MainActivity.findSong(MainActivity.java:68)
at com.devilteched.rexplayer.MainActivity.displaySong(MainActivity.java:79)
at com.devilteched.rexplayer.MainActivity$1.onPermissionGranted(MainActivity.java:46)
at com.karumi.dexter.MultiplePermissionsListenerToPermissionListenerAdapter.onPermissionsChecked(Unknown Source:35)
at com.karumi.dexter.DexterInstance$1.run(Unknown Source:43)
at com.karumi.dexter.MainThread.execute(Unknown Source:6)
at com.karumi.dexter.DexterInstance.checkMultiplePermissions(Unknown Source:71)
at com.karumi.dexter.DexterInstance.checkPermissions(Unknown Source:0)
at com.karumi.dexter.Dexter.check(Unknown Source:10)
at com.devilteched.rexplayer.MainActivity.runtimePermission(MainActivity.java:58)
at com.devilteched.rexplayer.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:8126)
at android.app.Activity.performCreate(Activity.java:8098)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1310)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3523)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3710)
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:2139)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8047)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:600)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
2021-08-05 22:17:03.248 22457-22457/com.devilteched.rexplayer D/OOMEventManagerFK: checkEventAndDumpForJE: 0
2021-08-05 22:17:03.276 22457-22457/com.devilteched.rexplayer I/Process: Sending signal. PID: 22457 SIG: 9
You dont have check for this line of code:
final ArrayList<File> mySongs = findSong(Environment.getStorageDirectory());
Your method findSong() returns null or empty List.
Can you please add folloing block:
final ArrayList<File> mySongs = findSong(Environment.getStorageDirectory());
if(!mySongs.isEmpty())
{
items = new String[mySongs.size()];
for (int i=0;i<mySongs.size();i++)
{
items[i] = mySongs.get(i).getName().toString().replace(".mp3","").replace(".wav","");
}
}
Related
This question already has answers here:
java.lang.InstantiationException: class com.e has no zero argument constructor
(5 answers)
Closed 1 year ago.
This a error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginappaplication, PID: 20994
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.loginappaplication/com.example.loginappaplication.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.loginappaplication.MainActivity> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3703)
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:2216)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
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:1075)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.loginappaplication.MainActivity> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1251)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3703)
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:2216)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
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:1075)
public class MainActivity extends AppCompatActivity {
private EditText eName;
private EditText ePassword;
private Button eLogin;
private TextView eAttemptsInfo;
private String Username = "Azahracaca";
private String Password = "Caca12345";
boolean isvalid = false;
private int counter = 3;
public MainActivity(Button eLogin) {
this.eLogin = eLogin;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eName = findViewById(R.id.IdName);
ePassword = findViewById(R.id.etPassword);
eAttemptsInfo = findViewById(R.id.tvAttemptsInfo);
eLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputName = eName.getText().toString();
String inputPassword = ePassword.getText().toString();
if (inputName.isEmpty() || inputPassword.isEmpty())
{
Toast.makeText(MainActivity.this, "Pastikan Semuanya Benar !", Toast.LENGTH_SHORT).show();
}else{
isvalid = valited(inputName, inputPassword);
if(!isvalid){
counter--;
Toast.makeText(MainActivity.this, "Salah Memasukkan Data !", Toast.LENGTH_SHORT).show();
eAttemptsInfo.setText("Jumlah Login Tersisa : 3 Kali" + counter);
if(counter == 0){
eLogin.setEnabled(false);
}
}else {
Toast.makeText(MainActivity.this, "Login Sukses !", Toast.LENGTH_SHORT).show(); //ke menu selanjutnya
Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
}
}
}
});
}
private boolean valited(String name, String password){
if(name.equals(Username) && password.equals(Password)){
return true;
}
return false;
}
}
public MainActivity(Button eLogin) {
this.eLogin = eLogin;
}
make this constructor empty, and initialize eLogin button using findViewById as you are doing for eName.
you should initialize all of your views in/after onCreate(). can not initialize view in class constructor.
Why constructor Activity you passing Param?
Edit:
public class MainActivity extends AppcompatActivity
And
Button button = findViewById(R.id....)
The structure should like that
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The issue I have is there're always Null Pointer Exception when I settext textview, so I cannot setText to my view.
I think the object didn't fill the field from getData method. How to fix this?
I am following this step https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection and this Parcelable object passing from android activity to fragment.
This is the error output from android studio console
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my.plkbi, PID: 24337
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.my.plkbi.Layanan.getSyarat()' on a null object reference
at com.my.plkbi.SubMainFragment.onCreateView(SubMainFragment.java:78)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
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: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)
EDIT: Add constructor to add object from other object, I follow this How do I copy an object in Java?
This is the object about the field database and Parcelable
public class Layanan implements Parcelable {
private String Nama;
private String Syarat;
private String Langkah;
private String Lampiran;
public Layanan(){
//this("connect to internet", "connect to internet", "connect to internet", "connect to internet");
}
//Constructor to add value from another object
public Layanan(Layanan another) {
this.nama = another.nama;
this.syarat = another.syarat;
this.langkah = another.langkah;
this.lampiran = another.lampiran;
this.deskripsi = another.deskripsi;
}
protected Layanan(Parcel in) {
Nama = in.readString();
Syarat = in.readString();
Langkah = in.readString();
Lampiran = in.readString();
}
public static final Creator<Layanan> CREATOR = new Creator<Layanan>() {
#Override
public Layanan createFromParcel(Parcel in) {
return new Layanan(in);
}
#Override
public Layanan[] newArray(int size) {
return new Layanan[size];
}
};
public static Layanan newInstance() {
Bundle args = new Bundle();
Layanan fragment = new Layanan();
fragment.setArguments(args);
return fragment;
}
private void setArguments(Bundle args) {
}
public String getNama() {
return Nama;
}
public String getSyarat() {
return Syarat;
}
public void setSyarat(String syarat) {
Syarat = syarat;
}
public String getLangkah() {
return Langkah;
}
public void setNama(String nama) {
Nama = nama;
}
public void setLangkah(String langkah) {
Langkah = langkah;
}
public String getLampiran() {
return Lampiran;
}
public void setLampiran(String lampiran) {
Lampiran = lampiran;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Nama);
dest.writeString(Syarat);
dest.writeString(Langkah);
dest.writeString(Lampiran);
}
}
This is how i get data from Firebase, it's inside in activity
Layanan UP;
Layanan GU;
Layanan LS;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
//initMF();
MainFragment homeFragment = MainFragment.newInstance();
Bundle extras = new Bundle();
getData("UP");
Log.d(TAG, "This is the value name of " + UP.getNama()); //Output: This is the value name of null
extras.putParcelable(UPParcelable, UP);
if (UP.getSyarat()!=null) Log.d(TAG, "Value Added");
if (UP.getSyarat()==null) Log.d(TAG, "Value not Added"); //Output: Value not Added
homeFragment.setArguments(extras);
getSupportFragmentManager().beginTransaction().add(R.id.main_activity, homeFragment).commit();
}
...
...
public void getData(final String p){
mFirebase.collection("panduan_layanan")
.whereEqualTo("nama", p)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent:error", e);
return;
}
Layanan newLayanan = new Layanan();
for (QueryDocumentSnapshot doc : value) {
if (doc.get("nama") != null && doc.get("syarat") != null && doc.get("langkah") != null && doc.get("lampiran")!= null){
newLayanan.setNama(doc.getString("nama"));
newLayanan.setLampiran(doc.getString("lampiran"));
newLayanan.setLangkah(doc.getString("langkah"));
newLayanan.setSyarat(doc.getString("syarat"));
Log.d(TAG, "Update data: Success" + p);
Log.d(TAG, "This is the " + p + " syarat" + newLayanan.getSyarat());
if (newLayanan.getSyarat() != null) Log.d(TAG, "new layanan is" + newLayanan.getNama()); //new layanan isUP, it is work too
}
}
if (p.equals("UP")) UP = new Layanan(newLayanan);
Log.d(TAG, "the" + UP.getNama()); //Output theUP so it is work in here
if (p.equals("GU")) GU = new Layanan(newLayanan);
if (p.equals("LS")) LS = new Layanan(newLayanan);
}
});
}
...
Thank you so much
You can't do that because firebase execute that block asynchronously. So the field doesn't get value immediately just like Frank's comment said
public class FragmentPatientsByVital extends Fragment {
private RecyclerView mRecyclerView;
private ArrayList<Patient> mList;
private AdapterVitalPatient mAdapter;
private MultiStateToggleButton mMultiStateToggleButton;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_patient_by_vital, container, false);
initUi(v);
if (mList != null)
updateList(mList);
return v;
}
private void initUi(View v) {
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
mMultiStateToggleButton = (MultiStateToggleButton) v.findViewById(R.id.mstb_multi_id);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mMultiStateToggleButton.setOnValueChangedListener(new ToggleButton.OnValueChangedListener() {
#Override
public void onValueChanged(int position) {
mAdapter.filterBy(position);
}
});
}
public void updateList(ArrayList<Patient> mList) {
if (mList == null) return;
this.mList = mList;
if (mAdapter == null)
mAdapter = new AdapterVitalPatient(mList);
mRecyclerView.setAdapter(mAdapter);
}
public static FragmentPatientsByVital newIntance() {
FragmentPatientsByVital f = new FragmentPatientsByVital();
return f;
}
}
Adapter
public class AdapterVitalPatient extends RecyclerView.Adapter<AdapterVitalPatient.ViewHolder> {
private ArrayList<Patient> mList;
public AdapterVitalPatient(ArrayList<Patient> mList) {
this.mList = mList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(InjectUtils.getInflator().inflate(R.layout.adapter_vital_patient, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Patient p = mList.get(position);
holder.mNameTextView.setText(p.getName());
if (mList.get(position).getSummary() != null) {
holder.updateRecords(mList.get(position).getSummary());
} else {
try {
holder.callApi(p.getEmail(), position);
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
return mList.size();
}
public void filterBy(int position) {
switch (position) {
case 0: //!--- Any
break;
case 1: //!--- Normal
break;
case 2: //!--- High
break;
case 3: //!--- Low
break;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final TextView mNameTextView;
private final ProgressBar mProgressBar;
private final GridLayout mTableLayout;
public ViewHolder(View itemView) {
super(itemView);
mNameTextView = (TextView) itemView.findViewById(R.id.textview_title);
mProgressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
mTableLayout = (GridLayout) itemView.findViewById(R.id.table_layout);
}
public void callApi(String email, final int pos) {
try {
RahaDelegates api = InjectUtils.getNetworkObj().create(RahaDelegates.class);
Call<String> call = api.getLatestVitals(String.format(RahaDelegates.GET_LATEST_VITALS, email));
InjectUtils.getNetworkClient().callApi(call, new ApiInterface() {
#Override
public void onResponse(boolean result, String completeResponse) {
Type token = new TypeToken<ArrayList<Vital>>() {
}.getType();
mList.get(getAdapterPosition()).setSummary((ArrayList<Vital>) InjectUtils.getGsonObj().fromJson(completeResponse, token));
updateRecords(mList.get(pos).getSummary());
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(String message) {
mProgressBar.setVisibility(View.GONE);
}
});
} catch (Exception e){
e.printStackTrace();
}
}
public void updateRecords(ArrayList<Vital> details) {
mTableLayout.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mTableLayout.removeAllViews();
for (int i = 0; i < details.size(); i++) {
Log.e("List Size", String.valueOf(details.size()));
Vital v = details.get(i);
if (!v.getVitalName().toLowerCase().contains("lungreco") && !v.getVitalName().toLowerCase().contains("kickco")) {
View view = InjectUtils.getInflator().inflate(R.layout.adapter_home_vital_patient, mTableLayout, false);
mTableLayout.addView(view);
TextView name = (TextView) view.findViewById(R.id.vital_name);
TextView value = (TextView) view.findViewById(R.id.vital_value);
name.setText(v.getVitalName());
if (v.getVitalName().toLowerCase().contains("bodyc")) {
value.setText(v.getFat() + "/" + v.getMuscale() + " " + v.getUnit());
} else if (v.getVitalName().toLowerCase().contains("temp")) {
if (v.getValue() != null) {
value.setText(Math.round(Float.valueOf(v.getValue())) + " " + v.getUnit());
}
} else if (v.getVitalName().toLowerCase().contains("heartra")) {
value.setText(v.getValue());
} else if (v.getVitalName().toLowerCase().contains("etalbe")) {
value.setText(v.getValue() + " " + v.getUnit());
} else if (v.getVitalName().toLowerCase().contains("bloodpres")) {
value.setText(v.getSystolic() + "/" + v.getDiastolic() + " " + v.getUnit());
} else if (v.getVitalName().toLowerCase().contains("loodoxy")) {
value.setText(v.getValue() + " " + v.getUnit());
} else if (v.getVitalName().toLowerCase().contains("oodglucos")) {
value.setText(v.getValue() + " " + v.getUnit());
}
}
}
}
}
}
02-10 09:06:39.430 1600-1600/? E/BoostFramework: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
02-10 09:06:39.476 16831-17154/? E/AndroidCll-SettingsSync: Could not get or parse settings
02-10 09:06:39.547 16831-17062/? E/Appboy v2.5.0 .bo.app.cj: Received server error from request: invalid_api_key
02-10 09:06:39.547 16831-17062/? E/Appboy v2.5.0 .bo.app.ci: Error occurred while executing Braze request: invalid_api_key
02-10 09:06:39.603 16831-17154/? E/AndroidCll-SettingsSync: Could not get or parse settings
02-10 09:06:39.759 1600-1600/? E/BoostFramework: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
02-10 09:06:41.294 16594-16594/sa.digitrends.rahah.doctor E/AndroidRuntime: FATAL EXCEPTION: main
Process: sa.digitrends.rahah.doctor, PID: 16594
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at sa.digitrends.doctor.adapter.AdapterVitalPatient$ViewHolder.updateRecords(AdapterVitalPatient.java:125)
at sa.digitrends.doctor.adapter.AdapterVitalPatient$ViewHolder$1.onResponse(AdapterVitalPatient.java:106)
at sa.app.base.retrofit.client.NetworkClient$1.onResponse(NetworkClient.java:60)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
02-10 09:06:41.761 16831-16831/? E/Referral: (LauncherApplication.java:890) restarted
You can remove below code segment from onBindView and add it inside another method that needs to fire when user do that relevant action
if (mList.get(position).getSummary() != null) {
holder.updateRecords(mList.get(position).getSummary());
} else {
try {
holder.callApi(p.getEmail(), position);
} catch (Exception e) {
e.printStackTrace();
}
}
then you can do notifydatasetchanged after get success response inside that public void onResponse(boolean result, String completeResponse)
It seems you have server error
Appboy v2.5.0 .bo.app.cj: Received server error from request: invalid_api_key 02-10 09:06:39.547 16831-17062/? E/Appboy v2.5.0 .bo.app.ci: Error occurred while executing Braze request: invalid_api_key 02-10 09:06:39.603 16831-17154
Error is due to NullPointerException
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
Update updateRecords methods as below
public void updateRecords(#Nullable ArrayList<Vital> details) {
mProgressBar.setVisibility(View.GONE);
if(details == null) {
return;
}
. . .
. . .
. . .
}
In general there can be further improvement made.
Avoid making API calls directly from Fragments or any Classes having views
Parse response in background thread. Below code might block your main thread for long time, when response is huge.
InjectUtils.getGsonObj().fromJson(completeResponse, token)
Whenever I open the activity Testme in the emulator, it encounters a RuntimeException. The logcat has been posted below:
FATAL EXCEPTION: main
Process: com.learn.earn.earnlearnapp, PID: 6622
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.learn.earn.earnlearnapp/com.learn.earn.earnlearnapp.Testme}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Nothing seems anything wrong with the code. I have spent hours trying to fix this problem. It would be great if you could help me solve this problem. Part of my activity code has been attached below:
public class Testme extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testme);
readQuestions();
}
int qnum = 0;
private List<TopicQuestion> questionsList = new ArrayList<>();
private TextView txtquestion = findViewById(R.id.txtquestion);
private Button answer1 = findViewById(R.id.btnans1);
private Button answer2 = findViewById(R.id.btnans2);
private Button answer3 = findViewById(R.id.btnans3);
private Button answer4 = findViewById(R.id.btnans4);
private boolean correct = false;
private void readQuestions() {
InputStream is = getResources().openRawResource(R.raw.questions);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while (
(line = reader.readLine()) != null) {
//Split the data
String[] tokens = line.split(",");
//Read the data
TopicQuestion question = new TopicQuestion();
question.setTopic(tokens[0]);
question.setQuestion(tokens[1]);
question.setAns1(tokens[2]);
question.setAns2(tokens[3]);
question.setAns3(tokens[4]);
question.setAns4(tokens[5]);
questionsList.add(question);
}
} catch (IOException e) {
Log.wtf("MyActivity","Error reading question file on line" + line, e);
e.printStackTrace();
}
{
}
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
answer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer1.getText().toString());
}
});
answer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns2()).equals(answer2.getText().toString());
}
});
answer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer3.getText().toString());
}
});
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correct = (questionsList.get(qnum).getAns1()).equals(answer4.getText().toString());
}
});
if (correct)
{
qnum +=1;
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
}
else
{
txtquestion.setText(questionsList.get(qnum).getQuestion());
answer1.setText(questionsList.get(qnum).getAns1());
answer2.setText(questionsList.get(qnum).getAns3());
answer3.setText(questionsList.get(qnum).getAns2());
answer4.setText(questionsList.get(qnum).getAns4());
}
}
}
You have to assign the values of the view in OnCreate after the setContentView.
Declare the fields outside:
private TextView ;
private Button; etc..
Place the below lines in OnCreate
txtquestion = findViewById(R.id.txtquestion);
answer1 = findViewById(R.id.btnans1);
answer2 = findViewById(R.id.btnans2);
answer3 = findViewById(R.id.btnans3);
answer4 = findViewById(R.id.btnans4);
Hope it helps!
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm getting a problem when I launch my App. I get this issue, Attempt to invoke a virtual method on a null object reference. I think its Because I didn't create the instance of LoadJobList Correctly but I'm not entirely sure.
Main Activity [EDITED]
public class MainActivity extends AppCompatActivity {
IntDataBaseHelper intDataBaseHelper;
ArrayAdapter<String> mAdapter;
ListView lstJob;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.header);
/// create instance of db helper and jobs
IntDataBaseHelper myhelper = new IntDataBaseHelper(this);
lstJob = (ListView)findViewById(R.id.lstJob);
LoadJobList();
// Create the database (only if it doesn't exists)
// does so by copying from the assets
if (CopyDBFromAssets.createDataBase(this,IntDataBaseHelper.DB_NAME)) {
// Get the data from the database
ArrayList<String> jobs = intDataBaseHelper.getJobList();
for (String s : jobs) {
Log.d("JobList", "Found Job " + s);
}
} else {
throw new RuntimeException("No Usable Database exists or was copied from the assets.");
}
}
// loads job to screen
private void LoadJobList() {
ArrayList<String> Joblist = intDataBaseHelper.getJobList();
if (mAdapter == null) {
mAdapter = new ArrayAdapter<String>(this,R.layout.header,R.id.header);
mAdapter = new ArrayAdapter<>(this,R.layout.row,R.id.BtnComplete);
mAdapter = new ArrayAdapter<>(this, R.layout.row, R.id.Job_name,Joblist);
lstJob.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(Joblist);
mAdapter.notifyDataSetChanged();
}
}
public void JobComplete(View view){
View parent = (View)view.getParent();
TextView taskTextView=(TextView)parent.findViewById(R.id.BtnComplete);
Log.e("String",(String) taskTextView.getText());
}
}
LogCat
[ 10-30 07:24:10.779 1506: 1551 D/]
HostConnection::get() New Host Connection established 0x949247c0, tid 1551
10-30 07:24:11.120 2774-2774/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.joelg.clapp, PID: 2774
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.joelg.clapp/com.example.joelg.clapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.example.joelg.clapp.IntDataBaseHelper.getJobList()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.example.joelg.clapp.IntDataBaseHelper.getJobList()' on a null object reference
at com.example.joelg.clapp.MainActivity.LoadJobList(MainActivity.java:52)
at com.example.joelg.clapp.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
getJobList method
public ArrayList<String> getJobList() {
ArrayList<String> JobList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]
{DB_COLUMN},null,null,null,null,null);
while(cursor.moveToNext()){
int index = cursor.getColumnIndex(DB_COLUMN);
JobList.add(cursor.getString(index));
}
cursor.close();
db.close();
return JobList;
}
DB helper class
package com.example.joelg.clapp;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
/**
* Created by joelg on 22/10/2017.
*/
public class IntDataBaseHelper extends SQLiteOpenHelper{
public static String DB_PATH ="//data/data/com.example.joelg.clapp/databases";
public static final String DB_NAME = "JobList";
private static final String DB_COLUMN = "jobNM";
private static final String DB_TABLE = "job";
public static final String DB_JOB_DETAILS = "jobDetails";
private static final String DB_ISDONE = "jobIsDone";
private SQLiteDatabase JobListDatabase;
private final Context jobContext;
/**
* constructor t
*/
public IntDataBaseHelper (Context context) {
super (context, DB_NAME,null, 1);
this.jobContext = context;
DB_PATH = jobContext.getDatabasePath(DB_NAME).getPath();
}
public void openDataBase() {
// open the database
String JobListPath = DB_PATH;
JobListDatabase = SQLiteDatabase.openDatabase(
JobListPath,null,SQLiteDatabase.OPEN_READONLY);
}
// Getting Job Count
public ArrayList<String> getJobList() {
ArrayList<String> JobList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]
{DB_COLUMN},null,null,null,null,null);
while(cursor.moveToNext()){
int index = cursor.getColumnIndex(DB_COLUMN);
JobList.add(cursor.getString(index));
}
cursor.close();
db.close();
return JobList;
}
// Gets the job state if it has been competed or not
public ArrayList<String> getIsDone() {
ArrayList<String> IsDone = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]{DB_ISDONE},null,null,null,null,null);
while(cursor.moveToFirst()){
int index = cursor.getColumnIndex(DB_ISDONE);
IsDone.add(cursor.getString(index));
}
cursor.close();
db.close();
return IsDone;
}
#Override
public synchronized void close(){
if(JobListDatabase !=null){
JobListDatabase.close();
super.close();
}
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public class MainActivity extends AppCompatActivity {
IntDataBaseHelper intDataBaseHelper;
ArrayAdapter<String> mAdapter;
ListView lstJob;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.header);
/// create instance of db helper and jobs
intDataBaseHelper = new IntDataBaseHelper(this);
lstJob = (ListView)findViewById(R.id.lstJob);
LoadJobList();
// Create the database (only if it doesn't exists)
// does so by copying from the assets
if (CopyDBFromAssets.createDataBase(this,IntDataBaseHelper.DB_NAME)) {
// Get the data from the database
ArrayList<String> jobs = myhelper.getJobList();
for (String s : jobs) {
Log.d("JobList", "Found Job " + s);
}
} else {
throw new RuntimeException("No Usable Database exists or was copied from the assets.");
}
}
// loads job to screen
private void LoadJobList() {
ArrayList<String> Joblist = intDataBaseHelper.getJobList();
if (mAdapter == null) {
mAdapter = new ArrayAdapter<String>(this,R.layout.header,R.id.header);
mAdapter = new ArrayAdapter<>(this,R.layout.row,R.id.BtnComplete);
mAdapter = new ArrayAdapter<>(this, R.layout.row, R.id.Job_name,Joblist);
lstJob.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(Joblist);
mAdapter.notifyDataSetChanged();
}
}
public void JobComplete(View view){
View parent = (View)view.getParent();
TextView taskTextView=(TextView)parent.findViewById(R.id.BtnComplete);
Log.e("String",(String) taskTextView.getText());
}
}
The object called intDataBaseHelper is never initialized, so it is null.
Initialize intDataBaseHelper and use it , like following
So the method will be .
public class MainActivity extends AppCompatActivity {
IntDataBaseHelper intDataBaseHelper;
ArrayAdapter<String> mAdapter;
ListView lstJob;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.header);
/// create instance of db helper and jobs
intDataBaseHelper = new IntDataBaseHelper(this);
lstJob = (ListView)findViewById(R.id.lstJob);
LoadJobList();
// Create the database (only if it doesn't exists)
// does so by copying from the assets
if (CopyDBFromAssets.createDataBase(this,IntDataBaseHelper.DB_NAME)) {
// Get the data from the database
ArrayList<String> jobs = intDataBaseHelper.getJobList();
for (String s : jobs) {
Log.d("JobList", "Found Job " + s);
}
} else {
throw new RuntimeException("No Usable Database exists or was copied from the assets.");
}
}
// loads job to screen
private void LoadJobList() {
ArrayList<String> Joblist = intDataBaseHelper.getJobList();
if (mAdapter == null) {
mAdapter = new ArrayAdapter<String>(this,R.layout.header,R.id.header);
mAdapter = new ArrayAdapter<>(this,R.layout.row,R.id.BtnComplete);
mAdapter = new ArrayAdapter<>(this, R.layout.row, R.id.Job_name,Joblist);
lstJob.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(Joblist);
mAdapter.notifyDataSetChanged();
}
}
public void JobComplete(View view){
View parent = (View)view.getParent();
TextView taskTextView=(TextView)parent.findViewById(R.id.BtnComplete);
Log.e("String",(String) taskTextView.getText());
}
}