Issues storing data into Parse - Using TextView - java

I have received the following unexpected error while trying to run my activity:
Invalid type for value: class android.widget.TextView
Essentially I am trying to store data into Parse.com, where a user would select their calendar date and time through button clicks, and where the date and time selected would be recorded and shown into two TextViews that is displayed to them (Date and Time). Now I want to grab the TextViews information and record it into parse.
Below is the logcat message:
09-16 16:58:25.510: E/AndroidRuntime(1542): FATAL EXCEPTION: main
09-16 16:58:25.510: E/AndroidRuntime(1542): Process: com.dooba.beta, PID: 1542
09-16 16:58:25.510: E/AndroidRuntime(1542): java.lang.IllegalArgumentException: invalid type for value: class android.widget.TextView
09-16 16:58:25.510: E/AndroidRuntime(1542): at com.parse.ParseObject.put(ParseObject.java:2696)
09-16 16:58:25.510: E/AndroidRuntime(1542): at com.parse.ParseUser.put(ParseUser.java:404)
09-16 16:58:25.510: E/AndroidRuntime(1542): at com.dooba.beta.ScheduleMatchOptionActivity$1.onClick(ScheduleMatchOptionActivity.java:55)
09-16 16:58:25.510: E/AndroidRuntime(1542): at android.view.View.performClick(View.java:4438)
09-16 16:58:25.510: E/AndroidRuntime(1542): at android.view.View$PerformClick.run(View.java:18422)
09-16 16:58:25.510: E/AndroidRuntime(1542): at android.os.Handler.handleCallback(Handler.java:733)
09-16 16:58:25.510: E/AndroidRuntime(1542): at android.os.Handler.dispatchMessage(Handler.java:95)
09-16 16:58:25.510: E/AndroidRuntime(1542): at android.os.Looper.loop(Looper.java:136)
09-16 16:58:25.510: E/AndroidRuntime(1542): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-16 16:58:25.510: E/AndroidRuntime(1542): at java.lang.reflect.Method.invokeNative(Native Method)
09-16 16:58:25.510: E/AndroidRuntime(1542): at java.lang.reflect.Method.invoke(Method.java:515)
09-16 16:58:25.510: E/AndroidRuntime(1542): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-16 16:58:25.510: E/AndroidRuntime(1542): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-16 16:58:25.510: E/AndroidRuntime(1542): at dalvik.system.NativeStart.main(Native Method)
Below is the Activity code
public class ScheduleMatchOptionActivity extends Activity implements
OnClickListener {
protected TextView mCalendarDate;
protected TextView mCalendarTime;
Button btnCalendar, btnTimePicker;
TextView txtDate, txtTime;
private int mYear, mMonth, mDay, mHour, mMinute;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.match_schedule);
txtDate = (TextView) findViewById(R.id.txtDate);
txtTime = (TextView) findViewById(R.id.txtTime);
Button mConfirm2 = (Button)findViewById(R.id.btnConfirmSchedule);
mConfirm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseUser currentUser = ParseUser.getCurrentUser();
// Create the class and the columns
currentUser.saveInBackground();
currentUser.put("ActivityDate", txtDate);
currentUser.put("ActivityTime", txtTime);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
}
else {
}
}
});
}
});
btnCalendar = (Button) findViewById(R.id.btnCalendar);
btnTimePicker = (Button) findViewById(R.id.btnTimePicker);
txtDate = (TextView) findViewById(R.id.txtDate);
txtTime = (TextView) findViewById(R.id.txtTime);
btnCalendar.setOnClickListener(this);
btnTimePicker.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == btnCalendar) {
// Process to get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Dialog
DatePickerDialog dpd = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// Display Selected date in textbox
txtDate.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
dpd.show();
}
if (v == btnTimePicker) {
// Process to get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
txtTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
tpd.show();
}
}
}
If you require any additional information, or clarification, let me know.

currentUser.put("ActivityDate", txtDate);
currentUser.put("ActivityTime", txtTime);
Above two lines require ("key",value) pair.As you are passing only the TextView widget its causing exception.
Replace your line with these
currentUser.put("ActivityDate", txtDate.getText().toString());
currentUser.put("ActivityTime", txtTime.getText().toString());
EDIT
For Validation of your textView do this in your onclick method:
mConfirm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(txtDate.getText().toString().length()>0 && txtTime.getText().toString().length() >0 ){
ParseUser currentUser = ParseUser.getCurrentUser();
// Create the class and the columns
currentUser.saveInBackground();
currentUser.put("ActivityDate", txtDate);
currentUser.put("ActivityTime", txtTime);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
}
else {
}
}
});
}else{
Toast t = t.makeText(context,"Please fill all the details !",Toast.Length_LONG);
t.setGravity(Gravity.center,0,0);
t.show();
}
});

Related

FatalCrash when I click on a Button

I have this RemoteCar App which has the Buttons,
"LOCK" -> leads you to another Acitivity.
"LOCATION" -> leads you to another Activity.
"START ENGINE" -> Lets you click on it and it changes the txt into
"ENGINE RUNNING".
"REFUEL" -> lets you refuel and increments my ProgressBar(FuelBar).
So the problem I have is that I can't click on START ENGINE or REFUEL anymore since the App keeps crashing for reasons I can not resolve, yet. I can easily click on LOCATION and LOCK those work perfectly fine.
Here I have the ErrorMessage:
05-21 13:39:52.887 1869-1869/? W/gralloc_ranchu: Gralloc pipe failed 05-21 13:39:52.897 1869-1869/? D/OpenGLRenderer: Enabling debug mode 0 05-21 13:39:53.097 1402-1429/system_process I/ActivityManager: Displayed com.example.schwarzerritter.remotecv02/.MainActivity: +546ms 05-21 13:39:53.297 1402-1429/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread) 05-21 13:39:56.857 1402-1486/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory) 05-21 13:42:00.387 1869-1869/? D/AndroidRuntime: Shutting down VM 05-21 13:42:00.387 1869-1869/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6661228) 05-21 13:42:00.387 1869-1869/? E/AndroidRuntime: FATAL EXCEPTION: main
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:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NumberFormatException: Invalid int: "AC : 18"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4084) 
at android.view.View$PerformClick.run(View.java:16966) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511)
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
public ProgressBar fuelBar;
public Button lockButton;
public Button engButton;
public Button refuelButton;
public Button plusButton;
public Button minusButton;
public Button locationButton;
public SeekBar seekBarButton;
public TextView seekText;
int incFuel = 0;
int acNum = 0;
public void onClick(View v) {
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
acNum = Integer.parseInt(seekText.getText().toString());
switch (v.getId()) {
case engB:
if (engButton.getText() == "ENGINE RUNNING") {
engButton.setText("START ENGINE");
} else {
if (fuelBar.getProgress() > 0) {
Toast.makeText(MainActivity.this,"Starting engine..",Toast.LENGTH_SHORT).show();
engButton.setText("ENGINE RUNNING");
if (fuelBar.getProgress() >= 10) {
incFuel = fuelBar.getProgress();
incFuel -= 10;
fuelBar.setProgress(incFuel);
if (fuelBar.getProgress() < 100)
refuelButton.setText("REFUEL");
}
} else
if(fuelBar.getProgress() == 0) {
Toast.makeText(MainActivity.this, "No fuel", Toast.LENGTH_SHORT).show();
engButton.setText("EMPTY GASTANK");
}else
engButton.setText("START ENGINE");
}
break;
case refuelB:
if (fuelBar.getProgress() == 0) {
engButton.setText("START ENGINE");
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else if (fuelBar.getProgress() < 100) {
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else {
Toast.makeText(MainActivity.this,"Tank is full",Toast.LENGTH_SHORT).show();
refuelButton.setText("FULL");
}
break;
}
}
public void seek_bar(){
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekText.setText("AC : " + (seekBarButton.getProgress() + 18));
seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNum;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressNum = progress;
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
});
}
public void lockPage() {
lockButton = (Button) findViewById(R.id.lockB);
lockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
startActivity(lockPage);
}
});
}
public void locationPage() {
locationButton = (Button) findViewById(R.id.locationB);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent locationPage = new Intent(MainActivity.this, location.class);
startActivity(locationPage);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = (Button) findViewById(R.id.locationB);
lockButton = (Button) findViewById(R.id.lockB);
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
fuelBar.setMax(100);
fuelBar.setProgress(30);
refuelButton.setText(R.string.refuelB);
lockButton.setText(R.string.lockB);
locationButton.setText(R.string.locationB);
engButton.setText(R.string.engB);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
int acNum;
seek_bar();
lockPage();
locationPage();
}
}
java.lang.NumberFormatException: Invalid int: "AC : 18"
at com.example.schwarzerritter.remotecv02.MainActivity.onClick(MainActivity.java:41)
You are trying to convert the string AC : 18 to an integer in MainActivity.java line 41.
(Reading error messages helps)

My simple "counter app" crashes when trying to move to another activity...why?

When trying to move to another activity the app crashes...
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{myact.julianhernandez.com.counterapp/myact.julianhernandez.com.counterapp.CounterDisplay}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:244)
at android.widget.TextView.setText(TextView.java:3888)
at myact.julianhernandez.com.counterapp.CounterDisplay.onCreate(CounterDisplay.java:31)
at android.app.Activity.performCreate(Activity.java:5231)
MainActivity.class Code
public class MainActivity extends AppCompatActivity {
Button moveActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moveActivity = (Button) findViewById(R.id.list1_button);
moveActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toCounter = new Intent(MainActivity.this , CounterDisplay.class);
startActivity(toCounter);
}
});
CounterDisplay.class Code
public class CounterDisplay extends AppCompatActivity {
private TextView countView;
private Button addButton;
private Button subtractButton;
//int initialCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter_display);
countView = (TextView) findViewById(R.id.currentCount);
addButton = (Button) findViewById(R.id.add);
subtractButton = (Button) findViewById(R.id.subtract);
countView.setText(0);
//increment counter by 1
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentCount;// = initialCount;
for(currentCount=0;currentCount>=0;currentCount++){
countView.setText(currentCount);
}
}
});
}
}
Why does this code crash when switching activities?
Textview.setText(int) method takes a resource ID, not the text you are trying to display. Because there are no resource strings matching the ID you pass in (which is 0 on line 31), an exception gets thrown.
There are additional overloads of the setText() method that allow you to pass in a char[] if you don't want to use resource strings. View the documentation for more information. http://developer.android.com/reference/android/widget/TextView.html

DatePicker and TimePicker crash when I press the Set button

I am making a messenger that has date and time pickers pop up when I click the button. When I press the Set button to display them, the app crashes. My code is:
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
yearSet = year;
monthSet = monthOfYear + 1;
daySet = dayOfMonth;
btnDate.setText(yearSet + monthSet + daySet);
}
};
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
hourSet = hour;
minuteSet = minute;
btnTime.setText(hourSet + minuteSet);
}
};
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x7f4
at android.content.res.Resources.getText(Resources.java:1068)
at android.widget.TextView.setText(TextView.java:4546)
at devncode.kemo.testApp.SendMessageActivity$3.onDateSet(SendMessageActivity.java:95)
at android.app.DatePickerDialog.tryNotifyDateSet(DatePickerDialog.java:199)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java:154)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:185)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Your problem is that you are setting text of different items as integers.. For example btn.setText(int); where it should be a string btn.setText(String);
So to fix it, wherever you have something like
btnTime.setText(hourSet + minuteSet);
change it to
btnTime.setText(hourSet + minuteSet + "");
Adding the + "" will cast it as a String and not give an error.

java.lang.RuntimeException: Unable to start activity ComponentInfo{..}java.lang.NullPointerException

I want to add some data to sqlite dy fragmnet.but when i Run the code it gives this error..
java.lang.RuntimeException: Unable to start activity ComponentInfo{codes.project.sameera.o_project/codes.project.sameera.o_project.Indi_Add_Details_menu}: java.lang.NullPointerException
i can add data to sqlite by this code without using Fragment.but when i convert my class into Fragmnet this happen.
How Can i fix this..?
this is my Fragment_addStudentDetails class
public class Fragment_addStudentDetails extends Fragment implements View.OnClickListener {
EditText fName,mName, Address, sName, hNo, mNo, presentSpo;
DatabaseAdapter databaseHelper;
Button btnAdd;
Button btnView;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_add_student_details,container,false);
fName=(EditText) view.findViewById(R.id.editTextfname);
mName=(EditText) view.findViewById(R.id.editTextmName);
Address = (EditText) view.findViewById(R.id.editTextAdd);
sName = (EditText) view.findViewById(R.id.editTextsure);
hNo = (EditText) view.findViewById(R.id.editTexttpH);
mNo = (EditText) view.findViewById(R.id.editTextTPM);
presentSpo = (EditText) view.findViewById(R.id.editTextPS);
btnAdd = (Button) view.findViewById(R.id.btnAdd);
btnView = (Button) view.findViewById(R.id.btnView);
btnAdd.setOnClickListener(this);
btnView.setOnClickListener(this);
databaseHelper = new DatabaseAdapter(getActivity());
return view;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAdd:
addStudent(view);
break;
case R.id.btnView:
viewDetails(view);
break;
default:
break;
}
}
public void addStudent(View view){
String fname = fName.getText().toString();
String mname = mName.getText().toString();
String sname = sName.getText().toString();
String address = Address.getText().toString();
String TPhome = hNo.getText().toString();
String TPmobile = mNo.getText().toString();
String presentsport = presentSpo.getText().toString();
long id= databaseHelper.insertData(fname, mname, sname, address, TPhome, TPmobile, presentsport);
if(id<0){
Message.message(getActivity(),"Error inInsertiong Data");
}else
{
Message.message(getActivity(),"Succecsfuly inserted to data");
}
}
public void viewDetails(View view){
String data = databaseHelper.getAllData();
Message.message(getActivity(),data);
}
}
log cat
java.lang.RuntimeException: Unable to start activity ComponentInfo{codes.project.sameera.o_project/codes.project.sameera.o_project.Indi_Add_Details_menu}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at codes.project.sameera.o_project.Fragment_addStudentDetails.onCreateView(Fragment_addStudentDetails.java:38)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.Activity.performStart(Activity.java:5240)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
           
btnAdd is null which results in the NullPointerException in btnAdd.setOnClickListener(this). This is because the fragment_add_student_details layout contains no View with the btnAdd id.

Implementing Getextra() and Putextra

I am trying to use putextra() and getextra() but my program is crashing after implementing it
Go through my code and let me know my mistake
If I am not using getextra() and putextra() the code is working flawlessly
This is 1st class from where I am getting the value
public class Assess extends ListActivity {
String itm;
ArrayAdapter<String> Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setBackgroundResource(R.drawable.background);
Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getResources()
.getStringArray(R.array.English));
setListAdapter(Adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
selectItem(pos);
itm = getListView().getItemAtPosition(pos).toString();
// Toast.makeText(getApplicationContext(), "CLicked",
// Toast.LENGTH_SHORT).show();
}
});
}
public void selectItem(int pos) {
switch (pos) {
case 0: {
Intent i;
List<Question> questions = getQuestionSetFromDb();
// Initialise Game with retrieved question set ///
GamePlay c = new GamePlay();
c.setQuestions(questions);
c.setNumRounds(getNumQuestions());
((ChuckApplication) getApplication()).setCurrentGame(c);
// Start Game Now.. //
i = new Intent(this, QuestionActivity.class);
**i.putExtra("itemname", itm);**
//startActivityForResult(i, Constants.PLAYBUTTON);
startActivity(i);
//this.finish();
break;
}
}
}
Now the Second class where I am trying to Pass the item name
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
topic1 = i.getStringExtra("itemname");
Log.i("sanket", topic1);
/**
* Configure current game and get question
*/
currentGame = ((ChuckApplication) getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
RadioGroup rdgb = (RadioGroup) findViewById(R.id.group1);
rdgb.setOnCheckedChangeListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current
* games current question
*/
private void setQuestions() {
// set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion()) + "?";
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
// set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
}
/*
* #Override public void onClick(View arg0) { //Log.d("Questions",
* "Moving to next question");
*//**
* validate a checkbox has been selected
*/
/*
* if (!checkAnswer()) return;
*//**
* check if end of game
*/
/*
* if (currentGame.isGameOver()){ //Log.d("Questions",
* "End of game! lets add up the scores.."); //Log.d("Questions",
* "Questions Correct: " + currentGame.getRight()); //Log.d("Questions",
* "Questions Wrong: " + currentGame.getWrong()); Intent i = new
* Intent(this, EndgameActivity.class); startActivity(i); finish(); } else{
* Intent i = new Intent(this, QuestionActivity.class); startActivity(i);
* finish(); } }
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (a > 0) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
return true;
}
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it has then check if its
* correct and update gamescore
*/
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer == null) {
// Log.d("Questions", "No Checkbox selection made - returning");
return false;
} else {
// Log.d("Questions",
// "Valid Checkbox selection made - check if correct");
if (currentQ.getAnswer().equalsIgnoreCase(answer)) {
// Log.d("Questions", "Correct Answer!");
currentGame.incrementRightAnswers();
} else {
// Log.d("Questions", "Incorrect Answer!");
currentGame.incrementWrongAnswers();
}
return true;
}
}
/**
*
*/
public String getSelectedAnswer() {
RadioButton c1 = (RadioButton) findViewById(R.id.answer1);
RadioButton c2 = (RadioButton) findViewById(R.id.answer2);
RadioButton c3 = (RadioButton) findViewById(R.id.answer3);
RadioButton c4 = (RadioButton) findViewById(R.id.answer4);
if (c1.isChecked()) {
return c1.getText().toString();
}
if (c2.isChecked()) {
return c2.getText().toString();
}
if (c3.isChecked()) {
return c3.getText().toString();
}
if (c4.isChecked()) {
return c4.getText().toString();
}
return null;
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
// Log.d("Questions", "Moving to next question");
a++;
/**
* validate a checkbox has been selected
*/
if (!checkAnswer())
return;
/**
* check if end of game
*/
if (currentGame.isGameOver()) {
// db.open();
// db.insertOptions(topic1, currentGame.getRight(), month);
// Log.d("Questions", "End of game! lets add up the scores..");
// Log.d("Questions", "Questions Correct: " +
// currentGame.getRight());
// Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
// db.close();
} else {
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
}
Or is there any other way to carry data from one page to other page other than putextra() and getextra().
Here is my LOGCAT
02-04 10:33:35.697: E/AndroidRuntime(1776): FATAL EXCEPTION: main
02-04 10:33:35.697: E/AndroidRuntime(1776): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tmm.android.chuck/com.tmm.android.chuck.QuestionActivity}: java.lang.NullPointerException: println needs a message
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.os.Handler.dispatchMessage(Handler.java:99)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.os.Looper.loop(Looper.java:130)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-04 10:33:35.697: E/AndroidRuntime(1776): at java.lang.reflect.Method.invokeNative(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): at java.lang.reflect.Method.invoke(Method.java:507)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-04 10:33:35.697: E/AndroidRuntime(1776): at dalvik.system.NativeStart.main(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): Caused by: java.lang.NullPointerException: println needs a message
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.util.Log.println_native(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.util.Log.i(Log.java:158)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.tmm.android.chuck.QuestionActivity.onCreate(QuestionActivity.java:48)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-04 10:33:35.697: E/AndroidRuntime(1776): ... 11 more
Try out to get the string as below :
First change your onItemClickListener as below: You need to assign value to your itm variable and then call the selectItem() method so that your itm variable is not null.
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
itm = getListView().getItemAtPosition(pos).toString();
selectItem(pos);
}
});
Get the String in your another activity as below:
String topic1 =getIntent().getStringExtra("itemname");
first initialize the itm String in OnItemClickListener implementation of ListView, then call selectItem() method.
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
itm = getListView().getItemAtPosition(pos).toString(); // initialize it first.
selectItem(pos);
// Toast.makeText(getApplicationContext(), "CLicked",
// Toast.LENGTH_SHORT).show();
}
});
and in reeiving Activity, get this String as
topic1 = getIntent().getStringExtra("itemname");
You should read string from getIntent(). Read like below
topic1 = getIntent().getStringExtra("itemname");
It must be a NullPointerException because "itm" will always be null in that scope
Why don't you make it like this:
itm = getListView().getItemAtPosition(pos).toString();
selectItem(pos,itm);
And then pass it as extra in this method
Hope that helps :)

Categories

Resources