Android Studio getApplicationcontext() - java

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.

Related

Whenever I am clicking save button in this SetupActivity my app crashes. My app is crashing whenever I am going to WRITE in Firebase Database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I Am creating a Login/Register Activity in my android app. When a user is registering the Firebase Authentication is working fine. After Registering a use is directed into Setup activity. Now the setup activity is to store data into Firebase Database. Whenever the user is completing setup and clicking on the button to update in the database. The app stops working.
private Button SaveInformation;
SaveInformation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
SaveAccountSetupInformation();
}
});
When the app is crashing the logcat is showing this error
enter image description here
The App is showing this error
The Code of my Setup Activity is:
package com.example.application;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
public class SetupActivity2 extends AppCompatActivity {
private EditText FirstName, LastName, Day, Month, Year;
private EditText Country, State;
private ImageView ProfilePic;
private Button SaveInformation;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private ProgressDialog loadingBar;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup2);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
FirstName = (EditText) findViewById(R.id.setup_FirstName);
LastName = (EditText) findViewById(R.id.setup_LastName);
Day = (EditText) findViewById(R.id.setup_date);
Month = (EditText) findViewById(R.id.setup_month);
Year = (EditText) findViewById(R.id.setup_year);
Country = (EditText) findViewById(R.id.setup_country);
State = (EditText) findViewById(R.id.setup_state);
ProfilePic = (ImageView) findViewById(R.id.setup_profilePic) ;
SaveInformation = (Button) findViewById(R.id.setup_button);
loadingBar = new ProgressDialog(this);
SaveInformation.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
SaveAccountSetupInformation();
}
});
}
private void SaveAccountSetupInformation()
{
String firstName = FirstName.getText().toString().trim();
String lastName = LastName.getText().toString().trim();
String day = Day.getText().toString().trim();
String month = Month.getText().toString().trim();
String year = Year.getText().toString().trim();
String country = Country.getText().toString().trim();
String state = State.getText().toString().trim();
if(TextUtils.isEmpty(firstName))
{
Toast.makeText(this, "Please write your username...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(lastName))
{
Toast.makeText(this, "Please write your full name...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(country))
{
Toast.makeText(this, "Please write your country...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(state))
{
Toast.makeText(this, "Please write your state...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(day))
{
Toast.makeText(this, "Please write your full name...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(month))
{
Toast.makeText(this, "Please write your month...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(year))
{
Toast.makeText(this, "Please write your year...", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Saving Information");
loadingBar.setMessage("Please wait, while we are creating your new Account...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
HashMap userMap = new HashMap<>();
userMap.put("FirstName",firstName);
userMap.put("LastName",lastName);
userMap.put("day",Day);
userMap.put("month",Month);
userMap.put("year",Year);
userMap.put("country",country);
userMap.put("state",State);
userMap.put("Status","Hey There !! I am using Toodle.");
userMap.put("Gender","Default");
userMap.put("Institution","Default");
UsersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(SetupActivity2.this, "your Account is created Successfully.", Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(SetupActivity2.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void SendUserToMainActivity()
{
Intent mainIntent = new Intent(SetupActivity2.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
Error in My LOGCAT when the app crashes.
2020-09-13 11:05:00.540 20182-20182/com.example.application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.application, PID: 20182
com.google.firebase.database.DatabaseException: Found conflicting getters for name: getText
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init>(CustomClassMapper.java:477)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass(CustomClassMapper.java:329)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:166)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:141)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToPlainJavaTypes(CustomClassMapper.java:65)
at com.google.firebase.database.DatabaseReference.updateChildrenInternal(DatabaseReference.java:412)
at com.google.firebase.database.DatabaseReference.updateChildren(DatabaseReference.java:392)
at com.example.application.SetupActivity2.SaveAccountSetupInformation(SetupActivity2.java:141)
at com.example.application.SetupActivity2.access$000(SetupActivity2.java:26)
at com.example.application.SetupActivity2$1.onClick(SetupActivity2.java:72)
at android.view.View.performClick(View.java:6312)
at android.view.View$PerformClick.run(View.java:24811)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6651)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
your error as shown in logcat is
Found conflicting getters for name: getText
the Firebase Database can only store JSON types but you send to it an Edit Text
the error exactly here
userMap.put("day",Day);
userMap.put("month",Month);
userMap.put("year",Year);
userMap.put("state",State);
you send Day ,Month ,Year and State as Edit Text not String
do it like these
userMap.put("day",day);
userMap.put("month",month);
userMap.put("year",year);
userMap.put("state",state);
and it will work fine

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.

Attempted to finish an input event but the input event receiver has already been disposed error

I am not sure what I have done but for a moment my code was working smoothly and after I added a new activity the error Attempted to finish an input event but the input event receiver has already been disposed.
I need help on how to fix this.
package proj.com.desperationfinals;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
}
public void validate (View view){
String word = editText.getText().toString();
if(word.contentEquals("Sir Zalameda")) {
AlertDialog.Builder Alert = new AlertDialog.Builder(this);
Alert.setMessage("Correct!")
.create();
Alert.show();
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
}else{
AlertDialog.Builder Alert = new AlertDialog.Builder(this);
Alert.setMessage("Mali!")
.create();
Alert.show();
}
}
}
The problem is in the following section:
AlertDialog.Builder Alert = new AlertDialog.Builder(this);
Alert.setMessage("Correct!")
.create();
Alert.show();
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
You are getting the error because you are trying to show an alert right before starting a new activity. Now, the 'receiver' for the dialog is the current activity and as soon as you start new activity that is switched. To tackle this problem you can try something like this:
Alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
}
TL;DR: Can't show an alert right before starting a new activity.

How to use intent to open email application

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);

Categories

Resources