How to use intent to open email application - java

Hi am new to android development and have come across a problem. I am whatching this tutorial video from http://www.youtube.com/watch?v=Sqk154QSe8Y#t=158 (The New Boston) and as far as I can tell I have the same exact code however the for some reason my code won't open email app on the tap of the button and the call of the Intent
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailaddress);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I hate you");
emailIntent.setType("plain/type");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
The button does work because I am capable of changing text color but the email intent does not open
I there something I am doing wrong??
This is the complete code---
package com.infitenothing.word;
import com.infitenothing.dogcat.R;
import android.R.anim;
import android.R.layout;
import android.app.Activity;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Email extends Activity implements View.OnClickListener {
EditText personsEmail, intro, personsName, stupidThings, hatefulAction,
outro;
String emailAdd, beginning, name, stupidAction, hatefulAct, out;
Button sendEmail;
TextView color;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.email);
initializeVars();
sendEmail.setOnClickListener(this);
}
private void initializeVars() {
// TODO Auto-generated method stub
personsEmail = (EditText) findViewById(R.id.etEmails);
intro = (EditText) findViewById(R.id.etIntro);
personsName = (EditText) findViewById(R.id.etName);
stupidThings = (EditText) findViewById(R.id.etThings);
hatefulAction = (EditText) findViewById(R.id.etAction);
outro = (EditText) findViewById(R.id.etOutro);
sendEmail = (Button) findViewById(R.id.bSentEmail);
color = (TextView) findViewById(R.id.colors);
}
public void onClick(View v) {
// TODO Auto-generated method stub
color.setTextColor(Color.RED);
convertEditTextVarsIntoStringsAndYesThisIsAMethodWeCreated();
String emailaddress[] = { emailAdd };
String message = "Well hello "
+ name
+ " I just wanted to say "
+ beginning
+ ". Not only that but I hate when you "
+ stupidAction
+ ", that just really makes me crazy. I just want to make you "
+ hatefulAct
+ ". Welp, thats all I wanted to chit-chatter about, oh and"
+ out
+ ". Oh also if you get bored you should check out www.mybringback.com"
+ '\n' + "PS. I think I love you... :(";
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
//Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailaddress);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I hate you");
emailIntent.setType("plain/type");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
}
private void convertEditTextVarsIntoStringsAndYesThisIsAMethodWeCreated() {
// TODO Auto-generated method stub
emailAdd = personsEmail.getText().toString();
beginning = intro.getText().toString();
name = personsName.getText().toString();
stupidAction = stupidThings.getText().toString();
hatefulAct = hatefulAction.getText().toString();
out = outro.getText().toString();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}

You have created the intent, but never signaled it to execute. Add this code :
startActivity(Intent.createChooser(emailIntent, "Send Email"));

try this out and may be you can find what you were missing in your code
Intent it = new Intent(Intent.ACTION_SEND);
it.setData(Uri.parse("mailto:"));
String [] to = {"Your-Email#example.com"};
it.putExtra(Intent.EXTRA_EMAIL, to);
it.putExtra(Intent.EXTRA_SUBJECT, "Hii this was sent from my App");
it.putExtra(Intent.EXTRA_TEXT, "Hey Whatsupp!! ,how yuo doing ???");
it.setType("message/rfc822");
chooser = Intent.createChooser(it, "Launch Email");
startActivity(chooser);

Related

Button Code Crashes App [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am creating my second app and having issues.
My app works fine without inputting code for a button to function.
But when I do, it crashes. The app doesn't even open.
What is going on?
I tried rearranging and it still doesn't work.
The buttons are used to combine EditText
They work on a different app but when I try to combine it with this code it fails.
package com.glenn.howtowritefantasy.activities;
import com.glenn.howtowritefantasy.R;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
Button btn_Combine,btn_Clear;
EditText Tagline_p2,Start_writing_p1,
Part_three1,Part_four1,Part_five1;
TextView tv_Result;
//THIS IS WHERE THE PROBLEM STARTS
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tagline_p2= (EditText) findViewById(R.id.tagline_p2);
Start_writing_p1= (EditText) findViewById(R.id.start_writing_p1);
Part_three1= (EditText) findViewById(R.id.part_three1);
Part_four1= (EditText) findViewById(R.id.part_four1);
Part_five1= (EditText) findViewById(R.id.part_five1);
tv_Result= (TextView) findViewById(R.id.tv_result);
btn_Combine= (Button) findViewById(R.id.btn_combine);
btn_Clear= (Button) findViewById(R.id.btn_clear);
btn_Clear.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
btn_Clear.setBackgroundColor(Color.DKGRAY);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
btn_Clear.setBackgroundColor(Color.BLUE);
}
return false;
}
});
btn_Combine.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
btn_Combine.setBackgroundColor(Color.DKGRAY);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
btn_Combine.setBackgroundColor(Color.BLUE);
}
return false;
}
});
//THIS IS WHERE THE PROBLEM ENDS
// Check operating system version and set the layout file based on the outcome
if(Build.VERSION.SDK_INT == 18 || Build.VERSION.SDK_INT == 19)
{
setContentView(R.layout.activity_main_no_material);
}
else
{
setContentView(R.layout.activity_main);
}
init();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.character_development:
Intent intentCharDev = new Intent(this, CharacterDevActivity.class);
startActivity(intentCharDev);
break;
case R.id.the_world:
Intent intentWorld = new Intent(this, TheWorldActivity.class);
startActivity(intentWorld);
break;
case R.id.the_magic:
Intent intentMagic = new Intent(this, TheMagicActivity.class);
startActivity(intentMagic);
break;
case R.id.creatures_races:
Intent intentCreaturesRaces = new Intent(this, CreaturesRacesActivity.class);
startActivity(intentCreaturesRaces);
break;
case R.id.story_development:
Intent intentStoryDev = new Intent(this, StoryDevActivity.class);
startActivity(intentStoryDev);
break;
case R.id.btn_combine:
//Toast.makeText(MainActivity.this,"combine",Toast.LENGTH_SHORT).show();
String first=Tagline_p2.getText().toString();
String last=Start_writing_p1.getText().toString();
String unew= Part_three1.getText().toString();
String blast=Part_four1.getText().toString();
String end= Part_five1.getText().toString();
if (TextUtils.isEmpty(first)){
Tagline_p2.setError("please enter your first name");
return;
}
if (TextUtils.isEmpty(last)){
Start_writing_p1.setError("please enter your last name");
return;
}
if (TextUtils.isEmpty(unew)){
Part_three1.setError("please enter your something");
return;
}
if (TextUtils.isEmpty(unew)){
Part_four1.setError("please enter your something");
return;
}
if (TextUtils.isEmpty(unew)){
Part_five1.setError("please enter your something");
return;
}
String full=first+" "+last+" "+unew+" " +blast+" " +end;
tv_Result.setText(""+full);
break;
case R.id.btn_clear:
//Toast.makeText(MainActivity.this,"Clear",Toast.LENGTH_SHORT).show();
Tagline_p2.setText("");
Start_writing_p1.setText("");
Part_three1.setText("");
Part_four1.setText("");
Part_five1.setText("");
tv_Result.setText("");
break;
}
}
private void init(){
this.setSupportActionBar((Toolbar) findViewById(R.id.tb_menu));
this.getSupportActionBar().setTitle("Write Fantasy");
findViewById(R.id.character_development).setOnClickListener(this);
findViewById(R.id.the_world).setOnClickListener(this);
findViewById(R.id.the_magic).setOnClickListener(this);
findViewById(R.id.creatures_races).setOnClickListener(this);
findViewById(R.id.story_development).setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
/**
* Handles events from the options menu
*/
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.item_1:
sendRequestEmail();
return true;
case R.id.item_2:
sendEmail();
return true;
case R.id.item_3:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Sends email to timo24apps#gmail.com to request content
*/
private void sendRequestEmail(){
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:timo24apps#gmail.com"));
i.putExtra(Intent.EXTRA_SUBJECT, "How to Write Fantasy: Request Content");
i.putExtra(Intent.EXTRA_TEXT , "Please describe what content you would like to see added or feel free to give me any suggestions for improving the app! I'm also available to read a chapter or two from your story and give some feedback!" + System.getProperty("line.separator") + System.getProperty("line.separator") + "**********************" + System.getProperty("line.separator") + System.getProperty("line.separator"));
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
/**
* Sends email to timo24apps#gmail.com to report problem
*/
private void sendEmail(){
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:timo24apps#gmail.com"));
i.putExtra(Intent.EXTRA_SUBJECT, "How to Write Fantasy: Report Problem");
i.putExtra(Intent.EXTRA_TEXT , "Please describe what problem you encountered or feel free to give me any suggestions for improving the app!" + System.getProperty("line.separator") + System.getProperty("line.separator") + "**********************" + System.getProperty("line.separator") + System.getProperty("line.separator"));
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
Here are the logcat errors:
Process: com.glenn.howtowritefantasy, PID: 5705
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.glenn.howtowritefantasy/com.glenn.howtowritefantasy.activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnTouchListener(android.view.View$OnTouchListener)' on a null object reference
Check if a Button with btn_clear id exists in your activity_main.xml file. If so , check if the id declarations is like this: android:id="#+id/btn_clear" *With the +signal

Issue with sharing variables between Activities

The code is heavily borrowed from https://github.com/hastarin/android-udpsender and where his code is very versatile, I want a simple way to send a udp packet to an Arduino that will unlock a garage door.
Basically page one (MainActivity) has a big "Open" button and a small "Set Params" button. Page two (Main2Activity) is mostly the borrowed code with lots deleted and provides a way to input the IP address, port and the unlock code word. Currently there is "Send" button that sends the assembled udp packet to the client and it works as intended.
The issue is that I really don't want to have to access the second page regularly. I need the "sendData" routine in MainActivity to have access to the stored values for processing.
At this time, pressing the Send button on the MainActivity page results in:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.kke.android.opener.MainActivity.sendData(MainActivity.java:47)
at com.kke.android.opener.MainActivity.onClick(MainActivity.java:30)
Which I take to mean that the the variable values are not available to the sendData routine on that page.
MainActivity
package com.kke.android.opener;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnsend = (Button) findViewById(R.id.buttonSend);
Button btnset = (Button) findViewById(R.id.buttonSet);
btnsend.setOnClickListener(this);
btnset.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSend:
sendData(v);
break;
case R.id.buttonSet:
editParams(view);
break;
}
}
public void sendData(View view) {
Context context = getApplicationContext();
/**Load global variable from Main2Activity*/
Bundle bundle = getIntent().getExtras();
String host = bundle.getString("host");
String port = bundle.getString("port");
String dataText = bundle.getString("dataText");
//EditText editText = (EditText) findViewById(R.id.editTextIP);
//String host = editText.getText().toString();
if (!host.matches("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b")) {
CharSequence text = "Error: Invalid IP Address";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
//editText = (EditText) findViewById(R.id.editTextPort);
//String port = editText.getText().toString();
if (!port.matches("^(6553[0-5]|655[0-2]\\d|65[0-4]\\d\\d|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)$")) {
CharSequence text = "Error: Invalid Port Number";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
// editText = (EditText) findViewById(R.id.editTextData);
//String dataText = editText.getText().toString();
if (dataText.length() < 1 ) {
CharSequence text = "Error: Text required to send";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
String uriString = "udp://" + host + ":" + port + "/";
uriString += Uri.encode(dataText);
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
}
/** Called when the user taps the Set Params button */
public void editParams(View view) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
Main2Activity
package com.kke.android.opener.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.kke.android.opener.R;
public class Main2Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Restore preferences
SharedPreferences settings = getPreferences(0);
ToggleButton toggleButton = ((ToggleButton) findViewById(R.id.toggleButton));
boolean checked = settings.getBoolean("toggleChecked", false);
toggleButton.setChecked(checked);
toggleButton.setVisibility(View.GONE);
EditText editText = (EditText) findViewById(R.id.editTextIP);
if (checked) {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
}
editText.setText(settings.getString("host", ""), TextView.BufferType.EDITABLE);
editText = (EditText) findViewById(R.id.editTextPort);
if (checked) {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
}
editText.setText(settings.getString("port", ""), TextView.BufferType.EDITABLE);
editText = (EditText) findViewById(R.id.editTextData);
editText.setText(settings.getString("dataText", ""), TextView.BufferType.EDITABLE);
/** Set up global variable to pass to MainActivity */
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
intent.putExtra("host", "host");
intent.putExtra("port", "port");
intent.putExtra("dataText", "dataText");
startActivity(intent);
}
#Override
public void onPause() {
super.onPause();
// Get current values
EditText editText = (EditText) findViewById(R.id.editTextIP);
String host = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextPort);
String port = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextData);
String dataText = editText.getText().toString();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getPreferences(0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("host", host);
editor.putString("port", port);
editor.putString("dataText", dataText);
editor.putBoolean("toggleChecked", ((ToggleButton) findViewById(R.id.toggleButton)).isChecked());
// Commit the edits!
editor.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_send:
this.sendData(null);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void sendData(View view) {
Context context = getApplicationContext();
EditText editText = (EditText) findViewById(R.id.editTextIP);
String host = editText.getText().toString();
if (!host.matches("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b")) {
CharSequence text = "Error: Invalid IP Address";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
editText = (EditText) findViewById(R.id.editTextPort);
String port = editText.getText().toString();
if (!port.matches("^(6553[0-5]|655[0-2]\\d|65[0-4]\\d\\d|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)$")) {
CharSequence text = "Error: Invalid Port Number";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
editText = (EditText) findViewById(R.id.editTextData);
String dataText = editText.getText().toString();
if (dataText.length() < 1 ) {
CharSequence text = "Error: Text/Hex required to send";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
String uriString = "udp://" + host + ":" + port + "/";
uriString += Uri.encode(dataText);
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
}
public void onToggleClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();
EditText editTextIp = (EditText) findViewById(R.id.editTextIP);
EditText editTextPort = (EditText) findViewById(R.id.editTextPort);
if (on) {
editTextIp.setInputType(InputType.TYPE_CLASS_TEXT);
editTextPort.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
editTextIp.setInputType(InputType.TYPE_CLASS_PHONE);
editTextPort.setInputType(InputType.TYPE_CLASS_PHONE);
}
}
}
All suggestions will be appreciated.
Please remember I am very new to this.
Both of your Activities have the exact same layouts... That is probably confusing...
Anyways, you called getIntent().getExtras() when there was no extras to get (that activity just started).
Sample of your code
Bundle bundle = getIntent().getExtras();
String host = bundle.getString("host");
String port = bundle.getString("port");
String dataText = bundle.getString("dataText");
You can simply do this
Bundle extras = getIntent().getExtras();
// TODO: declare some variables here
String host, port, text;
if (extras != null) {
// TODO: assign your variables here
String host = extras.getString("host");
String port = extras.getString("port");
String dataText = extras.getString("dataText");
}
However, don't be surprised if you don't get anything because the intent could still be empty
What is happening is that your MainActivity is probably launched from the Android launcher and not from MainActivity2.
Basically when you click send, you inspect the intent that brought you here (to this activity). Since you came from the launcher, this intent does not have the data that you need to execute the function. Remember that you are setting the data for this intent in your MainActivity2 (on your oncreate method, which is kind of a bad practice in this context).
To fix this, go to the manifest and make your MainActivity2 your launcher activity:
<activity android:name="<YOUR_ACTIVITY_TWO_NAME">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This will make sure that your Activity2 will be called first, this linking to MainActivity and sending an intent with actual data.

Android Studio getApplicationcontext()

I am trying to have messages pop up if the user does not enter their username and password, however my problem is the getApplicationcontext(), it says "cannot resolve method". how do i fix it?-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.example.rojean.prelim_project;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
Button loginBtn;
EditText txtUsername, txtPassword;
AccountsManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Object getApplication;
session = new AccountsManagement(getApplicationcontext());
txtUsername = (EditText) findViewById(R.id.nameField);
txtPassword = (EditText) findViewById(R.id.passwordField);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
loginBtn = (Button)findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
//Validation method
if(username.trim().length() > 0 && password.trim().length() > 0){
// For testing puspose username, password is checked with static data
// username = admin
// password = admin
if(username.equals("admin") && password.equals("admin")){
// Creating user login session
// Statically storing name="Android Example"
// and email="androidexample84#gmail.com"
session.createUserLoginSession("Android Example",
"androidexample84#gmail.com");
// Starting MainActivity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}else{
// username / password doesn't match&
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
}else{
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
}
}
Try LoginActivity.this instead of getApplicationContext()
Use this instead of getApplicationContext():
Toast.makeText(this, "User Login Status: " + session.isUserLoggedIn(), Toast.LENGTH_LONG).show;
In this way you get the activity's context.
Do not use getApplicationContext(). The best way to get the Activity context is to use LoginActivity.this, where this refers to the context itself.

Zxing barcode matching app for android

I'm trying to develop an app which will scan a barcode, store the value in a variable, then scan another barcode and match that value with the previous value and return a 'match' or 'no match' result. I have already got the first part working thanks to help from foamyguy, here's the initial code that I used,
package com.barcodesample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class BarcodeSample extends Activity {
private Button scanBtn;
private TextView resultsTxt;
/** Called when the activity is first created. */;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
scanBtn = (Button) findViewById(R.id.scanBtn);
resultsTxt = (TextView) findViewById(R.id.resultsTxt);
scanBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
resultsTxt.setText("Scanning...");
Intent intent = new intent("com.google.zxing.client.android.SCAN");
try {
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
new AlertDialog.Builder(v.getContext())
.setTitle("WARNING:")
.setMessage("You don't have Barcode Scanner installed. Please install it.")
.setCancelable(false)
.setNeutralButton("Install it now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
})
.show();
}
}
});
}
/*Here is where we come back after the Barcode Scanner is done*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// contents contains whatever the code was
String contents = intent.getStringExtra("SCAN_RESULT");
// Format contains the type of code i.e. UPC, EAN, QRCode etc...
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan. In this example I just put the results into the TextView
resultsTxt.setText(format + "\n" + contents);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel. If the user presses 'back' before a code is scanned.
resultsTxt.setText("Canceled");
}
}
}
}
Now how do I start another intent with another scan button similar to the one above, and finally how to compare both values and return the match or no match in a new screen?
Thanks in advance for the valuable advice
Use the same code on the other button except following.
startActivityForResult(intent, 1); // right now it's 0 for button 1
Now add one more section in onActivityResult for returning results for 2nd button.
if (requestCode == 1) {
// your code here that will be used for comparing.
}

onItemClick, Intent, startActivity errors

My code:
package elf.app;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import elf.app.entity.ELFList;
import elf.app.entity.Entry;
import elf.app.test.FakeComm;
// TODO Kunna skicka att något är färdigt (ett rum är städat).
public class RoomListActivity extends ListActivity {
private ELFList eList;
// private FakeComm fakecomm;
private Bundle extras;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.extras = getIntent().getExtras();
eList = new ELFList();
// fakecomm = new FakeComm();
// eList.add(fakecomm.getData());
String[] strArr = {"asd","sdf","dfg"};
eList.add(strArr);
String[] str = eList.returnNames();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, str));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Entry e = eList.getEntry(position);
String roominfo = e.toString();
Intent intent = new Intent(this, RoomInfoActivity.class);
intent.putExtra("entry",roominfo);
this.startActivity(intent);
// old stuff
// String message;
// message = eList.getEntryInfo(position);
// Toast.makeText(getApplicationContext(),
// message, Toast.LENGTH_SHORT).show();
}
});
}
}
I'm getting errors at the following lines:
Intent intent = new Intent(this, RoomInfoActivity.class);
and
this.startActivity(intent);
I don't have much of a clue why I get these errors, the exact output in the editor for these errors are:
"The constructor Intent(new AdapterView.OnItemClickListener(){}, Class ) is undefined"
"The method startActivity(Intent) is undefined for the type new AdapterView.OnItemClickListener(){}"
I'm an Android newbie so please take that into consideration, however I have studied Java for about a year.
Fix
Intent intent = new Intent(this, RoomInfoActivity.class);
to
Intent intent = new Intent(RoomListActivity.this, RoomInfoActivity.class);
The error is because by this you refer to OnClickListener. The problem is fixed, if you refer to the Activity's this. The second error is the same - wrong reference. Just remove this, and startActivity() method will be searched within the enclosing class too.
try this
Intent intent = new Intent(RoomListActivity.this, RoomInfoActivity.class);
intent.putExtra("entry",roominfo);
RoomListActivity.this.startActivity(intent);

Categories

Resources