So I am trying to pass data from my HomePage.class(my main activity) to my ContactHelper class but it just seems to crash.
This is the code that crashes the app:
Context context = view.getContext();
Intent i = new Intent(context, ContactHelper.class);
i.putExtra("name", displayName);
i.putExtra("phone", phone);
i.putExtra("email", contactEmail);
i.putExtra("amount", Amount);
i.putExtra("curDate", CurDate);
i.putExtra("dueDate", DueDate);
i.putExtra("curTime", TimeCur);
i.putExtra("timeDue", TimeDue);
//on below line we are starting a new activity,
context.startActivity(i);
Which is inside my getContacts function:
@SuppressLint("Range")
private void getContacts(View view) {
// this method is use to read contact from users device.
// on below line we are creating a string variables for
// our contact id and display name.
String contactId = "";
String displayName = "";
String phone = "";
String contactEmail = "";
String Amount = "0";
String CurDate = "11111111";
String DueDate = "99999999";
String TimeCur = "0";
String TimeDue = "0";
// on below line we are calling our content resolver for getting contacts
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME " ASC");
// on blow line we are checking the count for our cursor.
if (cursor.getCount() > 0) {
// if the count is greater than 0 then we are running a loop to move our cursor to next.
while (cursor.moveToNext()) {
// on below line we are getting the phone number.
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
// we are checking if the has phone number is > 0
// on below line we are getting our contact id and user name for that contact
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// on below line we are calling a content resolver and making a query
Cursor phoneCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID " = ?",
new String[]{contactId},
null);
// on below line we are moving our cursor to next position.
if (phoneCursor.moveToNext()) {
// on below line we are getting the phone number for our users and then adding the name along with phone number in array list.
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsModalArrayList.add(new ContactsModal(displayName, phoneNumber));
}
// on below line we are closing our phone cursor.
phoneCursor.close();
}
}
Context context = view.getContext();
Intent i = new Intent(context, ContactHelper.class);
i.putExtra("name", displayName);
i.putExtra("phone", phone);
i.putExtra("email", contactEmail);
i.putExtra("amount", Amount);
i.putExtra("curDate", CurDate);
i.putExtra("dueDate", DueDate);
i.putExtra("curTime", TimeCur);
i.putExtra("timeDue", TimeDue);
//on below line we are starting a new activity,
context.startActivity(i);
}
// on below line we are closing our cursor.
cursor.close();
// on below line we are hiding our progress bar and notifying our adapter class.
loadingPB.setVisibility(View.GONE);
contactRVAdapter.notifyDataSetChanged();
}
I am trying to pass the intent to the class below to a function named getContactInfo:
package com.example.myan;
import android.app.AlertDialog;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ContactHelper extends AppCompatActivity {
static Context context;
static String number;
static String newName;
static String newNumber;
public static Cursor getContactCursor(ContentResolver contactHelper,
String startsWith) {
String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor cur = null;
try {
if (startsWith != null && !startsWith.equals("")) {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
" like \"" startsWith "%\"", null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
" ASC");
} else {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
" ASC");
}
cur.moveToFirst();
} catch (Exception e) {
e.printStackTrace();
}
return cur;
}
public void getContactInfo(View view) {
Intent intent = getIntent();
String getName = intent.getStringExtra("name");
String getPhone = intent.getStringExtra("phone");
String getEmail = intent.getStringExtra("email");
String getAmount = intent.getStringExtra("amount");
String getCurDate = intent.getStringExtra("curDate");
String getDueDate = intent.getStringExtra("dueDate");
String getCurTime = intent.getStringExtra("curTime");
String getTimeDue = intent.getStringExtra("timeDue");
Integer getFirstDate4thValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getCurDate).charAt(3)));
Integer getFirstDate3rdValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getCurDate).charAt(2)));
String getFirstDateNumber = String.valueOf(getFirstDate3rdValue) String.valueOf(getFirstDate4thValue);
Integer getSecondDate4thValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getDueDate).charAt(3)));
Integer getSecondDate3rdValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getDueDate).charAt(2)));
String getSecondDateNumber = String.valueOf(getSecondDate3rdValue) String.valueOf(getSecondDate4thValue);
if (Integer.valueOf(String.valueOf(intent.getStringExtra(getAmount))) > 0) {
view.findViewById(R.id.txtfront).setVisibility(View.VISIBLE);
}
if (Integer.valueOf(String.valueOf(intent.getStringExtra(getAmount))) == 0) {
view.findViewById(R.id.txtfront).setVisibility(View.GONE);
}
if (Integer.valueOf(getFirstDateNumber) != Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtDueToday).setVisibility(View.GONE);
}
if (Integer.valueOf(getFirstDateNumber) == Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.GONE);
view.findViewById(R.id.txtDueToday).setVisibility(View.VISIBLE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(intent.getStringExtra(getName) " owes you $" intent.getStringExtra(getAmount) ".00 today at " intent.getStringExtra(getTimeDue) " O'Clock.");
alertDialogBuilder.setIcon(R.drawable.ic_launcher_background);
alertDialogBuilder.setTitle("MYAN");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (Integer.valueOf(getFirstDateNumber) > Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.VISIBLE);
view.findViewById(R.id.txtDueToday).setVisibility(View.GONE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(intent.getStringExtra(getName) " is late and has owed you on " intent.getStringExtra(getDueDate) " and owes you $" intent.getStringExtra(getAmount) ".00");
alertDialogBuilder.setIcon(R.drawable.myanlogo);
alertDialogBuilder.setTitle("MYAN");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (Integer.valueOf(getFirstDateNumber) < Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.GONE);
}
}
public static long getContactID(ContentResolver contactHelper,
String phone) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phone));
String[] projection = { PhoneLookup._ID };
Cursor cursor = null;
try {
cursor = contactHelper.query(contactUri, projection, null, null,
null);
if (cursor.moveToFirst()) {
int personID = cursor.getColumnIndex(PhoneLookup._ID);
return cursor.getLong(personID);
}
return -1;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return -1;
}
public static void deleteContact(ContentResolver contactHelper,
String number) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String[] args = new String[] { String.valueOf(getContactID(
contactHelper, number)) };
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
.withSelection(RawContacts.CONTACT_ID "=?", args).build());
try {
contactHelper.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
}
Why would it be crashing?
My ultimate goal here is to have objects in my ContactsRVAdapter to become visible and not visible, and also text change, like current date and time.
[This is the FloatingActionButton which I am trying to manipulate][1] Which is in a RecyclerView
But I cant seem to reach the items in my FloatingActionButton(ContactsRVAdapter) in any way.
Here is my ContactsRVAdapter class:
package com.example.myan;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.net.URISyntaxException;
import java.util.ArrayList;
class ContactRVAdapter extends RecyclerView.Adapter<ContactRVAdapter.ViewHolder> {
public static final String CHANNEL_1="CHANNEL1";
// creating variables for context and array list.
private Context context;
private ArrayList<ContactsModal> contactsModalArrayList;
private ContentResolver contactHelper;
private String number;
private TextView contactLate;
private View view;
private Intent intent;
// creating a constructor
public ContactRVAdapter(Context context, ArrayList<ContactsModal> contactsModalArrayList) {
this.context = context;
this.contactsModalArrayList = contactsModalArrayList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// passing our layout file for displaying our card item
try {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.contacts_rv_item, parent, false));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
// below method is use for filtering data in our array list
public void filterList(ArrayList<ContactsModal> filterlist) {
// on below line we are passing filtered
// array list in our original array list
contactsModalArrayList = filterlist;
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// getting data from array list in our modal.
ContactsModal modal = contactsModalArrayList.get(position);
// on below line we are setting data to our text view.
holder.contactTV.setText(modal.getUserName());
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getRandomColor();
// below text drawable is a circular.
TextDrawable drawable2 = TextDrawable.builder().beginConfig()
.width(100) // width in px
.height(100) // height in px
.endConfig()
// as we are building a circular drawable
// we are calling a build round method.
// in that method we are passing our text and color.
.buildRound(modal.getUserName().substring(0, 1), color);
// setting image to our image view on below line.
holder.contactIV.setImageDrawable(drawable2);
// on below line we are adding on click listener to our item of recycler view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line we are opening a new activity and passing data to it.
Intent i = new Intent(context, ContactDetailActivity.class);
i.putExtra("name", modal.getUserName());
i.putExtra("contact", modal.getContactNumber());
//on below line we are starting a new activity,
context.startActivity(i);
}
});
}
@Override
public int getItemCount() {
return contactsModalArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView contactLate;
public ImageView txtFront;
// on below line creating a variable
// for our image view and text view.
private ImageView contactIV;
private TextView contactTV;
private ImageView btnDeleteContact;
private ImageView textDueToday;
private Intent intent;
private String getName;
private String getPhone;
private String getEmail;
private String getAmount;
private String getCurDate;
private String getDateDue;
private String getCurTime;
private String getDueTime;
public ViewHolder(@NonNull View itemView) throws URISyntaxException {
super(itemView);
// initializing our image view and text view.
contactIV = itemView.findViewById(R.id.idIVContact);
contactTV = itemView.findViewById(R.id.idTVContactName);
//contactLate = itemView.findViewById(R.id.txtLate);
//txtFront = itemView.findViewById(R.id.txtfront);
//textDueToday = itemView.findViewById(R.id.txtDueToday);
}
}
}
So all I am trying to do is make it to where I can manipulate the objects inside ContactsRVAdapter class which is a Floating action button.
And my Logcat
FATAL EXCEPTION: main
Process: com.example.myan, PID: 1719
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myan/com.example.myan.HomePage}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3645)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
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:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at com.example.myan.HomePage.getContacts(HomePage.java:286)
at com.example.myan.HomePage.access$200(HomePage.java:39)
at com.example.myan.HomePage$4.onPermissionsChecked(HomePage.java:159)
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.example.myan.HomePage.requestPermissions(HomePage.java:187)
at com.example.myan.HomePage.onCreate(HomePage.java:69)
at android.app.Activity.performCreate(Activity.java:8305)
at android.app.Activity.performCreate(Activity.java:8284)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1417)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3626)
CodePudding user response:
Check the datatypes of the data that you are parsing in Another activities. It should be parcelable or serializable.
CodePudding user response:
try this code...
Intent i = new Intent(this, ContactHelper.class);
The crash is in your view
. You are passing view of an activity, which doesn't exist or has been finished.
Context context = view.getContext();
In this function, pass context of existing activity.
private void getContacts(View view) {
...
}