NullPointerException in onCreate for Android - java

so I'm making a pretty simple class organizer for students and I am getting a nullPointerException in the onCreate for the Add Class activity. I really don't know why I'm getting this. Any help would be appreciated!
Here's the MainActivity:
public class MainActivity extends Activity {
ListView classList;
Button addClass;
ArrayAdapter<Class> adapterClass;
ArrayList<Class> currClasses = new ArrayList<Class>();
ClassesSingleton myClasses;
int REQUEST_CODE_ADD = 318;
int REQUEST_CODE_EDIT = 319;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
classList = (ListView) findViewById(R.id.classList);
final Context context = this;
adapterClass = new ArrayAdapter<Class>(this, R.layout.single_list_item, R.id.label, currClasses);
classList.setAdapter(adapterClass);
addClass = (Button) this.findViewById(R.id.addClass);
classList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <?> arg0, View view, int position, long id){
Intent intent = new Intent(MainActivity.this, ShowClass.class);
startActivityForResult(intent, REQUEST_CODE_EDIT);
}
});
addClass.setOnClickListener(new OnClickListener() {
public void onClick(View arg0){
Intent intent = new Intent(MainActivity.this, AddClass.class);
startActivityForResult(intent, REQUEST_CODE_ADD);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUEST_CODE_ADD){
Class newClass = new Class();
if(data.hasExtra("className")){
newClass.setName(data.getExtras().getString("name"));
}
if(data.hasExtra("number")){
newClass.setNumber(data.getExtras().getInt("number"));
}
if(data.hasExtra("students")){
ArrayList<Student> s = data.getExtras().getParcelableArrayList("students");
newClass.setStudents(s);
}
myClasses = ClassesSingleton.getInstance();
updateClassList(newClass);
myClasses.setClassArray(currClasses);
}
else if(resultCode == RESULT_OK && requestCode == REQUEST_CODE_EDIT){
}
}
public void updateClassList(Class n){
adapterClass = null;
currClasses.add(n);
adapterClass = new ArrayAdapter<Class>(this, R.layout.single_list_item, R.id.label, currClasses);
classList.setAdapter(adapterClass);
adapterClass.notifyDataSetChanged();
}
}
Here's the second Activity:
public class AddClass extends Activity{
Button addStudent, saveClass, cancelClass;
EditText className, classNumber;
ListView studentList;
ArrayAdapter<Student> adapterStudent;
ArrayList<Student> currStudents = new ArrayList<Student>();
int REQUEST_CODE_ADDSTU = 317;
int REQUEST_CODE_EDSTU = 316;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.new_class);
addStudent = (Button) findViewById(R.id.addStudent);
saveClass = (Button) findViewById(R.id.confirmClassAdd);
className = (EditText) findViewById(R.id.newClassName);
classNumber = (EditText) findViewById(R.id.newClassNumber);
studentList = (ListView) findViewById(R.id.newStudentList);
adapterStudent = new ArrayAdapter<Student>(this, R.layout.single_list_item, R.id.label, currStudents);
studentList.setAdapter(adapterStudent);
studentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <?> arg0, View view, int position, long id){
Intent intent2 = new Intent(AddClass.this, EditStudent.class);
startActivityForResult(intent2, REQUEST_CODE_EDSTU);
}
});
addStudent.setOnClickListener(new OnClickListener() {
public void onClick(View arg0){
Intent intent2 = new Intent(AddClass.this, AddStudent.class);
startActivityForResult(intent2, REQUEST_CODE_ADDSTU);
}
});
saveClass.setOnClickListener(new OnClickListener() {
public void onClick(View arg0){
Intent data = new Intent();
int numData = 0;
if((className.getText() != null) && (classNumber.getText() != null) && (currStudents.isEmpty() != true)){
String nameData = className.getText().toString();
String numStr = classNumber.getText().toString();
ArrayList students = currStudents;
boolean intTrue = true;
try{
numData = Integer.parseInt(numStr);
}catch(NumberFormatException e){
Toast.makeText(AddClass.this, "Please be sure to enter a numberic value in the number field.", Toast.LENGTH_LONG).show();
intTrue = false;
}
if(intTrue){
data.putExtra("className", nameData);
data.putExtra("number", numData);
data.putParcelableArrayListExtra("students", students);
setResult(RESULT_OK, data);
finish();
}
}
else{
Toast.makeText(AddClass.this, "Don't leave your class name or number field blank!", Toast.LENGTH_LONG).show();
}
}
});
}
//onActivityResult callback
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUEST_CODE_ADDSTU){
Student newStudent = new Student();
if(data.hasExtra("name")){
newStudent.setName(data.getExtras().getString("name"));
}
if(data.hasExtra("id")){
newStudent.setId(data.getExtras().getInt("id"));
}
updateStudentList(newStudent);
}
}
public void updateStudentList(Student s){
adapterStudent = null;
currStudents.add(s);
adapterStudent = new ArrayAdapter<Student>(this, R.layout.single_list_item, R.id.label, currStudents);
studentList.setAdapter(adapterStudent);
adapterStudent.notifyDataSetChanged();
}
}
Here's the stack trace:
FATAL EXCEPTION: main
Process: com.example.congelassign2, PID: 1654
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.congelassign2/com.example.congelassign2.AddClass}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.access$700(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4998)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.congelassign2.AddClass.onCreate(AddClass.java:55)
at android.app.Activity.performCreate(Activity.java:5243)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
... 11 more
Edit: I added the reference to the saveClass button (which was a stupid mistake, thanks guys), but I'm still getting the same error at the same line...

You have not assigned anything to saveClass button so it is null
saveClass.setOnClickListener(new OnClickListener() {
this statement is resulting in NullPointerException.
You should have assigned it something like this:
saveClass = (Button) findViewById(R.id.saveClass);
Hope this helps.

You need to grab a reference to the saveClass button as well (and likely cancelClass at some point too), which should be something like:
addStudent = (Button) findViewById(R.id.addStudent);
saveClass = (Button) findViewById(R.id.saveClass);
cancelClass = (Button) findViewById(R.id.cancelClass);

Related

Try to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to make a barcode scanner app, and I want to add scan results to a certain list. In the MainActivity, I have a certain button that should send me to MyList activity, but then the app crashes and I don't know how to solve it.
So here is my code:
public class MainActivity extends AbsRuntimePermission implements ZXingScannerView.ResultHandler{
private ZXingScannerView zXingScannerView;
private static final int REQUEST_PERMISSION = 10;
boolean ok = false, chk = false;
private String scanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chk = getIntent().getBooleanExtra("check", chk);
if(chk) {
chk = false;
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
public void scan(View view){
requestAppPermissions(new String[]{Manifest.permission.CAMERA}, R.string.msg, REQUEST_PERMISSION);
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
#Override
public void onPermissionGranted(int requestCode) {
if(ok)
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
}
#Override
public void onResume(){
super.onResume();
if(ok)
{
if(zXingScannerView == null)
{
zXingScannerView = new ZXingScannerView(this);
setContentView(zXingScannerView);
}
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
#Override
protected void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
scanResult = result.getText();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
zXingScannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("GO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(scanResult));
startActivity(intent);
}catch (Exception ex)
{
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, scanResult);
startActivity(intent);
}
}
});
builder.setNegativeButton("Add to list", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, MyList.class);
intent.putExtra("CODE", scanResult);
startActivity(intent);
}
});
builder.setMessage(scanResult);
AlertDialog alert = builder.create();
alert.show();
}
public void Lista(View view){
Intent iNtent = new Intent(MainActivity.this, MyList.class);
startActivity(iNtent);
}
}`
And this is my error report:
01-12 09:42:26.013 2670-2670/com.example.tchibo.justqr E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tchibo.justqr, PID: 2670
java.lang.RuntimeException: Unable to pause activity {com.example.tchibo.justqr/com.example.tchibo.justqr.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null object reference at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3976)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3942)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3916)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3890)
at android.app.ActivityThread.-wrap15(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1605)
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 'void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null object reference
Actually, it says that is trying to invoke virtual method void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera() on a null object reference.
(sorry for the post style but i'm not familiar with it)
Well you create method scan(View view) in this method you initialize your camera(ZXingScannerView ) object but din't call anywhere. have look for solution
in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chk = getIntent().getBooleanExtra("check", chk);
zXingScannerView = new ZXingScannerView(getApplicationContext());
if(chk) {
chk = false;
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
in onPause()
#Override
protected void onPause() {
super.onPause();
if(zXingScannerView!=null)
zXingScannerView.stopCamera();
}
You can check zXingScannerView before using it.
if (zXingScannerView != null){
zXingScannerView.stopCamera();
}
java.lang.RuntimeException: Unable to pause activity
{com.example.tchibo.justqr/com.example.tchibo.justqr.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null
object reference
the logcat is telling you the problem, which is this line :
zXingScannerView.stopCamera();
your app is trying to stop something that does not exist !!
trivial solution :
if(zXingScannerView!=null){
zXingScannerView.stopCamera();
}

Error while transfer data from 2nd activity

I have 2 Activity.
FirstActivity with 1 textView and 1 button, and
MainActivity with 4 checkBoxes, 1 textView and 1 button.
First Activity is the first activity which app show to user.
Layouts of my activities
On the FirstActivity i want to check how many checboxes are checked in the textView.
On the MainActivity all working fine, we can select checkboxes and textView show how many is checked. Adittionaly, state of checkboxes and state of textView is save into SharedPreference.
Now i describe my problem, i dont know how to show currently numbers of checked boxes in 1st activity in my app after launch.
I tried to use onActivityResult but i think i do this wrong, and this my button2 with double intent must be also wrong.
What i should fix here and how ?
I paste here code of my 2 Activities:
FirstActivity :
public class FirstActivity extends AppCompatActivity {
private static final String SHARED_PREFS_NAME = "abc";
private Button b1;
private TextView tv2;
private int number;
public static final int REQUEST_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
b1 = (Button)findViewById(R.id.b1);
tv2 = (TextView)findViewById(R.id.tv2) ;
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
tv2.setText(""+number);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
int number = data.getExtras().getInt("number");
tv2.setText(""+number);
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
}
}
}
private void saveNumberToSharedPrefs(int num){
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); //Create and store this instance in onCreate method of activity, or use it like this.
preferences.edit().putInt("NUMBER", num).apply(); // Use constant value for key
}
}
MainActivity :
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private int numberOfTrue;
private TextView tv1;
private CheckBox cb1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox cb2,cb3,cb4;
Button b2;
b2 = (Button)findViewById(R.id.b2);
tv1 = (TextView)findViewById(R.id.tv1);
cb1 = (CheckBox)findViewById(R.id.cb1);
cb1.setChecked(getFromSP("cb1"));
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.cb2);
cb2.setChecked(getFromSP("cb2"));
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.cb3);
cb3.setChecked(getFromSP("cb3"));
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.cb4);
cb4.setChecked(getFromSP("cb4"));
cb4.setOnCheckedChangeListener(this);
loadVariable();
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
});
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private void saveVariable(int numberOfTrue){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key2", numberOfTrue);
editor.commit();
}
private void loadVariable(){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
int number = sharedPref.getInt("key2", 0);
tv1.setText(""+number);
numberOfTrue=number;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.cb1:
saveInSp("cb1",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb2:
saveInSp("cb2",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb3:
saveInSp("cb3",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb4:
saveInSp("cb4",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
}
saveVariable(numberOfTrue);
loadVariable();
}
}
This one if definitely wrong.
Intent intent = new Intent(MainActivity.this, FirstActivity.class);
intent.putExtra("number", numberOfTrue);
startActivityForResult(intent,1);
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
You need to left only second part of code. Like this:
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
And start your MainActivity like this:
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE); // This change is important.
And then do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
number = getIntent().getExtras().getInt("number");
}
}
This way you'll receive number from MainActivity when it'll be closed. But if you want to read this value on FirstActivity start (without going to MainActivity, you need to store checked number in shared preferences and then get value in onCreate() method of FirstActivity.
Write into SharedPreferences in onActivityResult to insure that only "saved" checks will be saved.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
}
}
private void saveNumberToSharedPrefs(int num){
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); //Create and store this instance in onCreate method of activity, or use it like this.
preferences.edit().putInt("NUMBER", num).apply(); // Use constant value for key
}
And then you can load your checked number in onCreate method of FirstActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
}
Update
Here you'r trying to get number from intent in onActivityResult. That's wrong, this way you'll always have number = 0 (default value). On activity result doesn't fill data into intent. All your data is in data variable passed in method.
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
You need to leave only this:
if (requestCode == REQUEST_CODE) { //also you need to check if result is RESULT_OK
number = data.getExtras().getInt("number");
tv2.setText(""+number);
saveNumberToSharedPrefs(number);
}
FirstActivity
Store values :
Intent intent = new Intent(getBaseContext(), Activity.class);
intent.putExtra("ID", sessionId);
startActivity(intent);
SecondActivity
Fetching Values:
String s = getIntent().getStringExtra("ID");
public static final int REQUEST_CODE = 100;
change on FirstActivity.java
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
add onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
Log.d("TAG","------"+data.getExtras().getInt("number"));
int number = data.getExtras().getInt("number");
tv2.setText(""+number);
}
}
}
change on MainActivity.java
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("TAG","------"+numberOfTrue);
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
});

Taking index of a string

Hello I have an edittext and an button.
I want when the user enters a number by pressing the number to be taken and put a bet on the index penultimate number.
Basically, what should I do? Thank you.
I try to do this with the following code:
public class BarcodScanner extends AppCompatActivity implements OnClickListener {
private Button scanBtn;
private Button nextLevel;
private EditText formatTxt, contentTxt;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scanner);
scanBtn = (Button)findViewById(R.id.scan_button);
nextLevel =(Button)findViewById(R.id.btn_enter);
textView = (TextView) findViewById(R.id.view1);
formatTxt = (EditText) findViewById(R.id.scan_format);
contentTxt = (EditText) findViewById(R.id.scan_content);
nextLevel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String inn = formatTxt.getText().toString();
int length_s = inn.length();
char m = inn.charAt(length_s - 2);
if ( m == 1){
Toast.makeText(BarcodScanner.this, "قبض آب",Toast.LENGTH_LONG).show();
}
}
});
scanBtn.setOnClickListener(this);
}
public void onClick(View v){
if(v.getId()==R.id.scan_button){
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
if (scanContent != null) {
formatTxt.setText(scanContent.substring(0, 13));
contentTxt.setText(scanContent.substring(18));
}
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}

Android activity is returning null through intent

Not sure why I keep getting a null reference when I am trying to return data to Main activity from another activity (done through Intents). I've tried to Serialize everything, and tried other stuff. I don't know what may be causing it. Can some one point out my mistake?
Here is the error I keep getting:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=10, result=0, data=null} to activity {ebadly.com.youstreamer/ebadly.com.youstreamer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
Here is the code in my MainActivity class:
public static final int PICK_CONTACTS = 10;
public ArrayList<Contact> mSendPhoneNumbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSendPhoneNumbers = new ArrayList<Contact>();
Button contactsButton = (Button)findViewById(R.id.select_contacts_button);
contactsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ContactsListActivity.class);
i.putExtra(ContactsListActivity.EXTRA, mSendPhoneNumbers);
startActivityForResult(i, PICK_CONTACTS);
}
});
Button enterButton = (Button)findViewById(R.id.enter_button);
enterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
enter code here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mSendPhoneNumbers = (ArrayList<Contact>)data.getSerializableExtra(ContactsListActivity.EXTRA);
}
Here is code from my ContactsListActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_list);
mSendPhoneNumbers = new ArrayList<Contact>();
mSendPhoneNumbers = (ArrayList<Contact>) getIntent().getSerializableExtra(EXTRA);
mContacts = new ArrayList<Contact>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext())
{
Contact c = new Contact();
c.mName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
c.mNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
mContacts.add(c);
}
phones.close();
if(!mSendPhoneNumbers.isEmpty() || mSendPhoneNumbers != null){
for(Contact c : mSendPhoneNumbers){
if(c.mChecked == true){
for(Contact search: mContacts){
if(search.mNumber.equals(c.mNumber)){
search.mChecked = true;
}
}
}
}
}
mContactsList = (ListView) findViewById(R.id.contact_list);
mContactsList.setAdapter(new ContactListViewAdapter(mContacts));
mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Contact c = (Contact) parent.getAdapter().getItem(position);
if(c.mChecked == true) c.mChecked = false;
else c.mChecked = true;
}
});
}
#Override
public void onBackPressed(){
super.onBackPressed();
for(Contact addContact: mContacts){
if (addContact.mChecked){
for(Contact search : mSendPhoneNumbers){
if(search.mNumber.equals(addContact.mNumber)){
break;
}else mSendPhoneNumbers.add(addContact);
}
}
}
Intent i = new Intent();
Log.d("HEREEE === ", mSendPhoneNumbers.toString());
i.putExtra(EXTRA, mSendPhoneNumbers);
setResult(RESULT_OK, i);
finish();
}

Activity called outside the tab

I am developing an app with 5 tabs and my last tab displays a list of menus. The problem appears when I click a menu tab, the menu activity appears nicely below my tab but when I click any of the menus (which it will call LoginActivity), the new Activity appears full screen not under the tab. How can I handle this? Below is my code.
TabActivity
package com.smartag.smarttreasure;
public class NfcSurveyActivity extends TabActivity {
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
mTechLists);
int profileCount = db.getContactsCount();
if (profileCount <= 0) {
Intent intent = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int profileCount = db.getContactsCount();
if (profileCount <= 0) {
Intent intent1 = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent1);
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
tabToDisplay = extras.getString("tab");
if (tabToDisplay.equals("CAMERA")) {
barcodeData = extras.getString("barcodeData");
}
extras.clear();
}
TabHost tabHost = getTabHost();
// Home
TabSpec tbspecHome = tabHost.newTabSpec("Home");
tbspecHome.setIndicator("",
getResources().getDrawable(R.drawable.tab_account_style));
Intent iHome = new Intent(this, HomeActivity.class);
tbspecHome.setContent(iHome);
tabHost.addTab(tbspecHome);
// History
tabHost.addTab(tabHost
.newTabSpec("Fun")
.setIndicator("",
getResources().getDrawable(R.drawable.tab_fun_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
if (tabToDisplay != null && tabToDisplay.equals("REDEEM")) {
if (barcodeData != null && barcodeData.length() > 0) {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra("autoLoadBarcodeData",
barcodeData)));
}
else {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
}
} else {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
}
// tabHost.setCurrentTab(2);
tabHost.getTabWidget().getChildAt(2).getLayoutParams().height = tabHost
.getTabWidget().getChildAt(2).getLayoutParams().height + 19;
// Search
TabSpec tbspecSearch = tabHost.newTabSpec("Finder");
tbspecSearch.setIndicator("",
getResources().getDrawable(R.drawable.tab_finder_style));
Intent iSearch = new Intent(this, NfcSurveyActivity.class);
tbspecSearch.setContent(iSearch);
tabHost.addTab(tbspecSearch);
// Profile
TabSpec tbspecProfile = tabHost.newTabSpec("Quit");
tbspecProfile.setIndicator("",
getResources().getDrawable(R.drawable.tab_quit_style));
Intent iProfile = new Intent(this, NfcSurveyActivity.class);
tbspecProfile.setContent(iProfile);
tabHost.addTab(tbspecProfile);
for (int i = 0; i <= 4; i++) {
tabHost.getTabWidget()
.getChildTabViewAt(i)
.setBackgroundColor(
getResources()
.getColor(android.R.color.transparent));
if (i == 2) {
tabHost.getTabWidget()
.getChildTabViewAt(i)
.setPadding(
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingLeft(),
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingTop(),
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingRight(), 20);
}
}
if (tabToDisplay != null && tabToDisplay.length() > 0) {
if (tabToDisplay.equals("CAMERA")) {
tabHost.setCurrentTab(2);
} else if (tabToDisplay.equals("HISTORY")) {
tabHost.setCurrentTab(1);
}
}
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
NfcSurveyConfiguration.SelectedTab = tabId;
}
});
}
}
MenuActivity
public class HomeActivity extends ListActivity {
static final String[] Account = new String[] { "Point History", "Scan History",
"Reward/Coupon History", "Share/Transfer History", "Personalise" };
String tabToDisplay = "";
String barcodeData = "";
SharedPreferences nfcSurveyConfiguration;
String profileId;
String pleaseWait = "";
protected boolean _taken;
protected File _directory;
protected String _filename;
protected String _fileExtension;
String profileName = "";
String profileEmail = "";
String profileStatus = "";
String profileLanguage = "";
String profileType = "";
DatabaseHandler db = new DatabaseHandler(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
R.layout.listview_item_row, Account));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
//Toast.makeText(getApplicationContext(),
// ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent1); // This activity appears not in the tab
}
});
}
#Override
public void onPause() {
super.onPause();
NfcSurveyConfiguration.CurrentActiveTab = 0;
}
}
Any suggestion or advice is highly appreciated.
this code inside setOnItemClickListener help me to solve the problem.
View view1 = getLocalActivityManager().startActivity(
"ReferenceName",
new Intent(getApplicationContext(),
YourActivityClass.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
setContentView(view1);

Categories

Resources