Android activity is returning null through intent - java

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();
}

Related

Zxing Bar code scanner issue in Android

I am working on a barcode scanner App where on button click in the first Activity, I am moving to the BarcodeScanner Activity where I am importing Zxing library functionalities. Once the scanning is completed, I am moving to a 3rd Activity where I am showing the scanned Results. On clicking a button in the 3rd activity, i am coming back to the 1st activity. For devices having Marshmallow, the code is running fine. But the issue is happening with devices having versions below marshmallow where after going back to the 1st activity from the 3rd Activity, when i am pressing again the button, the scanner activity is appearing but the camera is not starting. It just showing a blank page. Please help. Below I am posting my codes for all 3 Activities.
First Activity:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
ImageView Scan= (ImageView) findViewById(R.id.scanButton);
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstActivity.this.finish();
Intent nextPage= new Intent(FirstActivity.this,MainActivity.class);
startActivity(nextPage);
}
});
ScannerActivity:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Integer response = 0 ;
int currentIndex=0;
Boolean flash=false;
DataBaseHelper dataBaseHelper;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("onCreate", "onCreate");
checkPermissions();
mScannerView = new ZXingScannerView(this);
mScannerView.setResultHandler(this);
boolean cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
if(cam)
{
mScannerView.stopCamera();
}
cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
mScannerView.startCamera();
// FrameLayout frameLayout= new FrameLayout(this);
// FrameLayout.LayoutParams mainParam= new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
// frameLayout.setLayoutParams(mainParam);
// Button scanButton= new Button(this);
dataBaseHelper= new DataBaseHelper(this);
if(dataBaseHelper.checkDataBase()==false)
{
try {
dataBaseHelper.createDataBase();
} catch (IOException e)
{
e.printStackTrace();
}
}
else{
}
Log.d("AnimeshSQL","copy");
dataBaseHelper.openDataBase();
// List<String> data=dataBaseHelper.getQuotes("n",1);
// Log.d("AnimeshSQL",data.get(0).toString());
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// scanButton.setBackground(getResources().getDrawable(R.drawable.round_button));
// scanButton.setText("Flash");
// scanButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if(flash==false)
// {
// flash=true;
//
//
// }
// else
// {
// flash=false;
// }
// mScannerView.setFlash(flash);
// }
// });
// scanButton.setLayoutParams(params);
// frameLayout.addView(mScannerView);
// frameLayout.addView(scanButton);
// setContentView(mScannerView);
checkPermissions();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
}
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
private void checkPermissions() {
try {
for (int i = currentIndex; i < permissions.length; i++) {
currentIndex = currentIndex + 1;
int result = ContextCompat.checkSelfPermission(context, permissions[i]);
if (result == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermission(permissions[i]);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Activity activity = this;
Context context = this;
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private void requestPermission(String permission) {
//
ActivityCompat.requestPermissions(activity, new String[]{permission}, 101);
//
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
checkPermissions();
} else {
try {
// FuncUtils.showToast(context, permissions[0] + " Denied!!!");
} catch (Exception e) {
e.printStackTrace();
}
//
///
}
break;
}
}
#Override
public void onResume() {
super.onResume();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onDestroy() {
super.onDestroy();
mScannerView.stopCamera();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("ani","onrestart");
}
#Override
public void handleResult(Result rawResult)
{
//Some codes to handle the result
Intent intent= new Intent(this,ScanResultActivity.class);
startActivity(intent);
//vbn
mScannerView.stopCamera();
MainActivity.this.finish();
}
}
Final Activity:
public class ScanResultActivity extends AppCompatActivity {
SharedPreferences prefs;
Button ok;
ImageView Hubbell,CI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
prefs = getSharedPreferences("ScanPref", MODE_PRIVATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
//Codes to show the data
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScanResultActivity.this.finish();
Intent nextPage= new Intent(ScanResultActivity.this,FirstActivity.class);
startActivity(nextPage);
}
});
You can write Intent in OnActivityResult.
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}

Retrieve contact from mobile's phone directory

This code can open a built-in contacts directory on a mobile device. However, when I select a contact, the app reports "done", but doesn't retrieve the contact number -- the user can't send a message.
How do I retrieve the contact number? List View is not a solution: I need to return just the one number, not extra information.
Here's my code:
public EditText no;
public EditText msg;
public Button cancel;
public Button snd;
public String Number,name,Message;
public int run=0;
public static final int PICK_CONTACT=1;
public void callContacts(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode,int resultCode,Intent data)
{
super.onActivityResult(reqCode,resultCode,data);
if(reqCode==PICK_CONTACT)
{
if(resultCode== ActionBarActivity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData,null,null,null,null);
if(c.moveToFirst())
{
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_URI.toString()));
Toast.makeText(this,"done",Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
no = (EditText)findViewById(R.id.num);
msg = (EditText)findViewById(R.id.sms);
cancel = (Button)findViewById(R.id.cancel);
snd = (Button)findViewById(R.id.snd);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg.setText("");
no.setText("");
callContacts(null);
}
});
snd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Number = no.toString();
Message = msg.getText().toString();
SmsManager manager = SmsManager.getDefault();
ArrayList<String>long_sms = manager.divideMessage(Message);
manager.sendMultipartTextMessage(Number,null,long_sms,null,null);
Toast.makeText(getApplicationContext(),"Sent Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Here is the code just for selecting one phone number from contact list. i found this code simplest. let me know if there is any problem.
start activity with pick intent on phone data type:
findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
}
});
Now set onAcitivityResult();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
switch (requestCode){
case PICK_CONTACT_REQUEST:
if (resultCode == RESULT_OK){
Uri contactUri = intent.getData();
Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
if (nameCursor.moveToFirst()){
String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
((EditText)findViewById(R.id.person_name)).setText(name);
((EditText)findViewById(R.id.enter_mobile)).setText(number);
nameCursor.close();
}
}
break;
}
}

zxing bar code scanner is not returning results

I am trying to make this app to scan for a book's ISBC and then make a http request to fetch for the book's title and other details.
I got the app working in terms of initiating the camera with rootView.findViewById(R.id.scan_button)..... . Now I want to log the bar code and the code format to make sure it's working in onActivityResult but it's not logging or making a toast. The camera activity closes after the camera focuses on the code and returns to the view where I have the button to initiate the scan function but doesn't log anything or making any toast. I used this tutorial - http://code.tutsplus.com/tutorials/android-sdk-create-a-barcode-reader--mobile-17162 - earlier to see how zXing works and the tutorial worked perfectly and now I'm trying to implement some of the codes.
rootView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.setBeepEnabled(true);
scanIntegrator.setBarcodeImageEnabled(true);
scanIntegrator.setPrompt("Scan a barcode");
scanIntegrator.initiateScan();
}
});
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
Log.i("FORMAT ", scanFormat);
Log.i("CONTENT", scanContent);
Log.i("xZing", "contents: "+scanContent+" format: "+scanFormat);
Toast.makeText(getActivity(), "FORMAT " + scanFormat + " CONTENT " + scanContent, Toast.LENGTH_LONG).show();
}else{
Toast toast = Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
full code
public class AddBook extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "INTENT_TO_SCAN_ACTIVITY";
private EditText ean;
private final int LOADER_ID = 1;
private View rootView;
private final String EAN_CONTENT="eanContent";
private static final String SCAN_FORMAT = "scanFormat";
private static final String SCAN_CONTENTS = "scanContents";
private String mScanFormat = "Format:";
private String mScanContents = "Contents:";
private Button scanBtn;
private TextView formatTxt, contentTxt;
public AddBook(){
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(ean!=null) {
outState.putString(EAN_CONTENT, ean.getText().toString());
}
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_add_book, container, false);
ean = (EditText) rootView.findViewById(R.id.ean);
formatTxt = (TextView)rootView.findViewById(R.id.scan_format);
contentTxt = (TextView)rootView.findViewById(R.id.scan_content);
ean.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//no need
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//no need
}
#Override
public void afterTextChanged(Editable s) {
String ean = s.toString();
//catch isbn10 numbers
if (ean.length() == 10 && !ean.startsWith("978")) {
ean = "978" + ean;
}
if (ean.length() < 13) {
clearFields();
return;
}
//Once we have an ISBN, start a book intent
Intent bookIntent = new Intent(getActivity(), BookService.class);
bookIntent.putExtra(BookService.EAN, ean);
bookIntent.setAction(BookService.FETCH_BOOK);
getActivity().startService(bookIntent);
AddBook.this.restartLoader();
}
});
rootView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.setBeepEnabled(true);
scanIntegrator.setBarcodeImageEnabled(true);
scanIntegrator.setPrompt("Scan a barcode");
scanIntegrator.initiateScan();
}
});
rootView.findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ean.setText("");
}
});
rootView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent bookIntent = new Intent(getActivity(), BookService.class);
bookIntent.putExtra(BookService.EAN, ean.getText().toString());
bookIntent.setAction(BookService.DELETE_BOOK);
getActivity().startService(bookIntent);
ean.setText("");
}
});
if(savedInstanceState!=null){
ean.setText(savedInstanceState.getString(EAN_CONTENT));
ean.setHint("");
}
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
Log.i("FORMAT ", scanFormat);
Log.i("CONTENT", scanContent);
Log.i("xZing", "contents: "+scanContent+" format: "+scanFormat);
Toast.makeText(getActivity(), "FORMAT " + scanFormat + " CONTENT " + scanContent, Toast.LENGTH_LONG).show();
}else{
Toast toast = Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
// Checks for network connection
public boolean checkNetworkConnection(){
ConnectivityManager cm =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
private void restartLoader(){
getLoaderManager().restartLoader(LOADER_ID, null, this);
}
#Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
if(ean.getText().length()==0){
return null;
}
String eanStr= ean.getText().toString();
if(eanStr.length()==10 && !eanStr.startsWith("978")){
eanStr="978"+eanStr;
}
return new CursorLoader(
getActivity(),
AlexandriaContract.BookEntry.buildFullBookUri(Long.parseLong(eanStr)),
null,
null,
null,
null
);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
if (!data.moveToFirst()) {
return;
}
String bookTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.TITLE));
((TextView) rootView.findViewById(R.id.bookTitle)).setText(bookTitle);
String bookSubTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.SUBTITLE));
((TextView) rootView.findViewById(R.id.bookSubTitle)).setText(bookSubTitle);
String authors = data.getString(data.getColumnIndex(AlexandriaContract.AuthorEntry.AUTHOR));
String[] authorsArr = authors.split(",");
((TextView) rootView.findViewById(R.id.authors)).setLines(authorsArr.length);
((TextView) rootView.findViewById(R.id.authors)).setText(authors.replace(",","\n"));
String imgUrl = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.IMAGE_URL));
if(Patterns.WEB_URL.matcher(imgUrl).matches()){
new DownloadImage((ImageView) rootView.findViewById(R.id.bookCover)).execute(imgUrl);
rootView.findViewById(R.id.bookCover).setVisibility(View.VISIBLE);
}
String categories = data.getString(data.getColumnIndex(AlexandriaContract.CategoryEntry.CATEGORY));
((TextView) rootView.findViewById(R.id.categories)).setText(categories);
rootView.findViewById(R.id.save_button).setVisibility(View.VISIBLE);
rootView.findViewById(R.id.delete_button).setVisibility(View.VISIBLE);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {
}
private void clearFields(){
((TextView) rootView.findViewById(R.id.bookTitle)).setText("");
((TextView) rootView.findViewById(R.id.bookSubTitle)).setText("");
((TextView) rootView.findViewById(R.id.authors)).setText("");
((TextView) rootView.findViewById(R.id.categories)).setText("");
rootView.findViewById(R.id.bookCover).setVisibility(View.INVISIBLE);
rootView.findViewById(R.id.save_button).setVisibility(View.INVISIBLE);
rootView.findViewById(R.id.delete_button).setVisibility(View.INVISIBLE);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activity.setTitle(R.string.scan);
}
}
enter code here
The problem is that I was using IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()), which effected on onActivityResult being called at the Activity/Parent level. And since onActivityResult doesn't do anything, nothing happened. And since that I am using fragments, the child/fragment's onActivityResult wasn't being called.
To fix it, I replace IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()) in onClick to IntentIntegrator.forSupportFragment(AddBook.this), with "AddBook.this" in reference to the fragment so onActivityResult in the fragment is called, as opposed to one in Activity. .
:)
Cheers!

NullPointerException in onCreate for Android

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);

Activity not waiting for result

I have an activity called CForm. I would like to call CGForm for result. After i get the result start another activity. The problem is that when i start the details_click method , it executes the CGFORM, but doesn't waits for setting the result in the form, it jumps to the CDFORM.
here is the code for CFORM:
////////////////////////////CForm/////////////////////////
public boolean details_click()
{
if(listview.getCheckedItemPosition()>=0)
{
ArrayList<ComandaClass> listcompos = CClass.C();
int gestiuneId = 0;
if ((configurare.bAlCom) && (listcompos.size() == 0))
{
StocClass.setComandaContextForDB(this);
listGest = StocClass.Gestiuni_Get();
if (listGest.size() > 1)
{
Intent intent = new Intent();
intent.setClass(CForm.this,CGForm.class);
startActivityForResult(intent,GET_CODE);//here i would like to get back the result from CGForm
dGeid=getGIdResult;
}
}
boolean tof = true;
if ((configurare.bGCom) && (gestiuneId == -1))
tof = false;
if (tof)
{
dCid=listCom.get(listview.getCheckedItemPosition()).getCId();
dClid=listCom.get(listview.getCheckedItemPosition()).getClId();
dF=listCom.get(listview.getCheckedItemPosition()).getF();
Intent intent = new Intent();
intent.setClass(CForm.this,CDForm.class);
startActivity(intent);
}
return true;
}
else
{
Toast.makeText(this, "X", 5000).show();
return false;
}
}
public static int getGIdResult=-1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == GET_CODE)
{
if (resultCode == RESULT_OK)
{
getGIdResult=data.getIntExtra("GIdResult",-1);
}
else
{
getGIdResult=-1;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
CGFORM code:
////////////////////CGForm//////////////////
public class CGForm extends Activity
{
public static ArrayList<StocClass> listG=null;
public static int gid;
ListView listview=null;
Button btnOK=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.comenzigestiuni);
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
listview=(ListView)findViewById(R.id.listViewDG);
listG = CForm.listGest;
CG_Load();
}//oncreate
private void CG_Load()
{
//..adding data to listview
btnOK=(Button)findViewById(R.id.menuItemOk);
btnOK.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (listview.getCheckedItemPosition() >= 0)
{
gestiuneid = listG.get(listview.getCheckedItemPosition()).getGId();
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
finish();
}
}
});
}//CG_Load
#Override
protected void onStop()
{
gestiuneid=-1;
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
super.onStop();
}
}
thanks advanced !
Neither startActivity() nor startActivityForResult() are blocking calls. Anything that is supposed to be done after you receive the result needs to move to your onActivityResult() method.

Categories

Resources