I have tried a lot of times and in different ways to pass a string from one activity (LoginActivity) to another one (SettingsActivity). Of course I did a lot of research and tried each provided solution, but nothing could help me until now
LoginActivity.class:
package com.naderk.pds;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import com.naderk.pds.contexts.ContextServerActivity;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
final String LOG = "LoginActivity";
Button btnLogin, btnRegister;
EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.bRegister);
btnLogin.setOnClickListener(this);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent seeTasksIntent= new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(seeTasksIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
HashMap postData = new HashMap();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
postData.put("txtUsername", username);
postData.put("txtPassword", password);
PostResponseAsyncTask task1 = new PostResponseAsyncTask(LoginActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(LOG, s);
if(s.contains("success")){
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Wrong username or password. Please register and try again.", Toast.LENGTH_LONG).show();
}
}
});
task1.execute("http://192.168.0.11/customer/");
visitactivity1();
}
public void visitactivity1() {
Intent i = new Intent(LoginActivity.this, SettingsActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key", etUsername.getText().toString());
i.putExtras(bundle);
startActivity(i);
finish();
}
}
SettingsActivity.class:
package com.naderk.pds;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Intent;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView textView = (TextView) findViewById(R.id.tvUserName);
Bundle bundle = getIntent().getExtras();
String stuff = bundle.getString("key");
textView.setText(stuff);
}
}
Logcat:
Exceeds 30.000 characters lol
I really hope that someone is able to help me.
Cheers!
Try this
public void visitactivity1() {
Intent i = new Intent(LoginActivity.this, SettingsActivity.class);
i.putExtra("key", etUsername.getText().toString());
startActivity(i);
finish();
}
and on the second activity
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView textView = (TextView) findViewById(R.id.tvUserName);
String stuff = getIntent().getStringExtra("key");
textView.setText(stuff);
}
}
Hope it helps (:
You can add the putExtras
if(s.contains("success")){
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("passwordText", password.getText().toString());
intent.putExtra("usernameText",username.getText().toString());
startActivity(intent);
On your second activity implement the following within your onCreate() method
Intent intent = getIntent();
String password = intent.getStringExtra("passwordText");
String username = intent.getSringExtra("usernameText");
You can read this blog for more information about intents : What are intents
In summary is a tutorial about how to implement intents. It may help you in case you want to change your structure.
Finally, I´m not sure if this is the way you wanted to pass the data : instead use it as I recommend. I hope it helps !
postData.put("txtUsername", username);
postData.put("txtPassword", password);
You can use Bundle methods to to send and receive Strings across your Activity class.
Related
When i press login button app doesnt close but puts me in desktop mode on phone than i go again on the app and try to "login" and than it crashes
package com.example.coronaapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText username = findViewById(R.id.username);
final EditText password = findViewById(R.id.password);
Button login = findViewById(R.id.login);
Button register = findViewById(R.id.register_btn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// čia bus vykdomas kodas, kai paspaudžiamas mygtukas
// Kuriamas User klases objektas
// public User(String username, String password)
User user = new User(username.getText().toString(), password.getText().toString());
Toast.makeText(LoginActivity.this, "prisijungimo vardas:" +
user.getUsername() + "\n" + "slaptazodis:" +
user.getPassword(), Toast.LENGTH_LONG).show();
Toast.makeText(LoginActivity.this,
username.getText().toString(),
Toast.LENGTH_SHORT).show();
username.setError(null);
if (Validation.isValidUsername(username.getText().toString())) {
Intent goToSearchActivity = new Intent(LoginActivity.this, SearchActivity.class);
startActivity(goToSearchActivity);
password.setError(null);
}
if (Validation.isValidUsername(password.getText().toString())) {
Intent goToSearchActivity = new Intent(LoginActivity.this, SearchActivity.class);
startActivity(goToSearchActivity);
} else {
username.setError("Error Wrong username");
username.requestFocus();
password.setError("Wrong Password");
password.requestFocus();
}
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToRegisterActivity = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(goToRegisterActivity);
}
});
}
}
im new to java, i tried many ways that i found on stackoverflow but it just doesnt work. Even if i delete half the code and try to go with only validation after click still crashes
I am trying to implement the logout method in my android application
and write the below code. Main Activity is a login activity and ChoosingProcActivity is an activity which contains logout button.
when I press logout button it moves me to Main Activity but when I open application next time it directly moves me to ChoosingProcActivity.
in addition to that when I log in successfully and then go back or press back it show Main Activity (login). how can I avoid this?
are shared preferences wrong?
Main Activity code
package com.example.lenovo.tactic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
EditText email_input,password_input;
TextView reset;
Button btnLogin;
Boolean isLogedBefore = false;
Vibrator v;
String organizer_ID;
SharedPreferences test_name;
final String loginURL = "http://tactickevent.com/phpApp/loginApp.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email_input = findViewById(R.id.etUserName);
password_input = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
test_name = getSharedPreferences("NAME", Context.MODE_PRIVATE);
test_name.getString("email", "");
test_name.getString("organizer_ID", "");
// if(isLogedBefore == true){
boolean is = test_name.getBoolean("isLoged", false);
if (is==true) {
Intent intent = new Intent(MainActivity.this, ChoosingProcActivity.class);
startActivity(intent);
// }
}
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateUserData();
}
});
}
private void validateUserData() {
//first getting the values
final String email = email_input.getText().toString();
final String password = password_input.getText().toString();
//checking if email is empty
if (TextUtils.isEmpty(email)) {
email_input.setError("أدخل البريد الالكتروني من فضلك");
email_input.requestFocus();
// Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//checking if password is empty
if (TextUtils.isEmpty(password)) {
password_input.setError("أدخل كلمة السر من فضلك");
password_input.requestFocus();
//Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//validating email
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
email_input.setError("أدخل بريد الكتروني صحيح");
email_input.requestFocus();
//Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//Login User if everything is fine
//first getting the values
//String emaill = email_input.getText().toString();
// String passwordd = password_input.getText().toString();
loginUser(email,password);
}
private void loginUser(final String email,final String password) {
RequestQueue queue = Volley.newRequestQueue(this);
//Call our volley library
StringRequest stringRequest = new StringRequest(Request.Method.POST,loginURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// Toast.makeText(getApplicationContext(),response.toString(), Toast.LENGTH_SHORT).show();
JSONObject obj = new JSONObject(response);
if (obj.getInt("value")== 1) {
organizer_ID = obj.getString("organizer_ID");
//storing the user in shared preferences
//SharedPref.getInstance(getApplicationContext()).storeID(organizer_ID);
//starting the ChoosingProcActivity
SharedPreferences.Editor editor = test_name.edit();
editor.putBoolean("isLoged",true);
editor.putString("email", email);
editor.putString("organizer_ID", organizer_ID);
//apply
editor.commit();
Toast.makeText(getApplicationContext(), "تم تسجيل الدخول بنجاح", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
//finish();
// startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
} else{
Toast.makeText(getApplicationContext(),"هناك خطأ في كلمة السر أو البريد الالكتروني ", Toast.LENGTH_SHORT).show();
//getting user name
//Toast.makeText(getApplicationContext(), obj.getString("messagee"), Toast.LENGTH_SHORT).show();
//storing the user in shared preferences
//SharedPref.getInstance(getApplicationContext()).storeUserName(organizer_ID);
//starting the profile activity
//finish();
//startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Connection Error"+error, Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
//email key mean the value that will send to php in $_POST["email"];
//password key mean the value that will send to php in $_POST["password"];
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
queue.add(stringRequest);
/*
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, email, password);
try {
JSONObject jsonObject = new JSONObject(result1);
SharedPreferences.Editor editor = test_name.edit();
editor.putBoolean("isLoged",true);
editor.putString("email", email);
editor.putString("organizer_ID", jsonObject.getString("organizer_ID"));
//apply
editor.commit();
*/
}
}
code of second activity
package com.example.lenovo.tactic;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class ChoosingProcActivity extends AppCompatActivity {
Button eventBTN, subeventBTN;
SharedPreferences test_name;
String emailToPass,organizer_ID;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing_proc);
eventBTN= (Button)findViewById(R.id.BtnEvent);
subeventBTN= (Button)findViewById(R.id.BtnSubEvent);
test_name = getSharedPreferences("NAME", Context.MODE_PRIVATE);
emailToPass= test_name.getString("email", "");
organizer_ID= test_name.getString("organizer_ID", "");
eventBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ChoosingProcActivity.this, EventProcActivity.class);
startActivity(intent);
}
});
subeventBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ChoosingProcActivity.this, SubeventProcActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId() ==R.id.logout)
{
preferences =getSharedPreferences("Name",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
finish();
}
return true;
}
}
You can finish your activity every time the test is true so that it can no longer be accessible from the stack.
boolean is = test_name.getBoolean("isLoged", false);
if (is) {
Intent intent = new Intent(MainActivity.this, ChoosingProcActivity.class);
startActivity(intent);
finish();
}
I am assuming that your MainActivity is the first one to get launched when opening the app.
In your MainActivity add this:
#Override
protected void onStart() {
super.onStart();
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
Intent intent = new Intent(this, ChoosingProcActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
What it does during startup of your app it will query if there is someone already logged in if yes it will go to the ChoosingProcActivity. I am assuming that in your SharedPrefManager implementation you have a code to know if there is a logged in user.
In your login method uncomment the finish() method
startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
//finish();
After successfull login, if you press back button you will not see the MainActivity.
In your ChoosingProcActivity it will look like this:
#Override
protected void onStart() {
super.onStart();
if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Basically, it will ask if there is currently logged in user if not, it will go back to the MainActivity.
EDIT In Logout you may use this as basis from your code,
logoutComponent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPrefManager.getInstance(getActivity()).clear();
Intent intent = new Intent(ChooseProcActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
I work simple android app for sending sms. I have 2 activities. One is main for sending 2 different messages with 2 different content but messages send to same number. On secund activity i have 3 fields: one is for input number to send messages, and other two are for message content. When I click save button app save user input and go back to main activity. And here start my problem. How can i send users input for number to send messages and messages content to main activity to send sms with saved user input? I am totally beginner with android developing so please help! Here is my MainActivity.java:
package com.example.davor.light;
import android.content.Intent; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.telephony.SmsManager; import
android.telephony.SmsMessage; import android.view.Menu; import
android.view.MenuItem; import android.view.View; import
android.widget.Button; import android.widget.ImageView; import
android.widget.TextView; import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// GUMBI INFORMACIJE
Button ukljuci = (Button) findViewById(R.id.ukljuci);
Button iskljuci = (Button) findViewById(R.id.iskljuci);
Button postavke = (Button) findViewById(R.id.postavke);
final ImageView slika = (ImageView) findViewById(R.id.slika);
// INFORMACIJA O PORUCI
final String broj = "097";
final String ukljuciPoruka = "Uključi";
final String iskljuciPoruka = "Isključi";
// KLIK NA GUMB ISKLJUČI
iskljuci.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(broj, null, iskljuciPoruka, null, null);
Toast.makeText(getApplicationContext(), "Isključeno! poslano na broj " + broj, Toast.LENGTH_LONG).show();
slika.setImageResource(R.drawable.off);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Nemoguće isključiti!",Toast.LENGTH_LONG).show();
}
}
});
postavke.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent PostavkeActivity = new Intent(MainActivity.this,
Postavke.class);
startActivity(PostavkeActivity);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} }
And here is code for my second activity from witch I want to pull users input to MainActivity:
package com.example.davor.light;
import android.app.Activity; import android.content.Intent; import
android.content.SharedPreferences; import
android.preference.PreferenceManager; import
android.support.v7.app.ActionBarActivity; import android.os.Bundle;
import android.view.Menu; 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 Postavke extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postavke);
gumbZaPovratak();
SharedPreferences loadSettings = PreferenceManager.getDefaultSharedPreferences(this);
String ucitajBroj = loadSettings.getString("spremiBroj", "");
String ucitajUkljuci = loadSettings.getString("spremiUkljuci", "");
String ucitajIskljuci = loadSettings.getString("spremiIskljuci", "");
final EditText postavkeBroj = (EditText) findViewById(R.id.postavkeBroj);
postavkeBroj.setText(ucitajBroj);
final EditText postavkeUkljuci = (EditText) findViewById(R.id.postavkeUkljuci);
postavkeUkljuci.setText(ucitajUkljuci);
final EditText postavkeIskljuci = (EditText) findViewById(R.id.postavkeIskljuci);
postavkeIskljuci.setText(ucitajIskljuci);
Button spremi = (Button) findViewById(R.id.postavkeSpremi);
spremi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
spremiPostavke("spremiBroj", postavkeBroj.getText().toString());
spremiPostavke("spremiUkljuci", postavkeUkljuci.getText().toString());
spremiPostavke("spremiIskljuci", postavkeIskljuci.getText().toString());
Toast.makeText(getApplicationContext(), "Spremljeno", Toast.LENGTH_LONG).show();
finish();
}
});
}
private void postavkeBroj() {
EditText postavkeBroj = (EditText) findViewById(R.id.postavkeBroj);
}
private void spremiPostavke (String ključ, String vrijednost) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(ključ, vrijednost);
editor.commit();
}
private void gumbZaPovratak(){
Button nazad = (Button) findViewById(R.id.nazad);
nazad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_postavke, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} }
You can use startActivityForResult()
You can refer this link:
http://hmkcode.com/android-startactivityforresult/
In Activity1
Intent myIntent = new Intent(this,Activity2.class);
myIntent.putExtra("var", variable_to_pass);
startActivity(myIntent);
In Activity2
Bundle extras = getIntent().getExtras();
if (extras != null) {
intentExtra = extras.getString("var"); // retrieving variable
}
You can add data to an intent like this :
String messageContent = (EditText) findViewById(yourMessageContentId).getText().toString();
String messageNumber = (EditText) findViewById(yourMessageNumberId).getText().toString();
intent.putExtra("com.example.davor.light.MESSAGE_CONTENT", messageContent);
intent.putExtra("com.example.davor.light.MESSAGE_NUMBER", messageNumber);
And then get it on the MainActivity :
Intent intent = getIntent();
String messageNumber = intent.getStringExtra("com.example.davor.light.MESSAGE_NUMBER");
String messageContent = intent.getStringExtra("com.example.davor.light.MESSAGE_CONTENT");
you can send information from one activity to other activity like bellow
Intent postavkeActivity = new Intent(MainActivity.this,
Postavke.class);
Bundle bundle=new Bundle();
bundle.putString(|"messageKey1", "message content1");
bundle.putString(|"messageKey2", "message content2");
postavkeActivity.putExtras(bundle);
startActivity(PostavkeActivity);
in main activity get bundle data like bellow
Bundle b=getIntent.getExtras();
String smsContent=b.getString("messageKey1");
I want to make a button appear in the MenuActivity layout but the deciding if statement is in the CapitalReceiver class. I've tried adding 'static' to various variables but it didn't work. Please help!
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class MenuActivity extends Activity {
String status;
Boolean verified = false;
String textColour = "#000000";
TextView mTvCapital;
ArrayAdapter<String> mAdapter;
Intent mServiceIntent;
CapitalReceiver mReceiver;
IntentFilter mFilter;
String country = "7ec47294ff3d8b74";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_layout);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Button IDButton = (Button) findViewById(R.id.getIt);
Button RefreshButton = (Button) findViewById(R.id.refresh);
long updateTimeMillis = System.currentTimeMillis();
String updateTime = (String) DateFormat.format("hh:mm", updateTimeMillis);
//If application has been submitted//
if(preferences.contains("first_middle_store") & !(verified)) {
status = "Status: Application pending. Last updated: " + updateTime;
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.VISIBLE);
textColour = "#000000";
}
//If application has not been submitted
else {
status = "Status: Application not yet submitted";
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.GONE);
textColour = "#000000";
}
TextView text=(TextView)findViewById(R.id.application_status);
text.setTextColor(Color.parseColor(textColour));
text.setText(status);
Button btnNextScreen = (Button) findViewById(R.id.verify);
//Listening to verify event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(), VerifyActivity.class);
startActivity(nextScreen);
}
});
Button btnNextScreen2 = (Button) findViewById(R.id.how);
//Listening to HowItWorks event
btnNextScreen2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen2 = new Intent(getApplicationContext(), HowItWorksActivity.class);
startActivity(nextScreen2);
}
});
//Listening to IDbutton event
IDButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen3 = new Intent(getApplicationContext(), IDActivity.class);
startActivity(nextScreen3);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_layout, container, false);
return rootView;
}
}
public void refresh(View view) {
// Getting reference to TextView
mTvCapital = (TextView) findViewById(R.id.tv_capital);
mTvCapital.setText("hello");
// Creating an intent service
mServiceIntent = new Intent(getApplicationContext(), CapitalService.class);
mServiceIntent.putExtra(Constants.EXTRA_ANDROID_ID, country);
// Starting the CapitalService to fetch the capital of the country
startService(mServiceIntent);
// Instantiating BroadcastReceiver
mReceiver = new CapitalReceiver();
// Creating an IntentFilter with action
mFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Registering BroadcastReceiver with this activity for the intent filter
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, mFilter);
}
// Defining a BroadcastReceiver
private static class CapitalReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String capital = intent.getStringExtra(Constants.EXTRA_APPROVAL);
if(capital == "YES") {
//status = "Status: Application Approved";//
//IDButton.setVisibility(View.VISIBLE);//
}
else if(capital == "NO"){
//status = "Status: Application Denied";//
}
}
}
}
Just glancing over your code, a possible solution (and perhaps not the best) would be to make the ID Button variable global. You would then instantiate it in the onCreate whilst still allowing it to be manipulated in other classes in this MenuActivity.
I hope this helps.
I created 2 Activities, Main and Second. And I want to send text, put in the box EditText from Main to Second activity. Id of first EditText is UserName, and of the second is Description.
The code of the Main activity is:
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.support.v4.app.NavUtils;
import android.content.Intent;
import android.widget.EditText;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
intent.putExtra("username", UserName.getText().toString());
intent.putExtra("gift", Description.getText().toString());
startActivity(intent);
}
public void ButtonOneClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent i = new Intent(this, Second.class);
startActivity(i);
break;
}
}
}
Full code of the Second Activity is:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class Second extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView txtInfo = (TextView)findViewById(R.id.TextOne);
String user = "ЖЫвотное";
String gift = "дырку от бублика";
user = getIntent().getExtras().getString("username");
gift = getIntent().getExtras().getString("gift");
txtInfo.setText(user + " , вам передали " + gift);
}
}
and errors:
main.java: Description cannot be resolved
main.java: UserName cannot be resolved
sorry for my english
Thanks for help
P.S. I'm studying java and programming for android just third day, please don't throw stones to me.
You'd then refer to your R class file, that is:
EditText desc = (EditText) findViewById(R.id.Description);
...
You have not included
EditText UserName = (EditText) findViewById(R.id.username);
EditText Description = (EditText) findViewById(R.id.description);
in your onCreate() method in MainActivity.
As you reference UserName and Description here refer to them as they are classes. Unless you have such classes an error will be stated because these classes can not be found (or "resolved").
You can even notice this by the syntax highlight. Do you see the words a displayed in a lght green/turquoise like Main or Intent?
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
intent.putExtra("username", UserName.getText().toString());
intent.putExtra("gift", Description.getText().toString());
startActivity(intent);
}
Instead you want instances of the class EditText which you call userName and description. On these objects you can perform getText() and work your way along. :)
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
EditText userName = (EditText) findViewById(R.id.username);
EditText description = (EditText) findViewById(R.id.description);
intent.putExtra("username", userName.getText().toString());
intent.putExtra("gift", description.getText().toString());
startActivity(intent);
}
Please notice I've changed the names of your variables to lowerCase starting camelCase. Though not an explicit rule it's considered good practise to start variable names with lower case letters ('userName,description,intent) while **C**lass references like (ÈditText,Main,Second`) are started with upper case letters.
you have not initialize the username & description in your java;
EditText us_name=(EditText) findViewById(R.id.user_name);
EditText us_desp=(EditText) findViewById(R.id.desp);