i'm making a chart which contain x and y value from sqlite.
my code is like this :
Double a, b;
notesCursor.moveToFirst();
do {
a = notesCursor.getDouble(notesCursor.getColumnIndex(DbAdapter.KEY_ROWID));
b = notesCursor.getDouble(notesCursor.getColumnIndex(DbAdapter.KEY_RESULT));
mCurrentSeries.add(a, b);
}while(notesCursor.moveToNext());
when i didn't insert any x y value to my sqlite, the errors message came out... i want to add some code which when even i didn't insert any x y value to my database, the chart will come out with 0, 0 value..
i've been making a code like this :
Double a, b;
if(a==null && b==null){
mCurrentSeries.add(0.0, 0.0);
}
else{
notesCursor.moveToFirst();
do {
a = notesCursor.getDouble(notesCursor.getColumnIndex(DbAdapter.KEY_ROWID));
b = notesCursor.getDouble(notesCursor.getColumnIndex(DbAdapter.KEY_RESULT));
mCurrentSeries.add(a, b);
}while(notesCursor.moveToNext());
}
but i can't make it work, anyone can help me to solve this problem? thank you
You code INITIALISES the values to non null (0.0) but it never guarantees that they won't be rest to null before they are given to the mCurrentSeries.add method. In you previous code, if a and b start as not null, then the else in the if else will be exected, then the do while. If in the do while the noteCursor.getDouble returns null for either a or b, then a and/or b will be null. If what you need is for a and b to not be null when arriving into your mCurrentSeries object via the add method, you should modify that add method to give a and b some default values when they're null.
Your new code does not guarantee that a and b will be not null when passed to the mCurrentSeries.add method:
import java.util.HashMap;
import java.util.Map;
public class C {
Double a, b;
Map mCurrentSeries = new HashMap();
NotesCursor notesCursor = new NotesCursor();
public void yourMethod() {
if (a == null && b == null) {
mCurrentSeries.put(0.0, 0.0);
} else {
// notesCursor.moveToFirst();
do {
a = notesCursor.getDouble();
b = notesCursor.getDouble();
mCurrentSeries.put(a, b);
} while (notesCursor.moveToNext());
}
}
private static class NotesCursor {
boolean b = false;
public Double getDouble() {
return null;
}
public boolean moveToNext() {
return !b;
}
}
public static void main(String... args) {
C c = new C();
c.yourMethod();
System.out.println("a="+c.a);
System.out.println("b="+c.b);
}
}
Related
I have created a simple app to calculate the discount. it works fine when the values are provided, but keeps on crashing when calculation is done with empty text fields. thanks in advance..!!
public class Firstctivity extends AppCompatActivity {
Button find;
EditText ed1,ed2;
TextView tv1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstctivity);
find=(Button)findViewById(R.id.button);
tv1=(TextView)findViewById(R.id.text39);
ed1=(EditText)findViewById(R.id.sai);
ed2=(EditText)findViewById(R.id.editText);
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
try {
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
});
}
}
try tihs.
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(ed1.getText().toString.length() >0){
try {
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
}
});
When you try to calculate the discount, you call ed1.getText() and then, you try to convert a null value into a double value, witch causes a NullPointerException.
To solve that issue, you have to check if the getText() method is returning a valid text to convert it.
You'll want to check for empty strings and null values:
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ed1.getText() != null && !TextUtils.isEmpty(ed1.getText().toString()) &&
ed2.getText() != null && !TextUtils.isEmpty(ed2.getText().toString())) {
try {
final double a = Double.parseDouble(String.valueOf(ed1.getText().toString()));
final double b = Double.parseDouble(String.valueOf(ed2.getText().toString()));
double c = a * b;
double results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
} catch (NumberFormatException ex) {
Log.e("SOME TAG", ex.getMessage(), ex);
}
}
}
});
using try- catch in such simple calculations is not recommended and may "hide" crusial errors. First of all start with an If-statement inside your click event and do all your checks inside there. (if txtValue.getText()!=null {do something} ). this way it is easier for you to debug and correct your code.
So, just to clarify; remove try-catch. do if-stament and check if your txt fields are not null before proceeding to any calculations.finish you click event without any problem and with a valid calculation.
Hi guys i got 2 ArrayList based on same class. I have to add from arraylist1 to arraylist2 non exist(s)ing rows. I tried to use contains but its always returning false. What i m doing wrong ? Ty
MyClass
public class HataKoduBean {
private String Oid;
private String Name;
private String Surname;
}
How i define Arraylists
Arraylist<MyClass> array1 = new Arraylist<>();
Arraylist<MyClass> array2 = new Arraylist<>();
How i tried to compare ?
for (int ii = 0; ii < array1.size(); ii++) {
if (!array2.contains(array1.get(ii)))
array2.add(array1.get(ii));
}
First you have to implement equals() and hashCode() in your custom class.
Consider to use Sets, so you can merge collections in one line with addAll().
First you have to implement equals() and hashCode() in your custom object
and create loop and compare between object by using equals method like this.
implement equals and hashCode:
`#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
HataKoduBean o = (HataKoduBean) o;
return Oid != null?Oid.equals(HataKoduBean.Oid):HataKoduBean.Oid== null;
}
#Override
public int hashCode() {
return Oid != null ? Oid.hashCode() : 0;
}`
compare Objects:
for (int ii = 0; ii < array1.size(); ii++) {
if (!array2.get(ii).equals(array1.get(ii)))
array2.add(array1.get(ii));
}
I'm working on this program that uses a few lines of code that worked that last time I used them but the only difference this time is that I need to use else if's instead of a basic if else statement. Still trying to learn how to really use this but any help would be appreciated. My error is stemming from the if statement and I have a feeling it is to do with the float result; line.
private float caravan = 35;
private float wigwag = 25;
private float tent = 15;
private float caravan(float value){
return value * caravan;
}
private float wigwag(float value){
return value * wigwag;
}
private float tent(float value){
return value * tent;
}
Button bookButton;
public void onClick(View view) {
EditText bookAmount = (EditText)findViewById(R.id.txtNights);
EditText bookFinal = (EditText)findViewById(R.id.txtBooked);
float bookResult = Float.parseFloat(bookAmount.getText().toString());
float result;
RadioButton cbSelected = (RadioButton)findViewById(R.id.radCaravan);
if(cbSelected.isChecked()){
result = caravan(bookResult);
} else if (result == wigwag(bookResult)){
} else if (result == tent(bookResult)){
}
bookFinal.setText(String.valueOf(result));
}
Your problem is that you put a semicolon at the end of your statements, and you don't use the == operator:
if(cbSelected.isChecked()){
result = caravan(bookResult);
} else if (result = wigwag(bookResult);{
} else if (result = tent(bookResult);{
}
Fix by removing the semicolons and using the equality operator:
if(cbSelected.isChecked()){
result = caravan(bookResult);
} else if (result == wigwag(bookResult){
} else if (result == tent(bookResult){
}
used == instead of = operator
if (result == wigwag(bookResult))
In android I'm trying to save grids that the user already have pressed.
Code snipping I’m using is:
// private
private HashSet<int[]> PlayerSelectedHashField = new HashSet<int[]>();
private boolean collisionDetected = false;
In a function I’m using
collisionDetected = PlayerSelectedHashField.contains(TmpPos); // -> Fail - not working
{doing something}
PlayerSelectedHashField.add(TmpPos); // int[] TmpPos - TmpPos is x y
The .add function is working as expected, but .contains always return false.
Why does it not working - and what can I do instead?
public boolean contains(Object o) {
return map.containsKey(o);
}
containsKey:
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
getNode:
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
It will not work since equals of arrays will do a == compare, and it will return true only if they point to the same instance.
Your problem could be fixed without work with Arrays.equals (the way to compare two arrays elements and not reference) (could be problematic (at least, for me.) i prefer an easy way)
Since you save X and Y coordinates, just make a class Point
public class Point {
public final int X;
public final int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
#Override
public boolean equals(Object obj)
{
if (obj == this) {
return true;
}
if (obj instanceof Point) {
Point pObj = (Point) obj;
return pObj.X == X && pObj.Y == Y;
}
return false;
}
#Override
public int hashCode()
{
int result = X;
result = 31 * result + Y;
return result;
}
}
then use Point class to save X, Y points.
Instead of create your custom point class, you can use the Android Point.
Example
Set<Point> points = new HashSet<Point>();
points.add(new Point(1, 3));
points.add(new Point(1, 4));
System.out.println(points.contains(new Point(1, 3)));
System.out.println(points.contains(new Point(1, 4)));
System.out.println(points.contains(new Point(1, 5)));
From the HashSet javadocs:
public boolean contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
So, generally, if you don't know what happens when you call equals on a particular object type, then contains also may not behave as you expect. It is never a bad idea to make a class for a particular object if that object type has conceptual meaning in your program. If you do that, you can override the equals method to make sure it is behaving exactly as you want.
I am doing quize app. In this app questions wont be generate duplicates. so I am using code like int value=random.nextInt(10-1)+1.When i submit the answer random number will generate newly so generating duplicates.How can i compare previous random value with new random values every time ?
Generate from 1 to 10 and store in a list
Shuffle the list of generated numbers
Keep removing from the list
List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 10; i++) {
list.add(i)
}
Collections.shuffle(list);
int value= list.remove(0);
.......
value= list.remove(0);
and so on...
Check this also : Java - generate Random range of specific numbers without duplication of those numbers - how to?
Also storing in a HashMap and checking is a smart way like the other answer says. But this can cause a lot more clashes, since everytime you try to add a duplicate to the HashMap you fail and you have to generate a new one again. But generating all at once and shuffling doesnt cause this. But since the input set is small(10) this collision might not happen too much(depending on the randomness, or maybe it happens too much?) and the O(1) access to the map elements for comparison will help.
Store value in a hashmap and then check if it's already there. If there reroll.
Here is code which i was using at my project. Full source code is
here
package com.banglardin.test_code;
import android.app.*;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.banglardin.test_code.*;
import java.util.*;
public class MainActivity extends Activity {
protected SharedPreferences preference;
protected Questions questionObject;
protected TextView textView;
protected Button buttonView, cleanButton;
protected ArrayList<String> ques_array;
protected final String KEY="Key124";
protected int i=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//intilized Question and preference
questionObject = new Questions();
preference = getSharedPreferences(KEY,Context.MODE_WORLD_WRITEABLE);
// get array from question object
try{
ques_array= questionObject.getQestions(getApplicationContext());
}catch(Exception e){
e.printStackTrace();
}
// intilized views
textView = (TextView)findViewById (R.id.question);
buttonView = (Button) findViewById (R.id.button);
cleanButton = (Button) findViewById (R.id.button_clean);
textView.setTextSize(18.33f);
buttonView.setTextSize(18.00f);
cleanButton.setTextSize(18.00f);
// set onclickListener on button view
buttonView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int set = 0;
if(i < 6){
while(set == 0){
String history = getString(KEY); // <0>
Random r = new Random();
int id = r.nextInt(ques_array.size());
String s_id= "<"+ String.valueOf(id) + ">"; // ex : <0>
if( !history.contains(s_id)){
textView.setText(ques_array.get(id));
setString(KEY, (history + s_id)); // ex : <0> + <3> = <0><3>;
set = 67;
i++;
}
}
}
else if(i>=6){
textView.setText(getResources().getString(R.string.e2));
Toast.makeText(MainActivity.this,"Questions are not available any more",2).show();
}
}
}
);
// set onclickListener on button view
cleanButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
setString(KEY, "<-0>");
}
}
);
}
#Override
public void onBackPressed(){
if(preference != null){
setString(KEY, ("<-0>"));
finish();
}
super.onBackPressed();
}
/** Get String value from preference */
private String getString(String KEY){
if(preference != null){
return preference.getString(KEY,"<-33>");
}
else{
return null;
}
}
/** Put String value to preference */
private void setString(String KEY, String value){
if(preference != null){
SharedPreferences.Editor edit = preference.edit();
edit.putString(KEY, value);
edit.commit();
}
}
/** Class that gives us all questions */
class Questions{
protected ArrayList<String> data;
public ArrayList<String> getQestions(Context c) throws Exception{
data = new ArrayList<String>();
Resources res= c.getResources();
String qes[] ={
res.getString(R.string.q1) , //0
res.getString(R.string.q2) , //1
res.getString(R.string.q3) , //2
res.getString(R.string.q4) , //3
res.getString(R.string.q5) , //4
res.getString(R.string.q6) , //5
res.getString(R.string.q7) , //6
};
// add all the strings one by one
for(String i : qes){
data.add(i);
}
return data;
}
}
}
use 'HashSet' class in the main property of this class is they contain set of different values mean no value is repeated in it......
so u can generate random no. and add it in set like this
Random r = new Random();
int i = r.nextInt(100);
HashSet<int> s = new HashSet<int>();
s.add(i);
generat random number and add it inti hashset and use it....
an in nextInt parameter have to give maximum no. range...
example code as follows:
Random r = new Random();
//declare a hash set
HashSet set = new HashSet();
for(int i=0;i<50;i++)
{
set.add(r.nextInt(100));
}
// create an iterator
Iterator iterator = set.iterator();
// check values
while (iterator.hasNext()){
System.out.println("Value: "+iterator.next() + " ");
}