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.
Related
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 would like to ask something about Store Android Data to SQLite Database (I am new to SQLite Database). I have been trying to store data to SQLite Database, but when I saw the database with SQLiteStudio the data was empty.
This is my code :
DatabaseHelper.java
package com.example.toolsmanager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "btm.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static final String TABLE_1 = "oneroundsingle";
public static final String TABLE1_COLUMN1 = "_ID";
public static final String TABLE1_COLUMN2 = "GAMETYPE";
public static final String TABLE1_COLUMN3 = "PLAYER1";
public static final String TABLE1_COLUMN4 = "PLAYER2";
public static final String TABLE1_COLUMN5 = "SCORE";
public static final String TABLE1_COLUMN6 = "WINNER";
public static final String CREATE_TABLE_ORS = "create table" + TABLE_1 + " ( " +
TABLE1_COLUMN1 + " integer primary key autoincrement, " +
TABLE1_COLUMN2 + " text, " +
TABLE1_COLUMN3 + " text, " +
TABLE1_COLUMN4 + " text, " +
TABLE1_COLUMN5 + " text, " +
TABLE1_COLUMN6 + " text " + ");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_ORS);
db.execSQL(CREATE_TABLE_ORD);
db.execSQL(CREATE_TABLE_RS);
db.execSQL(CREATE_TABLE_RD);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists" + TABLE_1);
db.execSQL("drop table if exists" + TABLE_2);
db.execSQL("drop table if exists" + TABLE_3);
db.execSQL("drop table if exists" + TABLE_4);
onCreate(db);
}
}
OR_SingleCount.java
package com.example.toolsmanager;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class OR_SingleCount extends AppCompatActivity {
int player1_score, player2_score, final_score;
TextView text_player1_name, text_player2_name;
String score, winner;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_or_single_count);
text_player1_name = (TextView)findViewById(R.id.player1_name);
text_player1_name.setText(getIntent().getExtras().getString("player1"));
text_player2_name = (TextView)findViewById(R.id.player2_name);
text_player2_name.setText(getIntent().getExtras().getString("player2"));
}
public void singleCount(View v) {
int id = v.getId();
if (id == R.id.player1_plus) {
player1_score += 1;
TextView text_player1_score = (TextView) findViewById(R.id.player1_score);
text_player1_score.setText(String.valueOf(player1_score));
} else if (id == R.id.player1_minus && player1_score != 0) {
player1_score -= 1;
TextView text_player1_score = (TextView) findViewById(R.id.player1_score);
text_player1_score.setText(String.valueOf(player1_score));
} else if (id == R.id.player2_plus) {
player2_score += 1;
TextView text_player2_score = (TextView) findViewById(R.id.player2_score);
text_player2_score.setText(String.valueOf(player2_score));
} else if (id == R.id.player2_minus && player2_score != 0) {
player2_score -= 1;
TextView text_player2_score = (TextView) findViewById(R.id.player2_score);
text_player2_score.setText(String.valueOf(player2_score));
}
finalScore();
}
public void finalScore(){
if ((player1_score == 21 && player2_score < 20) || (player2_score == 21 && player1_score < 20)) {
final_score = 21;
getWinner();
} else if (player1_score == 30 || player2_score == 30) {
final_score = 30;
getWinner();
} else if (player1_score >= 20 && player2_score >= 20) {
if (player1_score == player2_score + 2) {
final_score = player1_score;
getWinner();
} else if (player2_score == player1_score + 2) {
final_score = player2_score;
getWinner();
}
}
}
public void getWinner() {
if (player1_score == final_score){
winner = text_player1_name.getText().toString();
String print_winner = winner + " is the winner";
Toast.makeText(getApplicationContext(),print_winner, Toast.LENGTH_LONG).show();
} else if(player2_score == final_score) {
winner = text_player2_name.getText().toString();
String print_winner = winner + " is the winner";
Toast.makeText(getApplicationContext(), print_winner, Toast.LENGTH_LONG).show();
}
score = player1_score + " - " + player2_score;
String gametype = "Single";
addORSingleData(gametype,
text_player1_name.getText().toString(),
text_player2_name.getText().toString(),
score,
winner);
AlertDialog repeatdialog= new AlertDialog.Builder(this)
.setTitle("Game Finish")
.setMessage("Do you want to repeat the game?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
player1_score = 0;
player2_score = 0;
recreate();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(OR_SingleCount.this, OneRoundMatch.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}).create();
repeatdialog.show();
}
public void addORSingleData(String gametype, String player1, String player2, String score, String winner){
databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TABLE1_COLUMN2, gametype);
contentValues.put(DatabaseHelper.TABLE1_COLUMN3, player1);
contentValues.put(DatabaseHelper.TABLE1_COLUMN4, player2);
contentValues.put(DatabaseHelper.TABLE1_COLUMN5, score);
contentValues.put(DatabaseHelper.TABLE1_COLUMN6, winner);
db.insert(DatabaseHelper.TABLE_1, null, contentValues);
}
}
What's wrong with my code?
I've never used SQLite Studio so I couldn't trouble shoot that issue if I wanted to but you could set up a cursor:
Cursor cursor = db.query(TABLE_NAME,null,null,null,null,null,null);
then call
Toast.makeText(this, "" + cursor.getCount(), Toast.LENGTH_SHORT).show();
to see if you're inserting any data. Also, what are the extra tables in your onCreate method?
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");
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;
}
}
Here is the java activity that provide to add data for record in SQLite. My question is how i insert some code for when clicking button and it will show second activity. i don't know where i should insert. And don't know what the code should be. please help me.
import java.sql.PreparedStatement;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class AddStudent extends Activity {
DatabaseStudent mHelper;
SQLiteDatabase mDb;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
mHelper = new DatabaseStudent(this);
mDb = mHelper.getWritableDatabase();
final EditText editName = (EditText)findViewById(R.id.editName);
final EditText editLastName = (EditText)findViewById(R.id.editLastName);
ImageView buttonAdd = (ImageView)findViewById(R.id.imageAdd);
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String name = editName.getText().toString();
String lastname = editLastName.getText().toString();
String condition = getIntent().getStringExtra("Condition");
double school = getIntent().getDoubleExtra("Intent", 0);
//Date&Time
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
if(name.length() != 0 && lastname.length() != 0
) {//&& school.length() != 0
Cursor mCursor = mDb.rawQuery("SELECT * FROM "
+ DatabaseStudent.TABLE_NAME + " WHERE "
+ DatabaseStudent.COL_NAME + "='" + name + "'"
+ " AND " + DatabaseStudent.COL_LASTNAME + "='"
+ lastname + "'" + " AND "
+ DatabaseStudent.COL_SCHOOL + "='" + school //add COL_SCHOOL = currentTime
+ "'"+ " AND " + DatabaseStudent.COL_TIME + "='" + currentTime
+ "'"+ " AND " + DatabaseStudent.COL_CON + "='" + condition
+ "'", null);
if(mCursor.getCount() == 0) {
mDb.execSQL("INSERT INTO " + DatabaseStudent.TABLE_NAME
+ " (" + DatabaseStudent.COL_NAME
+ ", " + DatabaseStudent.COL_LASTNAME
+ ", " + DatabaseStudent.COL_SCHOOL
+ ", " + DatabaseStudent.COL_TIME
+ ", " + DatabaseStudent.COL_CON
+ ") VALUES ('" + name + "', '" + lastname
+ "', '" + school + "', '" + currentTime + "', '" + condition + "');");
editName.setText("");
editLastName.setText("");
Toast.makeText(getApplicationContext()
, "Already added"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext()
, "This data is exist"
, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext()
, "Please fill in the blank"
, Toast.LENGTH_SHORT).show();
}
}
});
}
public void onStop() {
super.onStop();
mHelper.close();
mDb.close();
}
}
You'd want to insert any code you want executed when you hit a button in the onClick method, which you have as seen here:
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do stuff when buttonAdd is clicked
}
});
Now you can use intents inside the onClick method to begin a second activity, like so:
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(current_activity.this, second_activity.class);
startActivity(intent);
}
});
You can consult the following for more details: http://developer.android.com/training/basics/firstapp/starting-activity.html