How Do I Create A Contact Picker Activity? - java

I'm a novice coder and I've been trying to learn how to code for school in a few days and one thing I like to do is try and deconstruct other code to learn it better. So I was looking at trying to make a contact picker and I found a tutorial online, however, the code does not work, and I don't really understand what the error message means.
My code:
public class ContactActivity extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85500;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
}
public void pickContact(View v)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
* #param data
*/
private void contactPicked(Intent data) {
Button b1 = findViewById(R.id.button);
Button b2 = findViewById(R.id.button2);
Cursor cursor = null;
try {
String phoneNo = null ;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
// Set the value to the textviews
b1.setText(name);
b2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error Message:
08-14 16:25:16.437 3923-3923/com.example.jackson.safetynet E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jackson.safetynet, PID: 3923
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:4780) 
at android.view.View$PerformClick.run(View.java:19866) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Caused by: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
at android.support.v4.app.BaseFragmentActivityApi14.checkForValidRequestCode(BaseFragmentActivityApi14.java:79)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:748)
at com.example.jackson.safetynet.ContactActivity.pickContact(ContactActivity.java:29)
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
at android.view.View.performClick(View.java:4780) 
at android.view.View$PerformClick.run(View.java:19866) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
So I see the line " Caused by: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode " and I think that this is the problem. Is there something with the Result_Pick_Contact or what?
Layout Visual

Try using a smaller positive RESULT_PICK_CONTACT value
private static final int RESULT_PICK_CONTACT = 24;
As specified by this answer
You need to pass a positive number to startActivityForResult.

Related

Android java.lang.NullPointerException error with BroadcastReceiver

Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
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 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:438)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.provatimer.SecondActivity.<init>(SecondActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5256) 
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) 
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.
I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}

Android App crashes when I call onDismissListner

I am trying to update text after a Dialog is dismissed. I am using an OnDismissListner, because the code in my onTextClicked runs only when the textView is clicked, and not when the dialog is dismissed.
public class AddReminder extends AppCompatActivity
{
}
#Override
protected void onCreate(Bundle savedInstanceState) {
//oncreate code
}
public void onDateClick(View view) {
loadMap();
DialogFragment datefragment = new DatePickerFragment();
datefragment.show(getFragmentManager(), "DatePicker");
Dialog dialog = datefragment.getDialog();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
updateText();
}
});
}
public void updateText(){
TextView date = findViewById(R.id.tv_date);
String text =AddReminder.monthmap.get(DatePickerFragment.month)+" "+DatePickerFragment.day+", "+DatePickerFragment.year;
date.setText(text);
TextView time = findViewById(R.id.tv_time);
String tvdate = TimePickerFragment.hour + ":" + TimePickerFragment.min;
time.setText(tvdate);
}
When I to click the textView with the onDateClicked methodcode, the app crashes with the error:
5-21 21:40:06.121 19350-19350/com.zbot473gmail.reminders E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zbot473gmail.reminders, PID: 19350
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
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.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
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 'void android.app.Dialog.setOnDismissListener(android.content.DialogInterface$OnDismissListener)' on a null object reference
at com.zbot473gmail.reminders.AddReminder.onDateClick(AddReminder.java:80)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
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)
 
Is there a better way to run code when the dialog is dismissed? I have tried this, but I really don't understand how to solve it.

App crashes when calling startActivityForResult

I'm working on my first Android app, specifically in this case something to help me cook better. I have 2 activities that I'm currently struggling with, my MainActivity.java and whatCanIMake.java. When I start whatCanIMake from MainActivity using startActivity(intent), I'm able to pass objects using parcelables and generally use whatCanIMake. My issue is that I want to be able to pass back a list of everything that I've changed in my whatCanIMake activity. For example: I pass in a list of all the ingredients I currently have, and then whatCanIMake removes the ingredients that a recipe uses. I'd like to pass back the updated list of remaining ingredients.
The problem I'm having is with startActivityForResult(). Previously I was successfully able to use startActivity(), pass it the intent with the extra parcelables, and Bob's your uncle. When I changed over to startActivityForResult(), the new activity fails to launch, as the app crashes before hitting onCreate(). Obviously this points to my implementation of startActivityForResult(), so I've read basically every stack overflow question related to startActivityForResult() and now I'm here!
My code for starting whatCanIMake is below, as well as the onActivityResult() and corresponding code inside whatCanIMake.
It's just so odd to me that I can simply change out startActivityForResult() for startActivity() and the app works again! Thanks for any help in advance.
MainActivity.java:
public void searchRecipe(View view) {
crossViewVariables.setMakeSort('a');
Intent recipe = new Intent(this, whatCanIMake.class);
recipe.putExtra("Pantry",stock);
recipe.putExtra("Cookbook",activeCookbook);
recipe.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivityForResult(recipe,R.integer.search_by_recipe);
//startActivity(recipe);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case (R.integer.search_by_recipe)://comes from Recipe Search?
if (resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
stock = b.getParcelable("Pantry");
}
if (resultCode == Activity.RESULT_CANCELED) {
}
case (R.integer.search_by_ingredient)://comes from Recipe Search?
if (resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
stock = b.getParcelable("Pantry");
}
if (resultCode == Activity.RESULT_CANCELED) {
}
case (R.integer.make_recipe)://comes from seeRecipe?
if (resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
stock = b.getParcelable("Pantry");
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_LONG).show();
}
case (R.integer.edit_pantry):
if (resultCode == Activity.RESULT_OK) {
Bundle b = data.getExtras();
stock = b.getParcelable("Pantry");
}
}
}
whatCanIMake.java:
Intent result = new Intent();
result.putExtra("Pantry", stock);
setResult(Activity.RESULT_OK,result);
finish();
LogCat:
FATAL EXCEPTION: main
Process: com.example.schre.mememachine, PID: 26721
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5697) 
at android.widget.TextView.performClick(TextView.java:10826) 
at android.view.View$PerformClick.run(View.java:22526) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: android.util.AndroidRuntimeException: FORWARD_RESULT_FLAG used while also requesting a result
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1884)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1545)
at android.app.Activity.startActivityForResult(Activity.java:4283)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4230)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at com.example.schre.mememachine.MainActivity.searchRecipe(MainActivity.java:91)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5697) 
at android.widget.TextView.performClick(TextView.java:10826) 
at android.view.View$PerformClick.run(View.java:22526) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Remove this line:
recipe.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
You do not need it for startActivityForResult(), and it's what is causing your crash.
Instead of:
startActivityForResult(recipe,R.integer.search_by_recipe);
Try this:
startActivityForResult(recipe, getResources().getInteger(R.integer.search_by_recipe));

startActivityForResult force closes my app

I wanted to make two buttons on my main activity to startActivityForResult
Every time I press either of these buttons my app force closes , and I can't figure out why!
Here is the code of the two buttons :
public void billiards (View v)
{
Intent billiards = new Intent(this,Billiards.class);
startActivityForResult(billiards,99710);
}
public void snooker (View v)
{
Intent snooker = new Intent(this,Snooker.class);
startActivityForResult(snooker,99711);
}
Here is the code of Billiards activity :
public void bsave (View v)
{
Double dbgames = Double.parseDouble(ebgames.getText().toString());
Double calcbgames = (dbgames)*0.50;
Double btotal = (calcbgames);
Intent billiards=new Intent();
billiards.putExtra("btot",String.valueOf(btotal));
setResult(99710,billiards);
finish();
}
Here is the code of Snooker Activity :
public void ssave (View v)
{
Double dsgames = Double.parseDouble(esgames.getText().toString());
Double calcsgames = (dsgames)*1.00;
Double stotal = (calcsgames);
Intent snooker=new Intent();
snooker.putExtra("stot",String.valueOf(stotal));
setResult(99710,snooker);
finish();
}
And here is the code of onActivityResult in my MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==99710) {
if (resultCode == RESULT_OK) {
String billiardstot = data.getStringExtra("btot");
String bt = billiardstot;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(BToatal, bt);
editor.commit();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Wrong Request Code", Toast.LENGTH_LONG).show();
}
}
if (requestCode==99711) {
if (resultCode == RESULT_OK) {
String snookertot = data.getStringExtra("stot");
String st = snookertot;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(STotal, st);
editor.commit();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Wrong Result Code", Toast.LENGTH_LONG).show();
}
}
}
Whenever i press on Billiards or Snooker Buttons the app force closes
And here is the LogCat :
08-18 02:11:01.220 11972-11972/cafe.al_sheikhabuhamzehcafe E/AndroidRuntime: FATAL EXCEPTION: main
Process: cafe.al_sheikhabuhamzehcafe, PID: 11972
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
at android.support.v4.app.BaseFragmentActivityEclair.checkForValidRequestCode(BaseFragmentActivityEclair.java:64)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:868)
at cafe.al_sheikhabuhamzehcafe.ItemMenu.billiards(ItemMenu.java:149)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
08-18 02:11:03.043 11972-11972/cafe.al_sheikhabuhamzehcafe I/Process: Sending signal. PID: 11972 SIG: 9
java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
the values you are using for your requestCode are too large
stick to something less than ‭65535‬

How to display passed intent data in a TextView - NullPointerException error

I am making an app to display data from a database into a list view. When an item on the list view is clicked, it takes the user to a new activity where they can view more details about that item. I want to make the details page dynamic to display the details and have managed to show the title of the list view item in a toast.
Now, I am trying to display this by using setText() to show the title in a string but am getting the error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kathe.parenttripapp, PID: 22849
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kathe.parenttripapp/com.example.kathe.parenttripapp.Details}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
this is the class the error occurs at:
TextView titletext;
final List<Activitytable> activityTable = Activitytable.listAll(Activitytable.class);
String data = getIntent().getSerializableExtra("listPosition").toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
TextView titletext = (TextView) findViewById(R.id.titletext);
String data = getIntent().getSerializableExtra("listPosition").toString();
Toast.makeText(getBaseContext(),String.valueOf(data),Toast.LENGTH_LONG).show();
setData();
}
private void setData() {
Intent i = getIntent();
Bundle b = i.getExtras();
if (data != null) {
String j = (String) b.get("listPosition");
titletext.setText(j);
}
else{
titletext.setText("Hello");
}
}
This is the activity it has come from:
final ListView listView = (ListView) findViewById(R.id.viewAll_listview);
long count = Activitytable.count(Activitytable.class);
if(count>0) {
final List<Activitytable> activitytable = Activitytable.listAll(Activitytable.class);
final ViewAllListView madapter = new ViewAllListView(getApplicationContext(), activitytable);
listView.setAdapter(madapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?>parent, View v, int position, long id) {
String title = activitytable.get(position).Title.toString();
Activitytable AT = Activitytable.findById(Activitytable.class,activitytable.get(position).getId());
Intent i = new Intent(getApplicationContext(),Details.class);
i.putExtra("listPosition",title);
startActivity(i);
}
public Object getItem(int position) {return position;}
});
}
else
{
Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);
}
}
What I would like to do is to put the intent data into the TextView 'titletext' and then do an if statement saying if the passed intent data is equal to an activity title then display the following data but can't work out what is going wrong. I have tried using getStringExtra() instead of getSerializableExtra but no such luck. Works on toast but not on TextView.
If you don't have some good understanding of why you are doing so, try not to initialize your variables until you are in onCreate, also to prevent a NullPointerException, it is a good habit to use if (variable != null).
And you are storing an int, so use getIntExtra
TextView titletext;
List<Activitytable> activityTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
activityTable = Activitytable.listAll(Activitytable.class);
titletext = (TextView) findViewById(R.id.titletext);
Intent i = getIntent();
if (i != null) {
String data = i.getStingExtra("listPosition");
titletext.setText(String.valueOf(data));
}
}
In onCreate() and don't do it as a member variable.
Bundle intentBundle = getIntent().getExtras();
if (intentBundle != null) {
lastPosition = getInt( "lastPostion" );
}
The null pointer you are receiving is in the Details class on line 23
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)

Categories

Resources