The app has an order button when it's clicked the gmail app should be opened with subject and body filed desirably but the intent for it in my code is not working and the app shows a message that it is unfortunately stopping. I've tried many ways to implement this but i'm unable to do so.
package com.example.android.justjava;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import java.text.NumberFormat;
import static android.R.attr.value;
import static android.R.id.checkbox;
import static android.R.id.message;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int topping_price = 0;
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
String variable1,variable2,variable3;
CheckBox cream = (CheckBox) findViewById(R.id.checkbox);
CheckBox choco = (CheckBox) findViewById(R.id.checkbox_choco);
boolean value1 = cream.isChecked();
boolean value2 = choco.isChecked();
if(value1 == true) {
variable1 = "Yes";
topping_price += 1;
}
else
variable1 = "No" ;
if(value2 == true) {
variable2 = "Yes";
topping_price += 2;
}
else
variable2 = "No" ;
EditText input_name = (EditText) findViewById(R.id.name);
variable3 = input_name.getText().toString();
if((quantity + count) == 0){
topping_price = 0;
variable1 = "No";
variable2 = "No";
}
String price_message = "Whipped cream topping: " + variable1 + "\nChocolate topping: " + variable2 +"\nName: " + variable3 +"\nQuantity: " + (quantity + count) +"\nTotal $" + (( quantity + count ) * 10 + topping_price ) + "\nThank You";
displayMessage(price_message);
topping_price = 0 ;
Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
sendIntent.setType("*/*");
sendIntent.setData(Uri.parse("masquerade0097#gmail.com"));
sendIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "masquerade0097#gmail.com" });
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Just Java order for " + variable3);
sendIntent.putExtra(Intent.EXTRA_TEXT,"Whipped cream topping: " + variable1 + "\nChocolate topping: " + variable2 +"\nName: " + variable3 +"\nQuantity: " + (quantity + count) +"\nTotal $" + (( quantity + count ) * 10 + topping_price ) + "\nThank You");
// startActivity(sendIntent);
if (sendIntent.resolveActivity(getPackageManager()) != null) {
startActivity(sendIntent);
}
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String message) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(message);
}
int quantity = 1;
int count = 0;
public void increment(View view){
if((quantity + count) < 101)
count = count + 1;
display(quantity + count );
displayPrice( (quantity + count) * 10);
}
public void decrement(View view){
if((quantity + count) != 0)
count = count - 1;
display(quantity + count);
displayPrice((quantity + count) * 10);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
private void displayPrice(int number){
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}
You can try with this code. This will open chooser from where you can select gmail app.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_TEXT, "Text you want to share");
startActivity(Intent.createChooser(intent, "Send mail..."));
If you specifically want to open gmail app then use this
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("test#gmail.com"));
sendIntent.setClassName("com.google.android.gm","com.google.android.gm.ComposeActivityGmail");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "test#gmail.com" });
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Test");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Test");
startActivity(sendIntent);
but this code may fail if the package name changes or if the package name does not exist.So better use this(along with intent chooser)
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", emailId, null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.putExtra(Intent.EXTRA_TEXT, "");
startActivity(Intent.createChooser(emailIntent, "Send email..."));
use intent.setType("message/rfc822") in the Intent
To open the Gmail App, use the following code:
Intent mailClient = new Intent(Intent.ACTION_VIEW);
mailClient.setClassName("com.google.android.gm", "com.google.android.gm.ConversationListActivity");
startActivity(mailClient);
To have the fields to, subject and body pre-filled, you can put extras in the intent like this:
mailClient.putExtra(Intent.EXTRA_EMAIL, new String[] { "hello#gmail.com" });
mailClient.putExtra(Intent.EXTRA_SUBJECT, "hello subject");
mailClient.putExtra(Intent.EXTRA_TEXT, "hello message");
Related
Hello i have an android project ongoing at the moment. The user must answer a maths question then point should be awarded/taken away for the answer then the code should display a second different question until 10 questions have been completed. The problem is that the code skips the loop and instantly finishes the game. I have attempted using a while loop but the same problem happened. I thought about an if but couldn't work out how to re run the if. Below is the whole code of the project but the main problem is the for loop.
package com.example.mixmathsv3;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class SimpleModeActivity extends AppCompatActivity {
Button checkButt, nextQuestionButt;
TextView resultText, simpleQuestionText, scoreText, questionNumberText;
EditText userAnswer;
public volatile int completedTimes = 0;
public int scoreValue = 0;
public int intUserAnswer = 0;
public String questionAnswer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_mode);
resultText = (TextView) findViewById(R.id.result);
checkButt = (Button) findViewById(R.id.checkButt);
simpleQuestionText = (TextView) findViewById(R.id.simpleQuestionText);
scoreText = (TextView) findViewById(R.id.scoreText);
userAnswer = (EditText) findViewById(R.id.userAnswer);
//nextQuestionButt = (Button) findViewById(R.id.nextQuestion/Butt);
//questionNumberText = (TextView) findViewById(R.id.questionNumberText);
final String[] questionArray = {"5+2", "10+3", "7+1", "9+0", "1+6"};
final String[] answerArray = {"7", "13", "8", "9", "7"};
final Random r = new Random();
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
for (int i = 1; i < 11; i++) {
//System.out.println(i);
//Toast.makeText(getApplicationContext(), ("loop successful"), Toast.LENGTH_SHORT).show();
checkButt.setEnabled(true);
checkButt.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View v) {
checkButt.setEnabled(false);
intUserAnswer = Integer.parseInt(userAnswer.getText().toString());
int intQuestionAnswer = Integer.parseInt(questionAnswer);
if (intUserAnswer == intQuestionAnswer) {
resultText.setText("Correct");
scoreValue = scoreValue + 10;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes);
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
if (intUserAnswer != intQuestionAnswer) {
resultText.setText("Incorrect");
scoreValue = scoreValue - 5;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes)
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
}
});
}
Toast.makeText(getApplicationContext(), ("Game Over"), Toast.LENGTH_SHORT).show();
setOnClickListener does not do what you think :
setOnClickListener is used to register a method that will be called only if the user click on the button.
In your example, the for-loop register 10 times a new onClickListener which is not what we want.
In your case, you must not use the for-loop which is executed instantly. Change the question and the text when the user clicked on the button.
final String[] questionArray = {"5+2", "10+3", "7+1", "9+0", "1+6"};
final String[] answerArray = {"7", "13", "8", "9", "7"};
final Random r = new Random();
int answered = 0;
// Initial question
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
checkButt.setEnabled(true);
checkButt.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View v) {
checkButt.setEnabled(false);
intUserAnswer = Integer.parseInt(userAnswer.getText().toString());
int intQuestionAnswer = Integer.parseInt(questionAnswer);
if (intUserAnswer == intQuestionAnswer) {
resultText.setText("Correct");
scoreValue = scoreValue + 10;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes);
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
if (intUserAnswer != intQuestionAnswer) {
resultText.setText("Incorrect");
scoreValue = scoreValue - 5;
//completedTimes = + 1;
//questionNumberText.setText(completedTimes)
Toast.makeText(getApplicationContext(), ("Your Score is " + scoreValue), Toast.LENGTH_SHORT).show();
}
answered++;// We update the count of answered question
if(answered == 10) {
// Finish
Toast.makeText(getApplicationContext(), ("Game Over"), Toast.LENGTH_SHORT).show();
} else {
// Change question
int arrayRandom = r.nextInt(questionArray.length);
simpleQuestionText.setText(questionArray[arrayRandom]);
questionAnswer = (answerArray[arrayRandom]);
}
}
});
I suggest you to learn more about how Android is working and callback methods.
You don't need to put everything in the loop. Move all logic outside the loop and it should work.
Hello I just wanna ask about this code, the problem is I just want to show the getData in an EditTextview. But it only shows in a toast what do you think will be thre revisions needed for my code to call the data in getData into a EditText thank you so much for the help.
package com.example.serviceapplication;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class Timeinsms extends AppCompatActivity {
DatabaseHelper myDb;
EditText editTextId,editTextsmsi;
Button btngetData,btnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeinsms);
myDb = new DatabaseHelper(this);
editTextId = (EditText) findViewById(R.id.editText_idin);
btngetData = (Button) findViewById(R.id.button_view);
btnView = (Button) findViewById(R.id.button_viewALL);
getData();
viewAll();
}
public void getData() {
btngetData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = editTextId.getText().toString();
if (id.equals(String.valueOf(""))) {
editTextId.setError("Enter id to get data");
return;
}
Cursor res = myDb.getData(id);
String data = null;
if (res.moveToFirst()) {
data =
"Id:" + res.getString(0) + "\n\n" +
"Time In :" + res.getString(1) + "\n\n" +
"Customer :" + res.getString(2) + "\n\n"+
"Branch :" + res.getString(3) + "\n\n"+
"Machine :" + res.getString(4) + "\n\n";
}
showMessage("TIME OUT FORM"+"\n\n", data);
}
});
}
public void viewAll(){
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res=myDb.getAllData();
if(res.getCount() == 0) {
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer=new StringBuffer();
while(res.moveToNext()){
buffer.append("Id:"+res.getString(0)+"\n\n");
buffer.append("Time :"+ res.getString(1)+"\n\n");
buffer.append("Customer :"+ res.getString(2)+"\n\n");
buffer.append("Branch :"+ res.getString(3)+"\n\n");
buffer.append("Machine :"+ res.getString(4)+"\n\n\n");
}
showMessage("Time In History",buffer.toString());
}
});
}
private void showMessage(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.create();
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
You are not showing it in a Toast, you are using an Alertdialog to Show your Message.
This would be a Toast
Toast.makeText(this,"MESSAGE TO SHOW",Toast.LENGTH_LONG).show();
At this Position
data = "Id:" + res.getString(0) + "\n\n" +
"Time In :" + res.getString(1) + "\n\n" +
"Customer :" + res.getString(2) + "\n\n"+
"Branch :" + res.getString(3) + "\n\n"+
"Machine :" + res.getString(4) + "\n\n";
you are already creating a String which contains all your data, you only have to set your Edittext with this String.
editTextId.setText("TIME OUT FORM"+"\n\n"+data);
This must be placed inside the OnClick method, as data is a local variable at this method.
I'm working on a PiggyBank-like application wherein users can make wishlists of their wanted item and helps them save for that item. My app is still in prototype because i'm still learning android.
The problem i'm experiencing right now is every time i add a new data, it always returns false. Here's my code:
DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "price";
private static final String COL4 = "totalsavings";
private static final String COL5 = "duedate";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Returns all the data from database
* #return
*/
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Returns only the ID that matches the name passed in
* #param name
* #return
*/
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Updates the name field
* #param newName
* #param id
* #param oldName
*/
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
" = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
/**
* Delete from database
* #param id
* #param name
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
}
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
private EditText editText, editText2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for inputs
editText = (EditText) findViewById(R.id.editText);
editText2 =(EditText) findViewById(R.id.editText2);
//buttons
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
//call database
mDatabaseHelper = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("You must put something in the text field!");
}
String newPriceEntry = editText2.getText().toString();
if (editText2.length() != 0) {
AddData(newPriceEntry);
editText2.setText("");
} else {
toastMessage("You must put something in the text field!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListDataActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by User on 2/28/2017.
*/
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
EditDataActivity.java
In this activity, the data will be displayed in an EditText (name), the savings goal (price). (I'm still working on the totalsavings).
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private TextView myGoal, mySavings;
private Button btnSave,btnDelete, btnDeposit;
private EditText editable_item, depositInput;
DatabaseHelper mDatabaseHelper;
private String selectedName, selectedPrice;
private int selectedID, selectedTotalSavings;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
myGoal = (TextView) findViewById(R.id.displayGoal);
mySavings = (TextView) findViewById(R.id.displayTotalSavings);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnDeposit = (Button) findViewById(R.id.btnDeposit);
editable_item = (EditText) findViewById(R.id.editable_item);
mDatabaseHelper = new DatabaseHelper(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//now get the price we passed as an extra
selectedPrice = receivedIntent.getStringExtra("price");
//now we get the totalsavings we passed as an extra
selectedTotalSavings = receivedIntent.getIntExtra("totalsavings", -1);
//set the text to show the current selected name
editable_item.setText(selectedName);
//set the text to show the user's saving goal
myGoal.setText(selectedPrice);
//set text to show the user's total savings so far
mySavings.setText(selectedTotalSavings);
//-----------------------------------DIALOG BOX-----------------------------------------
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter Deposit");
builder.setMessage("Enter your deposit!");
depositInput= new EditText(this);
builder.setView(depositInput);
//SET POSITIVE BUTTON
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String depositTxt=depositInput.getText().toString();
selectedTotalSavings = Integer.parseInt(selectedTotalSavings + depositTxt);
mySavings.setText(selectedTotalSavings);
Toast.makeText(getApplicationContext(),depositTxt, Toast.LENGTH_LONG).show();
}
});
//SET NEGATIVE BUTTON
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//CREATE THE DIALOG
final AlertDialog depositPrompt=builder.create();
//--------------------------------------------------------------------------------------
//buttons
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item = editable_item.getText().toString();
if(!item.equals("")){
mDatabaseHelper.updateName(item,selectedID,selectedName);
}else{
toastMessage("You must enter a name");
}
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
editable_item.setText("");
toastMessage("removed from database");
}
});
btnDeposit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
depositPrompt.show();
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
Here's the Sample Syntax
User enters details for name and price
User clicks add data
User can View Data and the data will be displayed on a ListView
User can edit and view data in the EditDataActivity
I'm not sure what the problem is.
UPDATE
so i found this code on the MainActivity Class. I'm trying to add the data from editText2 but i don't know how.
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("You must put something in the text field!");
}
String newPriceEntry = editText2.getText().toString();
if (editText2.length() != 0) {
AddData(newPriceEntry);
editText2.setText("");
} else {
toastMessage("You must put something in the text field!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
Do i have to make a new AddData?
You need to insert the right type of values as mentioned below :
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item); // pass an integer instead of a String as you have mentioned its datatype as INTEGER or parse it using Integer.parseInt()
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
The problem I think is in the CREATE TABLE query.
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
There is no space between COL3 and "TEXT" (same for COL4 and "INTEGER"). So just add a space like so.
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + " TEXT, " + COL4 +" INTEGER)";
Problem is in your addData() method. COL4 holds INTEGER value.
Try this:
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, Integer.parseInt(item));
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
The return of db.insert() is a long and you're comparing it to an int. Change
if (result == -1) {
return false;
} else {
return true;
}
To
return (int)result == -1;
package com.davidcleary.numberguesser;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int randomNumber;
boolean isRight;
public void randomGenerator(View view) {
boolean isRight = false;
EditText guess = (EditText) findViewById(R.id.guessText);
String myGuess = guess.getText().toString();
int guessInt = new Integer(guess.getText().toString());
if (guessInt == randomNumber) {
Toast.makeText(getApplicationContext(), "You Guessed The Right Number!!! " + "( " + guessInt + " )" , Toast.LENGTH_LONG).show();
guess.setText("");
isRight = true;
} else if (guessInt > randomNumber) {
Toast.makeText(getApplicationContext(), "Your Guess Is Too High! " + "( " + guessInt + " )", Toast.LENGTH_SHORT).show();
guess.setText("");
} else {
Toast.makeText(getApplicationContext() , "Your Guess Is Too Low! " + "( " + guessInt + " )", Toast.LENGTH_SHORT).show();
guess.setText("");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randNum = new Random();
randomNumber = randNum.nextInt(21);
if (isRight == true) {
randomNumber = randNum.nextInt(21);
}
}
}
I am trying to change the value of 'randomNumber' when the user guesses the right number to a different random value but I have not found the solution. I have tried to use a boolean but that did not work as it came up with an error "Variable 'randNum' is already defined in the scope"
Any help would be greatly appreciated.
Juggle a few variables to fix your scopes....
package com.androidapps.numberguesser;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int randomNumber;
Random randNum = new Random();
public void randomGenerator(View view) {
EditText guess = (EditText) findViewById(R.id.guessText);
String myGuess = guess.getText().toString();
int guessInt = new Integer(guess.getText().toString());
if (guessInt == randomNumber) {
Toast.makeText(getApplicationContext(), "You Guessed The Right Number!!! " + "( " + guessInt + " )" , Toast.LENGTH_LONG).show();
guess.setText("");
randomNumber = randNum.nextInt(21);
} else if (guessInt > randomNumber) {
Toast.makeText(getApplicationContext(), "Your Guess Is Too High! " + "( " + guessInt + " )", Toast.LENGTH_SHORT).show();
guess.setText("");
} else {
Toast.makeText(getApplicationContext() , "Your Guess Is Too Low! " + "( " + guessInt + " )", Toast.LENGTH_SHORT).show();
guess.setText("");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
randomNumber = randNum.nextInt(21);
}
}
Not totally sure that I understand your question, but...
You probably want to re-use the java.util.Random you're using, so I'd move it into being a property of your Activity instead of a local:
public class MainActivity extends AppCompatActivity {
int randomNumber;
Random generator;
And then you can initialize these variables in your onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generator = new Random();
randomNumber = generator.nextInt(21);
}
and then, finally, after a correct guess, set the randomNumber to a new value:
if (guessInt == randomNumber) {
Toast.makeText(getApplicationContext(),
"You Guessed The Right Number!!! (" + guessInt + ")",
Toast.LENGTH_LONG).show();
guess.setText("");
randomNumber = generator.nextInt(21);
} // ... etc
package com.davidcleary.numberguesser;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int randomNumber;
Random randNum = new Random();
public void randomGenerator(View view) {
boolean isRight = false;
EditText guess = (EditText) findViewById(R.id.guessText);
String myGuess = guess.getText().toString();
int guessInt = new Integer(guess.getText().toString());
if (guessInt == randomNumber) {
Toast.makeText(getApplicationContext(), "You Guessed The Right Number!!! " + "( " + guessInt + " )" , Toast.LENGTH_LONG).show();
guess.setText("");
randomNumber = randNum.nextInt(21);
} else if (guessInt > randomNumber) {
Toast.makeText(getApplicationContext(), "Your Guess Is Too High! " + "( " + guessInt + " )", Toast.LENGTH_SHORT).show();
guess.setText("");
} else {
Toast.makeText(getApplicationContext() , "Your Guess Is Too Low! " + "( " + guessInt + " )", Toast.LENGTH_SHORT).show();
guess.setText("");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
randomNumber = randNum.nextInt(21);
}
}
Thanks everyone for the quick responses! My problem has been solved.
I have an app that records the accelerometer data and send a SMS when a treshhold is passed. It works fine when the phone is awake. What do I need to do so this is also do the same when the phone is locked/sleeping:
I have two activites SendSMSActivity.java:
package com.example.sendsms;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.FilterQueryProvider;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class SendSMSActivity extends Activity implements SensorEventListener {
SendSMS mSender = new SendSMS();
private SensorManager senSensorManager;
private Sensor senAccelerometer;
private long lastUpdate;
private float last_x, last_y, last_z;
//Contacts variable
AutoCompleteTextView emailText;
ContentResolver cr;
SimpleCursorAdapter emailAdapter;
protected void onResume() {
super.onResume();
senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
senSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
//To change body of implemented methods use File | Settings | File Templates.
Sensor mySensor = sensorEvent.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
long curTime = System.currentTimeMillis();
// only allow one update every 100ms.
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
float speed = Math.abs(x+y+z - last_x - last_y - last_z)/ diffTime * 10000;
TextView threshText = (TextView)findViewById(R.id.thresh);
if (speed > Float.parseFloat(threshText.getText().toString())) {
Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
TextView resultText = (TextView)findViewById(R.id.xacc);
resultText.setText("shake detected w/ speed: " + speed);
sendit2();
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// can be safely ignored for this demo
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get an instance of the SensorManager
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
//Contacts
cr = getContentResolver();
emailText = (AutoCompleteTextView) findViewById(R.id.mobileNo);
String[] fromCols = {
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.DATA,
};
int[] toViewIds = { R.id.list_name, R.id.list_email };
emailAdapter = new SimpleCursorAdapter(this, R.layout.email_and_name, getNamesAndEmails(null), fromCols, toViewIds);
// Important 1: You have to provide a way of making the chosen choice look presentable.
// emailAdapter.setStringConversionColumn(1); // 1=DISPLAY_NAME, 2=Email
emailAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
#Override
public CharSequence convertToString(Cursor cursor) {
return String.format("%s <%s>", cursor.getString(1).trim(), cursor.getString(2).trim());
}
});
// Important 2: You have to provide a query containing the values on demand
emailAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
String partialItemName = null;
if (constraint != null) {
partialItemName = constraint.toString();
}
return getNamesAndEmails(partialItemName);
}
});
emailText.setAdapter(emailAdapter);
}
//Contacts
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
final static String[] PROJECTION = new String[] {
ContactsContract.RawContacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.DATA,
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
};
/** Get the contacts that have email addresses matching "partialName".
* #author Modified from code obtained from
* http://stackoverflow.com/questions/5205999/android-get-a-cursor-only-with-contacts-that-have-an-email-listed-android-2-0
* #return
*/
Cursor getNamesAndEmails(String partialName) {
// Look for partialName either in display name (person name) or in email
final String filter =
ContactsContract.Contacts.DISPLAY_NAME + " LIKE '%" + partialName + "%'" +
" OR " +
ContactsContract.CommonDataKinds.Phone.DATA + " LIKE '%" + partialName + "%'";
// If display name contains "#" (maybe it's null so Contacts provides email here),
// order by email, else order by display name.
final String order = "CASE WHEN "
+ ContactsContract.Contacts.DISPLAY_NAME
+ " NOT LIKE '%#%' THEN 1 ELSE 2 END, "
+ ContactsContract.Contacts.DISPLAY_NAME
+ ", "
+ ContactsContract.CommonDataKinds.Phone.DATA
+ " COLLATE NOCASE";
// Now make a Cursor containing the contacts that now match partialName as per "filter".
return cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, filter, null, order);
}
public void sendit(View v) {
TextView mobileNum = (TextView)findViewById(R.id.mobileNo);
boolean success = mSender.sendSMSMessage(mobileNum.getText().toString(),
// This is standard lorem-ipsum text, do not bother
// trying to wrap it, there's about 500 characters...
"Movement detected."
);
Toast.makeText(this, "Message sent " + (
success ? "successfully" : "unsuccessfully"),
Toast.LENGTH_SHORT).show();
TextView resultText = (TextView)findViewById(R.id.xacc);
resultText.setText("Message Sent");
}
public void sendit2() {
TextView mobileNum = (TextView)findViewById(R.id.mobileNo);
boolean success = mSender.sendSMSMessage(mobileNum.getText().toString(),
// This is standard lorem-ipsum text, do not bother
// trying to wrap it, there's about 500 characters...
"Movement detected."
);
Toast.makeText(this, "Message sent " + (
success ? "successfully" : "unsuccessfully"),
Toast.LENGTH_SHORT).show();
TextView resultText = (TextView)findViewById(R.id.xacc);
resultText.setText("Message Sent");
}
}
and SendSMS.java:
package com.example.sendsms;
import java.util.ArrayList;
import android.telephony.SmsManager;
import android.util.Log;
/** The code for dealing with the SMS manager;
* called from the GUI code.
*/
public class SendSMS {
static String TAG = "SendSMS";
SmsManager mSMSManager = null;
/* The list of message parts our messge
* gets broken up into by SmsManger */
ArrayList<String> mFragmentList = null;
/* Service Center - not used */
String mServiceCentreAddr = null;
SendSMS() {
mSMSManager = SmsManager.getDefault();
}
/* Called from the GUI to send one message to one destination */
public boolean sendSMSMessage(
String aDestinationAddress,
String aMessageText) {
if (mSMSManager == null) {
return (false);
}
mFragmentList = mSMSManager.divideMessage(aMessageText);
int fragmentCount = mFragmentList.size();
if (fragmentCount > 1) {
Log.d(TAG, "Sending " + fragmentCount + " parts");
mSMSManager.sendMultipartTextMessage(aDestinationAddress,
mServiceCentreAddr,
mFragmentList, null, null);
} else {
Log.d(TAG, "Sendine one part");
mSMSManager.sendTextMessage(aDestinationAddress,
mServiceCentreAddr,
aMessageText, null, null);
}
return true;
}
}