I'm making an application in which the user can add Store departments and for those departments the ability to add the cities of where the departments are located.
I keep on getting a NumberFormatException when I'm trying to add a city for a departement:
Caused by: java.lang.NumberFormatException: Invalid long: "null"
at java.lang.Long.invalidLong(Long.java:124)
at java.lang.Long.parseLong(Long.java:345)
at java.lang.Long.parseLong(Long.java:321)
at org.hello.addgroups.vestiging_list.onCreate(vestiging_list.java:45)
after this the app crashes but when I restart the app the values are added into the list.
these are my classes:
Add_vestiging.java:
public class Add_vestiging extends Activity implements View.OnClickListener{
EditText et,hiddenet;
Button add_bt, cancel_btn;
SQLController dbcon;
Intent i;
Long groupd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_vestiging);
et = (EditText)findViewById(R.id.vestigingName);
add_bt = (Button) findViewById(R.id.addBtn);
cancel_btn = (Button) findViewById(R.id.cancelBtn);
dbcon = new SQLController(this);
try {
dbcon.open();
} catch(SQLException e) {
e.printStackTrace();
}
i = getIntent();
String id = i.getStringExtra("groupID");
groupd = Long.parseLong(id);
add_bt.setOnClickListener(this);
cancel_btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.addBtn:
String name = et.getText().toString();
try {
dbcon.insertVestiging(groupd, name);
}catch(SQLiteException e) {
e.printStackTrace();
}
Intent main = new Intent(Add_vestiging.this, vestiging_list.class);
startActivity(main);
break;
case R.id.cancelBtn:
super.finish();
break;
}
}
}
vestiging_list.java:
public class vestiging_list extends Activity {
ListView lv;
SQLController dbcon;
TextView title;
Button addves;
Long long_id;
String groupid;
Intent add_ves;
String groupname;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vestiging_list);
dbcon = new SQLController(this);
title = (TextView) findViewById(R.id.vestitel);
try {
dbcon.open();
} catch (SQLException e) {
e.printStackTrace();
}
add_ves = getIntent();
groupid = add_ves.getStringExtra("groupID");
groupname = add_ves.getStringExtra("groupName");
title.setText(groupname);
long_id = Long.parseLong(groupid);
addves = (Button)findViewById(R.id.addves_bt_id);
lv = (ListView)findViewById(R.id.vestigingList_id);
addves.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add_ves = new Intent(getApplicationContext(), Add_vestiging.class);
add_ves.putExtra("groupID", groupid);
startActivity(add_ves);
}
});
Cursor cursor = dbcon.readVestigingen(long_id);
String[] from = new String[] { GroupDatabaseHelper.V_ID, GroupDatabaseHelper.VESNAME};
int[] to = new int [] { R.id.vesID, R.id.vesName};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(vestiging_list.this, R.layout.vestiging_single_row_item, cursor, from, to,1);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
Any ideas on how to remove the NumberFormatException?
Any help is greatly appreciated.
Thanks in advance.
Any ideas on how to remove the NumberFormatException?
The exception is caused by Long.parseLong in vestiging_list at line 45. The reason is that groupid, in your case in null. Since you didn't fill up the Intent object you used to start vestiging_list.
E.g.
case R.id.addBtn:
String name = et.getText().toString();
try {
dbcon.insertVestiging(groupd, name);
}catch(SQLiteException e) {
e.printStackTrace();
}
Intent main = new Intent(Add_vestiging.this, vestiging_list.class);
main.putExtra("groupID", String.valueOf(groupd));
startActivity(main);
break;
assuming that groupd is a long.
I think problem is in the following line :
int[] to = new int [] { R.id.vesID, R.id.vesName};
What is the type of "R.id.vesName" ?. It should be integer.
From the stack trace that you have provided I can assume that groupId is null:
groupid = add_ves.getStringExtra("groupID");
...
long_id = Long.parseLong(groupid);
According to the Long's Javadoc Long#parseLong(String) throws an Exception if the argument is not a parsable Long, sth which is the case with null.
Check if groupid can be null else you have a bug. If it can be null then check if it equals null and then set long_id to an appropriate value e.g. 0 or -1.
It looks to me like you're creating an Intent, but you're not passing the info to the intent. The class reference to the current class is just a trace, and doesn't include info.
When you make the Intent in the Add_vestiging class, in onClick, do something like main.putExtra("groupID", id).
Looks like you're putting it in the SQLController, so you could try passing that as well.
Related
I have a many checkbox and I saved in a String if it's checked like this:
String juice = "";
if (apple.isChecked()) {
juice = apple.getText().toString().trim() + " " + etiquetas;
}
if (orange.isChecked()) {
juice = orange.getText().toString().trim() + " " + etiquetas;
}
But when I need in another Activity put the checkbox checked, idk how to checked because I saved in one. I really need to be like this in one variable, because they're instructions for the exam. And thas's my code for the other Activity;
Intent intent = getIntent();
if(intent != null){
String juice_2 = (String) getIntent().getStringExtra("EXTRA_JUICE");
//apple.setChecked();
}
In the current activity, you can use a single String that has multiple juice words separated by a SPACE character.
And at the destination activity, split the string into an array of strings based on the SPACE character, and then set the checkBox value if this array contains your specific juice.
at Activity A:
String juice = "";
if (apple.isChecked()) {
juice = apple.getText().toString().trim() + " ";
}
if (orange.isChecked()) {
juice = orange.getText().toString().trim() + " ";
}
// Going to Activity B
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("JUICE", juice);
startActivity(intent);
at Activity B:
if (getIntent() != null) {
String juice = getIntent().getStringExtra("JUICE");
if (juice != null) {
String[] splittedJuice = juice.split(" ");
ArrayList list = new ArrayList();
// Convert array into a List
Collections.addAll(list, oldLines);
// Check if the list contains "orange"
if (list1.contains("orange")) {
orange.setChecked(true);
}
if (list1.contains("apple")) {
apple.setChecked(true);
}
}
}
To pass data from one activity to another you can use Intent.putExtra().
The line will look something like this:
intent.putExtra(LABEL, juice);
where: LABEL is a String which allows second activity to find your variable,
juice is your variable.
To resolve the problem you can use something like this:
public class First extends AppCompatActivity {
private final static String LABEL = "juices";
String juice;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
final CheckBox apple = (CheckBox) findViewById(R.id.apple);
Button nextIntent = (Button) findViewById(R.id.next);
nextIntent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (apple.isChecked()) {
juice = apple.getText().toString();
}
Intent intent = new Intent(getApplicationContext(), Second.class);
intent.putExtra(LABEL, juice);
startActivity(intent);
}
});
}
}
Second Activity:
public class Second extends AppCompatActivity {
private final static String LABEL = "juices";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Intent intent = getIntent();
String dataReceived = intent.getStringExtra(LABEL);
System.out.println("Your string: " + dataReceived);
}
}
Anyway, I would recommend that you pass Boolean values to the next activity without converting them to a String if it's only to check/uncheck Checkboxes in the second layout.
If you have a lot of variables in the first activity you can pass them to the array, send it to the another activity (by the similar way) and iterate to check/uncheck boxes.
I am very new to java and need some help. I would like to add a function to this register page where users cannot leave their password and username fields blank. I would very much appreciate it if you could type the lines of code as it would be easier for me to visualize.
I have tried implementing else if to this page but it doesn't work and there is no error as well, so i removed those codes. Those codes does not appear in the lines of code i have shown here.Cheers
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
db = new DatabaseHelper(this);
mTextUsername = (EditText)findViewById(R.id.edittext_username);
mTextPassword = (EditText)findViewById(R.id.edittext_password);
mTextCnfPassword = (EditText)findViewById(R.id.edittext_cnf_password);
mButtonRegister = (ImageButton)findViewById(R.id.imagebutton_register);
mTextViewLogin = (TextView)findViewById(R.id.textview_login);
mTextViewLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent LoginIntent = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(LoginIntent);
}
});
mButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = mTextUsername.getText().toString().trim();
String pwd = mTextPassword.getText().toString().trim();
String cnf_pwd = mTextCnfPassword.getText().toString().trim();
if(pwd.equals(cnf_pwd)) {
Long val = db.adduser(user,pwd);
if(val > 0){
Toast.makeText(RegisterActivity.this,"Successfully Registered.",Toast.LENGTH_SHORT).show();
Intent movetoLogin = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(movetoLogin);
}
else{
Toast.makeText(RegisterActivity.this,"Registration Error.",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(RegisterActivity.this,"Those passwords didn't match.Try Again.",Toast.LENGTH_SHORT).show();
}
}
});
}
}
You can use the required attribute in html to avid those fields being left blanked.If you use this then you will not need a code to handle blank fields but it will control that situation in the frontend itself.
Refer here how to use it : required attribute
Have you tried make a length comparisson ?
Change this line: if(pwd.equals(cnf_pwd)) { to
if(pwd.length() > 0 && user.length() > 0 && pwd.equals(cnf_pwd)) {
There is no need to make it that complicated. After declaring strings,You can use
if(pwd.isEmpty() || user.isEmpty() )
{
Toast.makeText(RegisterActivity.this,"Enter Username and Password",Toast.LENGTH_SHORT).show();
}
else
{
if{pwd.equals(cnf_pwd))
{
Toast.makeText(RegisterActivity.this,"Successfully Registered.",Toast.LENGTH_SHORT).show();
Intent movetoLogin = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(movetoLogin);
}
else
{
Toast.makeText(RegisterActivity.this,"Make sure Password Entered is same",Toast.LENGTH_SHORT).show();
}
}
I'm trying to create an app like shopping cart
Using this to access my database http://www.tutecentral.com/restful-api-for-android-part-2/
And i'm stuck at adding products to cart, so far I understand that the selected products go to arraylist in a few tutorials. In the code below I have two Activities, the MaterialView (this shows the details of the materials and has the option to add to cart), and the MaterialCart (shows the list of selected products.)
this is the block of code in MaterialView to send the values to MaterialCart
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
Intent i=new Intent(MaterialView.this, MaterialCart.class);
i.putExtra("mID", mid);
i.putExtra("name", Name.getText().toString());
i.putExtra("qty", Qty.getText().toString());
i.putExtra("price", Price.getText().toString());
i.putExtra("stock", Stock.getText().toString());
i.putExtra("rqQty", RqQty.getText().toString());
startActivity(i);
Toast.makeText(MaterialView.this, "Added Succesfully.", Toast.LENGTH_LONG).show();
}
} );
I have used Intent to pass the values (I'm pretty sure this method is wrong, I also tried calling the MaterialCart class itself to access the arrayList so I can add values and it didn't work)
This is the block of codes in my MaterialCart to receive the values
public class MaterialCart extends Activity {
final ArrayList<PropertyCartTable> materialProperties = new ArrayList<>();
#SuppressLint("LongLogTag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cart);
Intent i = new Intent();
Bundle extras = getIntent().getExtras();
try{
String Name = extras.getString("name");
String Qty = extras.getString("qty");
String Price = extras.getString("price");
String Stock = extras.getString("stock");
String RqQty = extras.getString("rqQty");
String ID = extras.getString("mID");
Log.d("EXTRAS:", Name + " " + Qty + " " + ID);
materialProperties.add(new PropertyCartTable( ID,Name,Qty,Price,Stock,RqQty));
getIntent().removeExtra("Name");
getIntent().removeExtra("Qty");
getIntent().removeExtra("Price");
getIntent().removeExtra("Stock");
getIntent().removeExtra("RqQty");
getIntent().removeExtra("MID");
}
catch (Exception h){
Log.d("Exception!",h.toString());
}
// materialProperties.add(array);
Log.d("MaterialView.Cart isEmpty", String.valueOf(materialProperties.isEmpty()));
if(materialProperties.isEmpty()) {
Toast.makeText(this, "You have no materials to request.", Toast.LENGTH_LONG).show();
i = new Intent(MaterialCart.this, ProductDetails.class);
startActivity(i);
}else{
ArrayAdapter<PropertyCartTable> adapter = new propertyArrayAdapter(this, 0, materialProperties);
ListView listView = (ListView) findViewById(R.id.lv_materialcart);
listView.setAdapter(adapter);
}
}
The codes work for receiving the values, but when I go back to the materialView (or choose another product) the ArrayList doesn't append the values.
What I'm trying to achieve here is to add the values from the MaterialView (even if the user adds many prodducts) to MaterialCart's ArrayList.
You can let your Application contain the data:
public class MyApp extends Application {
private static List<String> data = new ArrayList<>();
public static void addItem(String item) {
data.add(item);
}
public static List<String> getData() {
return data;
}
}
And when button is clicked:
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
MyApp.addItem(your item);
Intent i=new Intent(MaterialView.this, MaterialCart.class);
startActivity(i);
}
} );
And in MaterialCart.class:
List<String> data = MyApp.getData();
But remember:data will be clear when app is closed.And if you want save it locally,you need to use SharedPreferences
I am new to Android development. I am trying to call a method of one of my classes when a button on my main activity is pressed.
On my Main Activity I have this button:
public void buttonTest(){
Button b = (Button) findViewById(R.id.test);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String s = "changeText:myText";
Intent in = new Intent(PlusActivity.this, Test.class);
in.putExtra("method",s);
startActivity(in);
}
});
}
And here is is the class (without imports) which that intent above is calling to.
public class Test extends Activity {
static String text = "test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
TextView mTextView = (TextView) findViewById(R.id.textView);
mTextView.setText(text);
}
public void changeText(String s){
this.text = s;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String[] array = intent.getStringExtra("method").split(":");
if(array[0].equals("changeText")){
changeText(array[1]);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
Basically I want to know if it is possible to change the value of that String text, before onCreate(). Basically each button will have a correspondent text, and I want to be able to modify that text based on which button.
If it is, what should I do/change?
Thanks in advance.
The right way to do it is to send the string you want it to be as an extra in the intent, and to read the extra from the intent and assign it to that variable in the onCreate function.
Use SharedPreference. Save in OnCLick of first class and retrieve in OnCreate of second class.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes
String text;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
text= null;
} else {
text= extras.getString("your default string message");
}
} else {
String s = "your default string message";
text= (String) savedInstanceState.getSerializable(s);
}
I'm programming an Android application and I got a little problem. I'm trying get a value from the Class A in the Class B but it doesn't return the correct value.
Here's my code to better understand (Sorry for my poor english)!
Class A
package com.androidhive.androidlistview;
//import
public class AndroidListViewActivity extends ListActivity {
int day;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
//prints 1 When I click on the first list item, 2 When I click on the second, ...
startActivity(i);
// sending data to new activity
i.putExtra("product", product);
}
});
}
public int getDay() {
return day;
}
}
Class B
package com.androidhive.androidlistview;
//import
#SuppressLint({ "NewApi", "HandlerLeak" })
public class SingleListItem extends Activity {
AndroidListViewActivity alva = new AndroidListViewActivity();
int day;
String url;
String code;
//others variables
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Graphic
new NetworkOperation().execute();
}
class NetworkOperation extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
Document doc;
try {
day = alva.getDay();
System.out.println(day);
//prints 0
url = "http://www.planetehockey.com/calendrier.php?saison=45&div=9&club=&journee=" + day + "&jour=&mois=&page=0";
doc = Jsoup.connect(url).get();
//Récupère le texte d'une balise ayant bg_tableau pour class
Elements getId = doc.getElementsByClass("bg_tableau");
code = getId.text();
code = code + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
//other code
}
};
}
Thank's a lot for all your answers it helped me a lot:
How I solved the problem:
Class A
i.putExtra("product", product);
startActivity(i);
and:
Class B
int day = Integer.parseInt(i.getStringExtra("product").replaceAll("[^\\d.]", ""));
In your Class A, you're trying to bundle components AFTER the activity has been called.
put the call function like this..
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
i.putExtra("product", product);
startActivity(i);
The passes the parameter in a bundle to the called activity.
HTH!
There are two simple solutions for your problem,
1. Pass day values in intent to SingleListItem
Or
2. Make day as a Static member and use it with class Name like,
public static int day; and access it `AndroidListViewActivity.day`
and remove public int getDay() method from AndroidListViewActivity as in both activity it refers a different object of AndroidListViewActivity .
Try doing i.putExtra("product", product); before startActivity(i);
In your Activity A you have written the getter method but not setter method to set the value of day in your code. Just write the setter method also and set the value of day.
public void setDay(int p_day)
{
day=p_day;
}
Make the variable day as static. After setting the day value try to get it in activity B.
I hope this will help you.