I have one textView value that the can be changed using a plus and minus button. (like androids number picker object but custom.)
I need to be able to extract each value and save if depending on a spinner value that is set by the user.
For each value that is saved for each spinner position, when the user returns to the same position on the spinner, the previous value entered will appear indicating a value has already been entered.
For Instance:(If spinner is the day of the week)(value is the TextView/custom Spinner) "If the user selects Wednesday, and picks a value of 7, then goes to Monday and picks 8, if the user returns to Wednesday the value entered before (7) will show, if the user returns to Monday the value 8 will show.
Spinner code
final Spinner spinner1 = (Spinner) findViewById(R.id.sp_dotw);
final ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this, R.array.dotw_array, R.layout.custom_spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner1position = position;
spinnerPos();
showToast("spinnerdotw: position= " + position + "id=" + id);
}
public void onNothingSelected(AdapterView<?> adapterView) {
showToast("No Dotw selected");
}
});
Number picker code
#Override
public void onClick(View v) {
String getString = String.valueOf(tvSony.getText());
int current1 = Integer.parseInt(getString);
if (v == btnUp1) {
if (current1 < nEnd) {
current1++;
tvSony.setText(String.valueOf(current1));
}
}
if (v == btnDown1) {
if (current1 > nStart) {
current1--;
tvSony.setText(String.valueOf(current1));
}
}
sonyRs = current1;
}
Any Suggestions on how to do this would be highly appreciated ?
My Attempt So far:
SharedPreferences sp = getSharedPreferences("sun32save", MODE_PRIVATE);
SharedPreferences.Editor spedit = sp.edit();
if (spinner1position == 0 & spinner2position == 0) {
spedit.putString("sun32Son", String.valueOf(sonyRs));
String savedValue1 = sp.getString("sun32Son", "");
spedit.commit();
tvSony.setText(savedValue1);
}
//if a value is found, display value
if (spinner1position == 0 & spinner2position == 1) {
spedit.putString("sun35Son", String.valueOf(sonyRs));
String savedValue2 = sp.getString("sun35Son", "");
spedit.commit();
tvSony.setText(savedValue2);
This returns the default value 0 if i go back to the same spinner position.
Screenshot
Edit Error
06-01 18:37:51.503 18264-18264/com.example.liam.quickreport20 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.liam.quickreport20, PID: 18264
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.liam.quickreport20/com.example.liam.quickreport20.UnitsForm}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object com.example.liam.quickreport20.UnitsForm$Cache.get(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object com.example.liam.quickreport20.UnitsForm$Cache.get(java.lang.Object)' on a null object reference
at com.example.liam.quickreport20.UnitsForm.loadTextFields(UnitsForm.java:220)
at com.example.liam.quickreport20.UnitsForm.onCreate(UnitsForm.java:152)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
Related
This question already has answers here:
android.content.res.Resurces$NotFoundException : String resource ID #0x0 [duplicate]
(2 answers)
Closed 3 years ago.
I am converting JSON data from a server to String and storing in an ArrayList so that I can display the data on a separate activity page. With my string values, this is working perfectly fine. However, when I try with my integer values, my app crashes with a fatal error.
This is my loop to convert the JSON data to strings and add to Array.
for (int i=0; i < jsonArray.length(); i++) {
String make = jsonArray.getJSONObject(i).get("make").toString();
String model = jsonArray.getJSONObject(i).get("model").toString();
String reg = jsonArray.getJSONObject(i).get("license_number").toString();
int year = Integer.parseInt(jsonArray.getJSONObject(i).get("year").toString());
int price = Integer.parseInt(jsonArray.getJSONObject(i).get("price").toString());
String colour = jsonArray.getJSONObject(i).get("colour").toString();
int number_doors = Integer.parseInt(jsonArray.getJSONObject(i).get("number_doors").toString());
String transmission = jsonArray.getJSONObject(i).get("transmission").toString();
int mileage = Integer.parseInt(jsonArray.getJSONObject(i).get("mileage").toString());
String fuel_type = jsonArray.getJSONObject(i).get("fuel_type").toString();
int engine_size = Integer.parseInt(jsonArray.getJSONObject(i).get("engine_size").toString());
String body_style = jsonArray.getJSONObject(i).get("body_style").toString();
String condition = jsonArray.getJSONObject(i).get("condition").toString();
String notes = jsonArray.getJSONObject(i).get("notes").toString();
Vehicle V = new Vehicle(make,model, year, price, reg, colour, number_doors, transmission, mileage, fuel_type,engine_size, body_style, condition, notes);
vehicleArrayList.add(V);
}
I then have an on click listener so when an object is selected it will take you to another activity with fully populated details on each vehicle.
vehicleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), DetailsActivity.class);
intent.putExtra("license_number", vehicleArrayList.get(position));
startActivity(intent);
}
});
And this is the code in my DetailsActivity.class that clicking on an object should take you to.
Bundle extras = getIntent().getExtras();
Vehicle vehicle = (Vehicle) extras.get("license_number");
System.out.println("received from the intent: " + vehicle.getLicense_number());
TextView reg = findViewById(R.id.vecReg);
TextView make = findViewById(R.id.make);
TextView model = findViewById(R.id.model);
// TextView year = findViewById(R.id.year);
// TextView price = findViewById(R.id.price2);
TextView colour = findViewById(R.id.colour2);
TextView transmission = findViewById(R.id.transmission2);
// TextView mileage = findViewById(R.id.mileage2);
TextView fuel = findViewById(R.id.fuel2);
// TextView engine = findViewById(R.id.engine2);
// TextView doors = findViewById(R.id.doors2);
TextView body = findViewById(R.id.body2);
TextView condition = findViewById(R.id.condition2);
TextView notes = findViewById(R.id.notes2);
reg.setText(vehicle.getLicense_number());
make.setText(vehicle.getMake());
model.setText(vehicle.getModel());
// year.setText(vehicle.getYear());
// price.setText(vehicle.getPrice());
colour.setText(vehicle.getColour());
transmission.setText(vehicle.getTransmission());
// mileage.setText(vehicle.getMileage());
fuel.setText(vehicle.getFuel_type());
// engine.setText(vehicle.getEngine_size());
// doors.setText(vehicle.getNumber_doors());
body.setText(vehicle.getBody_style());
condition.setText(vehicle.getCondition());
notes.setText(vehicle.getNotes());
As you can see, I have commented out the integer values as whenever I have not commented them out, I receive the fatal error. This is from my logcat.
03-28 12:40:56.959 16172-16172/com.example.vehicledatabaseapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vehicledatabaseapp, PID: 16172
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vehicledatabaseapp/com.example.vehicledatabaseapp.DetailsActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x7df
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7df
at android.content.res.Resources.getText(Resources.java:299)
at android.widget.TextView.setText(TextView.java:4132)
at com.example.vehicledatabaseapp.DetailsActivity.onCreate(DetailsActivity.java:42)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
03-28 12:40:59.856 16172-16172/com.example.vehicledatabaseapp I/Process: Sending signal. PID: 16172 SIG: 9
The line "com.example.vehicledatabaseapp.DetailsActivity.onCreate(DetailsActivity.java:42)" is referring to the line "year.setText(vehicle.getYear());"
you have to convert your int value to String before set it to TextView.
year.setText(String.valueOf(vehicle.getYear()))
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My code is below, I'm thinking it has something to do with my if / else statement. Essentially I want to make sure there is at least one radio button in a group checked before I open the next page. Once this works, I'll set it up so that if one of the radiobuttons in the group isn't checked then It will display an error message.
public void onClickListenerButton() {
radioGroup_gender = (RadioGroup) findViewById(R.id.radioGroup_gender);
radioGroup_course = (RadioGroup) findViewById(R.id.radioGroup_course);
button_splits = (Button)findViewById(R.id.button_splits);
button_splits.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.idealsplit.admin.idealsplit.ResultsActivity");
int selectedID_gender = radioGroup_gender.getCheckedRadioButtonId();
int selectedID_course = radioGroup_course.getCheckedRadioButtonId();
radioButton_gender = (RadioButton) findViewById(selectedID_gender);
radioButton_course = (RadioButton) findViewById(selectedID_course);
CharSequence gender, courseType, age, event, time;
if (selectedID_gender == -1) {
//Throw Error
isNull = true;
} else if (selectedID_course == -1) {
//Throw Error
isNull = true;
} else {
courseType = radioButton_course.getText();
gender = radioButton_gender.getText();
startActivity(intent);
}
}
}
);
}
And here is the logcat:
03-01 08:52:22.060 19234-19234/com.idealsplit.admin.idealsplit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.idealsplit.admin.idealsplit, PID: 19234
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.idealsplit.admin.idealsplit/com.idealsplit.admin.idealsplit.ResultsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.idealsplit.admin.idealsplit.ResultsActivity.onCreate(ResultsActivity.java:96)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Thanks for any and all help with this, if more information was needed let me know!
**If it helps I was following this youtube tutorial: https://www.youtube.com/watch?v=3f0NAn5xFy4
It looks like button_splits is null so (Button)findViewById(R.id.button_splits); is returning null.
Ensure that view R.id.button_splits exists.
Your view that is attached to this activity must have a button on it with the id of 'button_splits'.
What is a Null Pointer Exception
also you can stop this NPE happening by ensuring the button is not null before adding the listener, but if the button is null then this will not add the listener.
if (button_splits != null) {
button_splits.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.idealsplit.admin.idealsplit.ResultsActivity");
int selectedID_gender = radioGroup_gender.getCheckedRadioButtonId();
int selectedID_course = radioGroup_course.getCheckedRadioButtonId();
radioButton_gender = (RadioButton) findViewById(selectedID_gender);
radioButton_course = (RadioButton) findViewById(selectedID_course);
CharSequence gender, courseType, age, event, time;
if (selectedID_gender == -1) {
//Throw Error
isNull = true;
} else if (selectedID_course == -1) {
//Throw Error
isNull = true;
} else {
courseType = radioButton_course.getText();
gender = radioButton_gender.getText();
startActivity(new Intent(getApplicationContext(), ResultsActivity.class));
startActivity(intent);
}
}
}
);
}
I have two Activities
1. List view (multiple items each with title and link)
2. Text View( when click on any item in list view, fetches the link, do xml parsing and fetch the content and displayed)
I used intent to switch from List view to text view activity. Now on first time click, it start the text view activity. On pressing devices back button, it goes again to List view. Uptil now it's all right.
The main problem is that when the second time , i click on any item in List view, Android App gives me error of "Unfortunately application has stopped" .
and On clicking "OK" , it displayed the content of second item. and when second time , i pressed back button , application got closed
Here is my Second activity
public class ColoumnView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coloumn_view);
Intent intent = getIntent();
String message = intent.getStringExtra(MainListActivity.EXTRA_MESSAGE);
TextView myColoumnView = (TextView)findViewById(R.id.ColoumnView);
myColoumnView.setText(message);
}
#Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed();
finish();
}
Here is the part of my first activity where it is creating an intent
protected void onPostExecute(List<ContentGetter.Content> contents) {
if (contents != null && mException == null) {
for(int i=0; i<contents.size();i++) {
if(contents.get(i).summary != null )
{
summaryContent= contents.get(i).summary;
}
else {
continue;
}
Intent intent = new Intent(MainListActivity.this,ColoumnView.class);
intent.putExtra(EXTRA_MESSAGE, summaryContent);
startActivity(intent);
Log.d(TAG, contents.get(i).summary != null ? contents.get(0).summary : "NULL");
}
} else {
if (mException instanceof IOException){
} else if (mException instanceof XmlPullParserException) {
}
}
}
Edit: Here is the crash Log
11-01 13:11:46.274 2296-2296/com.example.talha.appforblog E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.talha.appforblog, PID: 2296
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at com.example.talha.appforblog.MainListActivity$DownloadXmlTaskContent.onPostExecute(MainListActivity.java:241)
at com.example.talha.appforblog.MainListActivity$DownloadXmlTaskContent.onPostExecute(MainListActivity.java:206)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The problem is in line no 241 of activity MainListActivity. You are calling a print there which is not having a proper msg to print for time being comment that line. If you share the line of code in that line that would help me narrow it down
Looks like this is doing it...
Log.d(TAG, contents.get(i).summary != null ? contents.get(0).summary : "NULL");
Ensure that your log message is not null, in this case, contents.get(0).summary.
The problem is as follows. I have a login activity (in Android Studio) which worked fine a few days before. I don't remember changing anything but when I run this one the previous time the app closed right after I clicked the login button. The last thing indicated was the toast about pre-execution of AsyncTask.
And I can't understand why there could be a NullPointerException.
I have almost the same code for my signup activity and it works fine.
Here is the log:
05-28 16:04:52.395 1218-1232/system_process V/WindowManager﹕ addAppToken: AppWindowToken{5d89eb token=Token{23ccc93a ActivityRecord{2fe54865 u0 utanashati.reminder/.HomepageActivity t17}}} to stack=1 task=17 at 1
05-28 16:04:52.407 19927-19927/utanashati.reminder D/AndroidRuntime﹕ Shutting down VM
05-28 16:04:52.408 19927-19927/utanashati.reminder E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: utanashati.reminder, PID: 19927
java.lang.RuntimeException: Unable to start activity
ComponentInfo{utanashati.reminder/utanashati.reminder.HomepageActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at utanashati.reminder.HomepageActivity.onCreate(HomepageActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-28 16:04:52.410 1218-1232/system_process W/ActivityManager﹕ Force finishing activity 1 utanashati.reminder/.HomepageActivity
05-28 16:04:52.411 1218-1232/system_process W/ActivityManager﹕ Force finishing activity 2 utanashati.reminder/.LoginActivity
EDIT 1
I had my eyes opened, the problem is not with LoginActivity, but with HomepageActivity. Here is the code:
import ...
public class HomepageActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected EditText mAddTaskText;
protected Spinner mPrioritySpinner;
protected Button mAddTaskButton;
protected int intPriority = 0;
protected String taskText;
protected Timestamp taskTimestamp;
protected Task userTask;
protected JsonGenerator taskJSON;
#Override
protected void onCreate(Bundle savedInstanceState) { // Starts activity. The state can be restored from savedInstanceState
super.onCreate(savedInstanceState); // Calls the superclass method (IMPORTANT)
setContentView(R.layout.activity_homepage); // Sets layout from activity_homepage.xml
mPrioritySpinner = (Spinner) findViewById(R.id.prioritySpinner); // Creates an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.priorityList, android.R.layout.simple_spinner_item); // Specifies the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Applies the adapter to the spinner
mPrioritySpinner.setAdapter(adapter);
mPrioritySpinner.setOnItemSelectedListener(this);
mAddTaskText = (EditText) findViewById(R.id.addTaskEditText); // Finds View by its id in .xml file
mAddTaskButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HomepageActivity.this, "Done!", Toast.LENGTH_LONG).show();
Calendar taskCalendar = Calendar.getInstance(); // Creates new calendar
long taskTime = taskCalendar.getTimeInMillis(); // Gets time in milliseconds
taskTimestamp = new Timestamp(taskTime); // Creates new Timestamp
taskText = mAddTaskText.getText().toString(); // Gets description of the task
userTask.setDate(taskTimestamp); // Sets date
userTask.setText(taskText); // Sets text
/* Creating JsonGenerator */
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(taskJSON, userTask);
}
catch (IOException e) {
Toast.makeText(HomepageActivity.this, "Could not create JSON", Toast.LENGTH_LONG).show();
}
/* Getting out email and password */
String userPassword = ((EmailPassword) HomepageActivity.this.getApplication()).getPassword();
String userEmail = ((EmailPassword) HomepageActivity.this.getApplication()).getUserEmail();
Toast.makeText(HomepageActivity.this, userEmail + " " + userPassword, Toast.LENGTH_LONG).show();
/* HTTP stuff */
HttpPoster get = new HttpPoster();
get.execute(userEmail, userPassword, taskJSON.toString());
}
});
}
public int getData (String username, String password, String taskJSON) {
try {
HttpPost httpPost = new HttpPost("http://something.com/" + username + "/tasks");
String dataToEncode = username + ":" + password;
String encodedData = Base64.encodeToString(dataToEncode.getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", encodedData);
try {
StringEntity taskEntity = new StringEntity(taskJSON, "UTF-8");
httpPost.setEntity(taskEntity);
}
catch (UnsupportedEncodingException e) {
Toast.makeText(HomepageActivity.this, "Unsupported encoding", Toast.LENGTH_LONG).show();
}
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
return 1;
}
else if (statusCode == 404) { return 2; }
else if (statusCode == 500) { return 3; }
else if (statusCode == 409) { return 4; }
else { return statusCode; }
}
catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String priority = parent.getItemAtPosition(pos).toString(); // Gets chosen priority
Toast.makeText(HomepageActivity.this, priority, Toast.LENGTH_LONG).show();
while (!((priority.equals("Low")) || (priority.equals("Medium")) || (priority.equals("High")))) {
Toast.makeText(HomepageActivity.this, "Something bad happened. Try to choose again", Toast.LENGTH_LONG).show();
}
if (priority.equals("Low")) {
intPriority = 0;
}
else if (priority.equals("Medium")) {
intPriority = 1;
}
else if (priority.equals("High")) {
intPriority = 2;
}
userTask.setPriority(intPriority); // Sets chosen priority
}
public void onNothingSelected(AdapterView<?> parent) {
userTask.setPriority(intPriority); // Sets default priority ("0")
}
public class HttpPoster extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(String... params) {
return getData(params[0], params[1], params[3]);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result == 1) {
Toast.makeText(HomepageActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent takeUserHome = new Intent(HomepageActivity.this, HomepageActivity.class);
startActivity(takeUserHome);
}
else if (result == 2) {
Toast.makeText(HomepageActivity.this, "No such user", Toast.LENGTH_LONG).show();
}
else if (result == 3) {
Toast.makeText(HomepageActivity.this, "Internal server error: unable to send email", Toast.LENGTH_LONG).show();
}
else if (result == 4) {
Toast.makeText(HomepageActivity.this, "Task already exists", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(HomepageActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
And XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="utanashati.testapp.HomepageActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Add a new task..."
android:id="#+id/addTaskEditText"
android:nestedScrollingEnabled="false"
android:minLines="1"
android:maxLines="1" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/prioritySpinner"
android:layout_alignRight="#+id/addTaskButton"
android:layout_alignEnd="#+id/addTaskButton"
android:layout_below="#+id/addTaskEditText" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add task"
android:id="#+id/addTaskButton"
android:layout_below="#+id/prioritySpinner"
android:layout_centerHorizontal="true" />
</RelativeLayout>
It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout)
Check it.
mAddTaskButton is null because you never initialize it with:
mAddTaskButton = (Button) findViewById(R.id.addTaskButton);
before you call mAddTaskButton.setOnClickListener().
Check out this solution. It worked for me.....
Check the id of the button for which the error is raised...it may be the same in any one of the other page in your app.
If yes, then change the id of them and then the app runs perfectly.
I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!!
Hope it works
That true,Mustafa....its working..its point to two layout
setContentView(R.layout.your_layout)
v23(your_layout).
You should take Button both activity layout...
solve this problem successfully
Check whether you have matching IDs in both Java and XML
Just define the button as lateinit var at top of your class:
lateinit var buttonOk: Button
When you want to use a button in another layout you should define it in that layout. For example if you want to use button in layout which name is 'dialogview', you should write:
buttonOk = dialogView.findViewById<Button>(R.id.buttonOk)
After this you can use setonclicklistener for the button and you won't have any error.
You can see correct answer of this question: Android Kotlin findViewById must not be null
Make sure that while using :
Button "varName" =findViewById("btID");
you put in the right "btID". I accidentally put in the id of a button from another similar activity and it showed the same error. Hope it helps.
Got the same error,
CHECK THIS : MINOR SILLY MISTAKE
check findviewbyid(R.id.yourID);
If you have put the id correct or not.
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
Placing setOnClickListener in onStart method solved the problem for me.
Checkout "Android Lifecycle concept" for further clarification
mAddTaskButton.setOnClickListener(new View.OnClickListener()
you have a click listner but you haven't initialized the mAddTaskButton with your layout binding
Please check whether you have two Layout folder (e.g Layout & Layout-V21). The XML file should be same in both folders. That was the case for me.
I created a new activity which is supposed to read elements in a text file then display them as a ListView, but when I try to start the activity by clicking on its icon in the emulator I get this error message :
Unfortunately, app has stopped working
I don't understand why because the project seems to have been compiled correctly ?
PS : The activity I try to open is SortedLocationsListActivity.
Logcat error message :
02-04 13:51:32.340 2900-2900/fr.isima.android.tp1.tp1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: fr.isima.android.tp1.tp1, PID: 2900
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.isima.android.tp1.tp1/fr.isima.android.tp1.tp2.SortedLocationsListActivity}: java.lang.NumberFormatException: Invalid long: "1400390852000A"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NumberFormatException: Invalid long: "1400390852000A"
at java.lang.Long.invalidLong(Long.java:124)
at java.lang.Long.parse(Long.java:366)
at java.lang.Long.parseLong(Long.java:353)
at fr.isima.android.tp1.tp2.SortedLocationsListActivity.onCreate(SortedLocationsListActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Here is a part of my SortedLocationsListActivity (I modified the onCreate method) :
public class SortedLocationsListActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_sorted_locations_list);
InputStream is = getResources().openRawResource(R.raw.locations);
BufferedReader in = new BufferedReader(new InputStreamReader(is));
List<String> maListe = new ArrayList<String>();
String myligne;
LocationAdapter adapter = new LocationAdapter(this, R.layout.row_location);
try {
while((myligne = in.readLine()) != null)
{
String a[] = myligne.split(";");
Long _date=Long.parseLong(a[2], 36);
System.out.println(a[0]+" "+a[1]+" "+a[2]);
adapter.addLocation(a[0],a[1],_date);
}
setListAdapter(adapter);
}
catch(IOException e)
{
System.out.println("Error");
}
}
Ok, so the code that causes the problem is :
Long _date=Long.parseLong(a[2], 36);
Basically want I'm trying to do is to convert a String which can be "1400390852000A" for example to the Long type, how can I do it correctly ?
Ok, I corrected the error and I have managed to start the activity but it only displays a blank screen instead of the list I want, Here is the adapter that i coded :
public class LocationAdapter extends BaseAdapter {
private List<Location> Locations;
int monLayout;
LayoutInflater inflater;
public LocationAdapter(Context context, int layout){
monLayout=layout;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Locations = new ArrayList<Location>();
}
private class Location{
public String name;
public String address;
public Long date;
public Location(String _name,String _address , Long _date){
name=_name;
address=_address;
date=_date;
}
}
private class ViewHolder{
TextView name_view;
TextView address_view;
TextView date_view;
public ViewHolder(View rowLayout){
name_view = (TextView)rowLayout.findViewById(R.id.name);
date_view = (TextView)rowLayout.findViewById(R.id.date);
address_view = (TextView)rowLayout.findViewById(R.id.address);
}
}
public void addLocation(String _name,String _address,Long _date){
//Création d'une nouvelle location avec les données en paramètres
Location new_loc = new Location(_name, _address,_date);
//Ajout de la location à la liste des locations
Locations.add(new_loc);
}
/*Méthodes de la classe mère*/
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
view = inflater.inflate(monLayout, parent, false);
ViewHolder holder = (ViewHolder)view.getTag();
if (holder == null)
{
holder = new ViewHolder(view);
view.setTag(holder);
}
Location location = (Location)getItem(position);
holder.name_view.setText(location.name);
holder.address_view.setText(location.address);
holder.date_view.setText("Test");
return view;
}
}
Can someone tell me where the problem may come from ?
Reason is this >> java.lang.NumberFormatException: Invalid long: "1400390852000A"
You are trying to convert String type to Long by Long.parseLong in your activity. Correct this and it will work.
String value >> 1400390852000A, can not be converted to Long.
check your SortedLocationsListActivity line number 37. Bug is there, go kill it :)
take a look at SortedLocationsListActivity line 37.
it's look's like an NumberFormatException: Invalid long: "1400390852000A".
check the parameters here:
Long _date=Long.parseLong(a[2], 36);
Go to line 37 of SortedLocationsListActivity class and check for a Long parsing method. Make sure that the parameter in this is always a number.
Long _date=Long.parseLong(a[2], 36);
Make sure that String myligne, after the ;, has only numbers.
Basically want I'm trying to do is to convert a String wich can be "1400390852000A" for example to the Long type, how can I do it correctly ?
It depends on the format of your Strings. If it's always the case that the letter is at the end then you can get the number by adding this in your code, just before the parsing:
String a[] = myligne.split(";");
String myFinalString = a[2].substring(0, a[2].length()-1);
Long _date=Long.parseLong(myFinalString, 36);