I hope you can help me with these
I am trying to extract information from my parse database for my android app (just a viewing app)
Basically what I want to do is I go select on my two spinners and click view
Once I click view it should query on three conditions
1st condition: current parse user = current user (from database)
2nd condition: selected item on spinner one (spin Month) = month (from database)
3rd condition: selected item on spinner two (spin Year) = year (from database)
Then it will give me the data needed for each text view (I was able to do this with just one condition but I need to specify it into 3 conditions)
Class Name: payslip
Column Name from class: username, month, year
I'm not sure which or what kind of if statement, switch case, or anything I can use so I can fit these 3 conditions
Thanks a bunch for the help!
a = (Spinner) findViewById(R.id.spinMonth);
ArrayAdapter adapterA = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, month);
a.setAdapter(adapterA);
b = (Spinner) findViewById(R.id.spinYear);
ArrayAdapter adapterB = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, year);
b.setAdapter(adapterB);
ParseQuery<ParseObject> query = ParseQuery.getQuery("payslip");
query.whereEqualTo("username",ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> res, ParseException e) {
if (res == null) {
Toast.makeText(getApplicationContext(),
"Data Retrieved",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Data Not Retrieved",
Toast.LENGTH_LONG).show();
}
}
});
stringmonth = (String) a.getSelectedItem();
stringyear = (String) b.getSelectedItem();
view.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ParseQuery<ParseObject> mainQuery = ParseQuery.getQuery("payslip");
mainQuery.whereEqualTo("month",stringmonth);
mainQuery.whereEqualTo("year",stringyear);
mainQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> results, ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
for (ParseObject x : results) {
String name = x.getString("name");
basic = x.getDouble("basicpay");
Double regot = x.getDouble("regot");
Double nightdiff = x.getDouble("nightdiff");
Double sss = x.getDouble("sss");
Double hdmf = x.getDouble("hdmf");
Double philhealth = x.getDouble("philhealth");
Double tax = x.getDouble("tax");
Double adjustment = x.getDouble("adjustment");
txtName.setText(name);
String stringbasic = Double.toString(basic);
txtBasic.setText(stringbasic);
String stringregot = Double.toString(regot);
txtRegot.setText(stringregot);
String stringnd = Double.toString(nightdiff);
txtND.setText(stringnd);
String stringsss = Double.toString(sss);
txtSSS.setText(stringsss);
String stringhdmf = Double.toString(hdmf);
txtHDMF.setText(stringhdmf);
String stringphilhealth = Double.toString(philhealth);
txtPhilhealth.setText(stringphilhealth);
String stringtax =Double.toString(tax);
txtTax.setText(stringtax);
String stringadjust = Double.toString(adjustment);
txtAdjust.setText(stringadjust);
gross = Double.valueOf(basic)+Double.valueOf(regot)+Double.valueOf(nightdiff);
String stringgross = Double.toString(gross);
txtGross.setText(stringgross);
deduction = Double.valueOf(sss)+Double.valueOf(hdmf)+Double.valueOf(tax)+Double.valueOf(philhealth);
String stringdeduction= Double.toString(deduction);
txtDeductions.setText(stringdeduction);
netpay= gross-deduction;
BigDecimal bd = new BigDecimal(netpay).setScale(2, RoundingMode.HALF_EVEN);
netpay = bd.doubleValue();
String stringnetpay=Double.toString(netpay);
txtNetpay.setText(stringnetpay);
}
}else {
// error
}
}
});
so apparently I got the answer I need
I omitted the first parse query I used
Inserted the two spinner.selected item inside the on click function of btnView
And also created the three line condition query which works!
The problem it doesn't apply the three conditions because in my parse database year is number and here I get it as a string..
public void onClick(View arg0) {
stringmonth = (String) a.getSelectedItem();
stringyear = (String) b.getSelectedItem();
numyear = Double.valueOf(stringyear);
ParseQuery<ParseObject> mainQuery = ParseQuery.getQuery("payslip");
mainQuery.whereEqualTo("username",ParseUser.getCurrentUser().getUsername());
mainQuery.whereEqualTo("month",stringmonth);
mainQuery.whereEqualTo("year",numyear);
mainQuery.findInBackground(new FindCallback<ParseObject>()
Related
I'm developing a recipe book and I'm implementing this method to insert my Recipe in the Database. In the for cycle I get the ingredient's name and quantity from multiples EditText, saving each of them in an Ingredient.class instance (newIngredient). Then I insert the instance into the DB and add it to an ArrayList. The followings "if conditions" are for the title, time and other Recipe's attributes. Finally, I also insert Recipe and Tag instances in the relatives DB's tables and I close DB.
public void saveRecipe() {
dbHelper = new DatabaseHelper(context);
// creating new recipe from user input
Ingredient newIngredient;
String title, childIngredient, instruction, tag;
int target, time, childQuantity, calories;
int countIngredients = parentIngredientLayout.getChildCount();
int countTags = chipGroup.getChildCount();
ArrayList<Ingredient> ingredients = null;
ArrayList<Tag> tags = null;
View childViewIng = null;
EditText childTextViewI = null;
EditText childTextViewQ = null;
// ingredients fields settings
for (int d=0; d<countIngredients; d++) {
childViewIng = parentIngredientLayout.getChildAt(d);
childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
childTextViewQ = childViewIng.findViewById(R.id.quantityField);
childIngredient = childTextViewI.getText().toString();
childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
newIngredient = new Ingredient(childIngredient, childQuantity);
dbHelper.insertIngredient(newIngredient);
ingredients.add(newIngredient);
}
//recipe fields settings
if (photoPath1 == null)
photoPath1 = "";
if (photoPath2 == null)
photoPath2 = "";
if (photoPath3 == null)
photoPath3 = "";
if (titleText.getText().toString().isEmpty()) {
title = "";
} else {
title = titleText.getText().toString();
}
if (targetNumber.getText().toString().isEmpty()) {
target = 0;
} else {
target = Integer.parseInt(targetNumber.getText().toString());
}
if (timeNumber.getText().toString().isEmpty()) {
time = 0;
} else {
time = Integer.parseInt(timeNumber.getText().toString());
}
if (instructionText.getText().toString().isEmpty()) {
instruction = "";
} else {
instruction = instructionText.getText().toString();
}
if (caloriesNumber.getText().toString().isEmpty()) {
calories = 0;
} else {
calories = Integer.parseInt(caloriesNumber.getText().toString());
}
if (tagName.getText().toString().isEmpty()) {
tag = "";
} else {
tag = tagName.getText().toString();
}
Recipe newRecipe = new Recipe(title, photoPath1, photoPath2, photoPath3, instruction, target, time, calories, ingredients);
Tag newTag = new Tag(tag);
dbHelper.insertRecipe(newRecipe);
dbHelper.insertTag(newTag);
dbHelper.close(); }
I found out by debugging that in this case is inserted only the first ingredient. I tried to move the FOR until the end of code, but in that case, are inserted both recipe and tag and always only the first ingredient. I think the problem is relative to the opening/closing of the DB. Can somebody help me?
Ingredient constructor:
public Ingredient(String ingredient_name, int quantity) {
this.ingredient_name = ingredient_name;
this.quantity = quantity;
}
dbHelper.insertIngredient(newIngredient) method:
public boolean insertIngredient(Ingredient ingredient) {
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INGREDIENT_NAME, ingredient.getIngredient_name());
contentValues.put(QUANTITY, ingredient.getQuantity());
contentValues.put(KEY_CREATED_AT, time.getTime().toString());
long result = db.insert(TBL_INGREDIENTS, null, contentValues);
//db.close();
Log.e(TAG, "Ingredient inserted!");
if (result == -1) {
return false;
} else {
return true;
}
}
Ok, thanks to your comment we got the problem :)
You are calling .add(newIngredient) on a list that you initialized with ArrayList<Ingredient> ingredients = null;
Change it to
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
and it will work :)
Good luck!
what im trying to do is look at the json pull all the names to a list view(save the imdbid of that names) and from there you can click on a movie and it will go to a new intent that will bring you the movie that you clicked on with its name summary and an image
im searching in a json with an array in it that looks like this(it based on what the user searched so this is one example...)
{"Search":[{"Title":"Batman Begins","Year":"2005","imdbID":"tt0372784","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg"},{"Title":"Batman v Superman: Dawn of Justice","Year":"2016","imdbID":"tt2975590","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTE5NzU3MTYzOF5BMl5BanBnXkFtZTgwNTM5NjQxODE#._V1_SX300.jpg"},{"Title":"Batman","Year":"1989","imdbID":"tt0096895","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"},{"Title":"Batman Returns","Year":"1992","imdbID":"tt0103776","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BODM2OTc0Njg2OF5BMl5BanBnXkFtZTgwMDA4NjQxMTE#._V1_SX300.jpg"},{"Title":"Batman Forever","Year":"1995","imdbID":"tt0112462","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNWY3M2I0YzItNzA1ZS00MzE3LThlYTEtMTg2YjNiOTYzODQ1XkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg"},{"Title":"Batman & Robin","Year":"1997","imdbID":"tt0118688","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTM1NTIyNjkwM15BMl5BanBnXkFtZTcwODkxOTQxMQ##._V1_SX300.jpg"},{"Title":"Batman: The Animated Series","Year":"1992–1995","imdbID":"tt0103359","Type":"series","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU3MjcwNzY3NF5BMl5BanBnXkFtZTYwNzA2MTI5._V1_SX300.jpg"},{"Title":"Batman: Under the Red Hood","Year":"2010","imdbID":"tt1569923","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTMwNDEyMjExOF5BMl5BanBnXkFtZTcwMzU4MDU0Mw##._V1_SX300.jpg"},{"Title":"Batman: The Dark Knight Returns, Part 1","Year":"2012","imdbID":"tt2313197","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMzIxMDkxNDM2M15BMl5BanBnXkFtZTcwMDA5ODY1OQ##._V1_SX300.jpg"},{"Title":"Batman: Mask of the Phantasm","Year":"1993","imdbID":"tt0106364","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTMzODU0NTYxN15BMl5BanBnXkFtZTcwNDUxNzUyMQ##._V1_SX300.jpg"}],"totalResults":"310","Response":"True"}
so what i want to do is get the imdbid when he clicks on the listview which contains the movie name
this is what i tried:
JSONObject jsonObject = new JSONObject(finalJson);
JSONArray parentArray = jsonObject.getJSONArray("Search");
StringBuffer finalStringBuffer = new StringBuffer();
String imdbid ;
for (int i=0; i<parentArray.length(); i++){
JSONObject finalJsonObject = parentArray.getJSONObject(i);
String movieName = finalJsonObject.getString("Title");
nameOfMovie.add(movieName);
String year = finalJsonObject.getString("Year");
yearOfMovie.add(year);
String omdbID = finalJsonObject.getString("imdbID");
id.add(omdbID);
finalStringBuffer.append(movieName + " , " + year + " , " + omdbID + "\n");
imdbid = omdbID ;
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
but how can i know the imdbid(which is in the movie name that is displayed in a list) that he cliked on?
listview code:
listViewInternetScreen.setClickable(true);
listViewInternetScreen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long i) {
Intent intenttoEditScreen=new Intent(AddFromInternet.this, EditMovie.class);
setResult(RESULT_OK,intenttoEditScreen);
String jsonMovieName = String.valueOf(nameOfMovie);
String jsonMovieSummery = String.valueOf(yearOfMovie);
String jsonImageURL = String.valueOf(id);
intenttoEditScreen.putExtra("json", jsonMovieName);
intenttoEditScreen.putExtra("json", jsonMovieSummery);
intenttoEditScreen.putExtra("json", jsonImageURL);
startActivity(intenttoEditScreen);
}
});
and the search method:
btnGo = (Button) findViewById(R.id.btnGo);
assert btnGo != null;
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MAKE A SEARCH STRING AND PARSE THE RESULT
final String search = "http://www.omdbapi.com/?s=" + EtSearch.getText().toString();
Log.e("JSON", search);
new JSONParser().execute(search);
ArrayList<String> list = new ArrayList<>(nameOfMovie);
arrayAdapter = new ArrayAdapter<>(AddFromInternet.this,
android.R.layout.simple_list_item_1, list);
arrayAdapter.notifyDataSetChanged();
listViewInternetScreen.setAdapter(arrayAdapter);
Log.e("JSON MOVIE", String.valueOf(nameOfMovie));
}
});
thanks for any help :D
Step 1: Use Gson (and Retrofit, if you'd like) to simplify turning a JSON string into a list of Java objects
Step 2: Make a custom ArrayAdapter that loads this list of objects. Then, when you add an Item click listener, you can get that object from the list item you clicked, and start the Intent for showing the full info for that movie.
Additional step would be to make the Movie object Parcelable, so you can add the object to the Intent in one line, rather than each individual field it contains
I'm doing a project right now that is supposed to be a math teaching app for kids.
I'm using firebase as my database to save the user names and password and also to save the questions and their answers.
I have a problem retreiving the question and the answers from the database and display it on the buttons and textview because it appears that the listener for single value event is triggered only when the class is done with all the other commands and i need to use this listener for every question i have.
My database:
My code so far:
ArrayList <Integer> list = new ArrayList<Integer>();
for (int i=1; i<11; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<5; i++) {
ref2 = ref.child(list.get(i).toString());
Questions.cont = false;
getQuestionsFromDb(ref2);
questionView.setText(Questions.question);
button1.setText(Questions.ans1);
button2.setText(Questions.ans2);
button3.setText(Questions.ans3);
button4.setText(Questions.ans4);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Questions.cont = true;
int ans = getAns(Questions.question);
Button b = (Button)v;
int buttonText = Integer.parseInt(b.getText().toString());
if(ans == buttonText) {
Questions.points++;
}
}
});
}
questionView.setText(Questions.points);
// end of for loop
}
private void getQuestionsFromDb(Firebase ref2) {
// TODO Auto-generated method stub
ref2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("aaa");
String question = (String) snapshot.child("question").getValue();
String ans1 = snapshot.child("ans1").getValue().toString();
String ans2 = snapshot.child("ans2").getValue().toString();
String ans3 = snapshot.child("ans3").getValue().toString();
String ans4 = snapshot.child("ans4").getValue().toString();
Questions.question = question;
Questions.ans1 = ans1;
Questions.ans2 = ans2;
Questions.ans3 = ans3;
Questions.ans4 = ans4;
}
#Override
public void onCancelled(FirebaseError arg0) {
// TODO Auto-generated method stub
}
});
}
private int getAns(String ansString) {
// TODO Auto-generated method stub
String[] parts = ansString.split("\\b");
String ans;
if(parts.length == 5) {
ans = parts[0] + parts[1] + parts[2] + parts [3] + parts [4];
}
else {
ans = parts[0] + parts[1] + parts[2];
}
return Integer.parseInt(ans);
}
As you can see i'm also using outer class that have static variables in order to save the questions and the answers and use them out of the inner class.
I hope someone can help.
In your case you should add more listeners addListenerForSingleValueEvent() to get all the data you need or rewrite your logic using addValueEventListener. In that case your data will be actual at any time.
I m using this framework, I already trying many times for making this problem, but I cant do it. I already asking on stackoverflow but no one cant help me. Actually I m tried.
I m using this framework : https://github.com/kikoso/Swipeable-Cards
And I m using SimpleCardStackAdapter like this :
for (int i = 0; i < user.length(); i++) {
final JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
// adapter.add(new CardModel(name, email, image1));
//Set JSON Data in TextView
Log.i("image1image1image1image1", image1);
// CardModel cardModel = new CardModel(" cardModel", " CardModel", r.getDrawable(R.drawable.picture1));
card = new CardModel(name, email, image1);
card.setOnClickListener(new CardModel.OnClickListener() {
#Override
public void OnClickListener() {
Log.i("Swipeable Cards", "I am pressing the card");
// Intent no = new Intent(HomeListview.this, YayDetailActivity.class);
/// startActivity(no);
}
});
card.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
#Override
public void onLike(CardModel card) {
Log.i("Swipeable Cards", "I dislike the card");
}
#Override
public void onDislike(CardModel card) {
Log.i("Swipeable Cards", "I like the card");
// new sendNewYay().execute(sharedToken, card.getTitle());
Toast.makeText(getApplicationContext(), card.getDescription(), Toast.LENGTH_SHORT).show();
}
});
// I m added adapter
adapter.add(card);
mCardContainer.setAdapter(adapter);
}
At the onDislike method, I need to get item name.
in this line : new sendNewYay().execute(sharedToken, name);
I send the item name, But it dont work.
1.How can I get the item name, in this method?
2.I have two button, one of them for onLike method, another one for onDislike Method. Ho can I triggered this two method with my button?
Thank you.
Decleare two variable global as string
String itemname;
try {
JSONArray c = new JSONArray(user.toString());
for (int i = 0 ; i < c.length();i++) {
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
System.out.println("Position : " + "" + i + ""+ c.getString(i));
itemname = name.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Final itemname is " + itemname);
Iam trying to fetch a value from the last row in my sqlite database and use it for multiplication and division in my main activity to get a certain result. But I get the multiplication result as 0 and division result as "infinity". Can anyone help!!
heres the code
food.java (main activity)
{
//user inputs
ETRate = (EditText)findViewById(R.id.ETRate);
ETFoodQty =(EditText)findViewById(R.id.ETFoodQty;
ETRate.setOnFocusChangeListener(this);
ETFoodQty.setOnFocusChangeListener(this);
FoodStorage foodGetInfo = new FoosStorage(this);
foodGetInfo.open();
foodGetInfo.getAvgTotal(this);
foodGetInfo.close();
chkLastTotal1.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
isChkLastTotal1=true;
}
});
public void onFocusChange(View predictionFocusView, boolean hasPredictionETFocus)
{
if(ETRate.isFocused())
{
if(foodQty!=0) //here I get rate =0
{
rate =(long) (lastTotal*foodQty);
setRate(rate);
ETRate.setText(String.valueOf(rate));
}
}
else if(foodQty.isFocused()) //Here I get foodQty = infinity
{
if(rate!=0)
{
foodQty =rate/avgtotal;
setPredictFoodQty(foodQty);
ETfoodQty.setText(String.valueOf(foodQty));
}
}
foodStorage.java (database file)
public void getAvgtotal(food pd)
{
String [] columns = new String[]{KEY_ROW_ID, KEY_RATE, KEY_FOOD_QTY, KEY_FOOD_PRICE, KEY_QUALITY, KEY_TOTAL, KEY_DATE,KEY_GRADE};
if(pd.isChkLastTotal1()==true)
{
Cursor c= ourDatabase.rawQuery("SELECT * FROM food_table ORDER BY _id DESC LIMIT 1", null);
c.moveToFirst();
if(c!=null && c.getCount()>0)
{
c.moveToLast();
String getLastTotal =c.getString(5);
food myFoodInfo = new Food();
myFoodInfo.setavgTotal(Double.parseDouble(getLastTotal));
}
c.close();
}
}
Here
food myFoodInfo = new Food();
myFoodInfo.setavgTotal(Double.parseDouble(getLastTotal));
You are creating new Food object
Why don't you set values to pd passing here:
public void getAvgtotal(food pd)