Can't make the button refer to another activity in android - java

I want the button to show some texts when it is clicked. When we click the 'formula' button, a new blank page should open up in the phone showing the layout of the activity.. Here are my codes
MainActivity.java
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "";
// ....
public void sendMessage(View view) {
Intent intent = new Intent(MainActivity.this, FormulaActivity.class);
EditText editText = (EditText) findViewById(R.id.edit);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
// Do something in response to button
startActivity(intent);
FormulaActivity.java
public class FormulaActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
MainActivity.xml (button coding)
<Button
android:id="#+id/formula"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="Formula" />

You just need to intialize the Button and EditText inside your MainActivity.java
XML Layout File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
/>
<Button
android:id="#+id/formula"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Formula"
android:gravity="bottom"
/>
public class MainActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Button F=(Button)findViewById(R.id.formula);
EditText editText = (EditText) findViewById(R.id.edit);
F.setOnClickListener(new View.onClickListener()
{
public void onClick()
{
sendMessage();
}
}
}
public void sendMessage()
{
String message = editText.getText().toString();
Intent intent = new Intent(MainActivity.this, FormulaActivity.class);
intent.putExtra("EXTRA_MESSAGE", message);
startActivity(intent);
}
}
public class FormulaActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra("EXTRA_MESSAGE");
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}

Your public final static String EXTRA_MESSAGE = ""; is empty string. Try changing it to any valued string.
Hope this will help you.

Related

Display words in a recyclerview from a second activity

I am trying to display a word from a second activity to my main activity which is inform of a recycler view with a textview item.
I have created my adapter and I am assuming it works fine the only problem is once I launch my floating button to access my display word activities it does not display on the main activity, what am I doing wrong, I am new to Android.
My Adapter :
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.RoomViewHolder> {
private List <RoomPojo> word;
public RoomAdapter(List <RoomPojo> word1){
this.word = word1;
}
#NonNull
#Override
public RoomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutInflater = LayoutInflater.from(parent.getContext()).inflate(R.layout.word_item,parent,false);
return new RoomViewHolder(layoutInflater);
}
#Override
public void onBindViewHolder(#NonNull RoomViewHolder holder, int position) {
holder.wordTextView.setText(word.get(position).getWord());
}
#Override
public int getItemCount() {
return word.size();
}
public class RoomViewHolder extends RecyclerView.ViewHolder{
private TextView wordTextView;
public RoomViewHolder(View itemView) {
super(itemView);
wordTextView = itemView.findViewById(R.id.display_word);
}
}
}
Here is my Main activity:
public class MainActivity extends AppCompatActivity {
private RoomAdapter roomAdapter;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.rv_word);
recyclerView.setAdapter(roomAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
FloatingActionButton floatingActionButton = findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DisplayWord.class);
String word = getIntent().getStringExtra(DisplayWord.EXTRA_KEY);
startActivityForResult(intent,NEW_WORD_ACTIVITY_REQUEST_CODE);
}
});
}
}
Here is my display word which has a button and a edit text which should take just one string.
public class DisplayWord extends AppCompatActivity {
public static final String EXTRA_KEY = "key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_word);
final EditText editText = findViewById(R.id.word_edit_text);
Button button = findViewById(R.id.word_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if(TextUtils.isEmpty(editText.getText())){
setResult(RESULT_CANCELED, replyIntent);
}else {
String word = editText.getText().toString();
replyIntent.putExtra(EXTRA_KEY,word);
}
finish();
}
});
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_word"
android:layout_width="368dp"
android:layout_height="433dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginLeft="328dp"
android:layout_marginStart="328dp"
android:layout_marginTop="12dp"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rv_word" />
</android.support.constraint.ConstraintLayout>
Your code should be like this :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if(TextUtils.isEmpty(editText.getText())){
setResult(RESULT_CANCELED, replyIntent);
}else {
String word = editText.getText().toString();
replyIntent.putExtra(EXTRA_KEY,word);
setResult(RESULT_OK, replyIntent); //missing
}
finish();
}
});
Then After handle it in MainActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String requiredValue = data.getStringExtra(DisplayWord.EXTRA_KEY);
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}

Using switch button to set text visibility in another activity

Am a beginner in android development and am desperately looking for a solution for a challenge i encountered while working on a quiz app.
I have a switch in my SettingsActivity which toggle set a particular text in another activity visible and invisible.
However i have been having problems finding the right logic to reference that text from my SettingsActivity in other to toggle its visibility.
QuizActivity.java
public class QuizActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mExplanationText = (TextView) findViewById(R.id.txtExplanation); //this is the text with which i want the visibility to be controlled from SettingsActivity
}
}
SettingsActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/explanationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:fontFamily="cursive"
android:layout_marginBottom="25dp"
android:textColor="#color/settings_text"
android:text="#string/explanation"/>
<Switch
android:id="#+id/explanationSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:checked="true"
android:layout_gravity="center"/>
</LinearLayout>
SettingsActivity.java
private Switch mExplanationSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_settings);
mExplanationSwitch = (Switch) findViewById(R.id.explanationSwitch);
mExplanationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// how do i toggle visibility of mExplanation text in my QuizActivity.java from here?
}
});
}
MainActivity.java
//This is where i start Quiz Activity
private Button startQuiz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startQuiz = (Button) findViewById(R.id.start);
startQuiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startQuiz = new Intent(this, QuizActivity.class);
startActivity(beginnerIntent);
});
}
Save Setting in Shared Preferences
mExplanationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences preferences = getSharedPreferences("SETTINGS", MODE_PRIVATE);
Editor editor = preferences.edit();
if(isChecked){
editor.putBoolean("ntoificatoin",isChecked);
}
else
{
editor.putBoolean("ntoificatoin",isChecked);
}
editor.apply();
// how do i toggle visibility of mExplanation text in my QuizActivity.java from here?
}
});
In Your QuizActivity
public class QuizActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mExplanationText = (TextView) findViewById(R.id.txtExplanation); //this is the text with which i want the visibility to be controlled from SettingsActivity
SharedPreferences preferences = getSharedPreferences("SETTINGS", MODE_PRIVATE);
boolean b=preferences.getBoolean("ntoificatoin",false);//it returns stored boolean value else returns false
if(b){
//return true from Settings
//do what you want to
mExplanationText.setText(" "+b);
}
else
{
//return false from Settings
//do what you want to
mExplanationText.setText(" "+b);
}
}
}
if you are looking for how to pass extra info to the QuizActivity here how to use the extra in the intent :
Intent intent = new Intent();
intent.putExtra("stateOfTheSwitch","clicked");
startActivity(intent);
and in the QuizActivity you can retrieve the extra like this :
if(getIntent().getExtras.getString("stateOfTheSwitch").equals("clicked")
//do something
else
//do something else

Preference settings in Android studio how to connect the value in EditTextPreference to a TextView

I don't know how to find the value from the EditTextPreference. Like when i write a number in Edittextpreference I want the number shows up in my Textview "numTxt" in my fragment firstlayout xml :(.
Blockquote
The base for the settings menu is the "Settings Activity" where you get in Android studio, new>Activity>Settings Activity.so in the xml pref_general.xml is where the EditTextPreference is.
Please look at the imgur photos where the textfield is going to be edited.
Image-imgur
This is the preference xml file.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference
android:defaultValue="true"
android:key="example_switch"
android:summary="#string/pref_description_social_recommendations"
android:title="#string/pref_title_social_recommendations" />
<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
android:capitalize="words"
android:defaultValue="#string/pref_default_display_name"
android:inputType="textCapWords"
android:key="example_text"
android:id="#+id/textnrisettings"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="#string/pref_title_display_name" />
<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
dismiss it. -->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
android:defaultValue="-1"
android:entries="#array/pref_example_list_titles"
android:entryValues="#array/pref_example_list_values"
android:key="example_list"
android:negativeButtonText="#null"
android:positiveButtonText="#null"
android:title="#string/pref_title_add_friends_to_messages" />
</PreferenceScreen>
And here is the java file of the first layout xml
public class FirstFragment extends Fragment {
private View view;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
//Down below in Textview numTxt is where the value from the Edittextpreference will be shown
TextView numTxt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
numTxt = (TextView)view.findViewById(R.id.nummer);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
msgTxt.setVisibility(View.INVISIBLE);
aonTxt.setVisibility(View.INVISIBLE);
aoffTxt.setVisibility(View.INVISIBLE);
rela1txt.setVisibility(View.INVISIBLE);
rela2txt.setVisibility(View.INVISIBLE);
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgrela2);
}
}
);
return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
I do not see any text field in your code, if you want to copy the value to the other activity (screen) you have to save the number using
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("numTxt", numTxt.getText());
editor.commit();
and retrieve the number in other activity using
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs.getString("numTxt", null);
TextView textView = (TextView) findViewById(R.id.textViewName); //your textField?
textView.setText(restoredText);
//or with EditText
//EditText editText = (EditText) findViewById(R.id.editTextName);
//editText.setText(restoredText);

Get Id from Linear Layout Dynamically on click Android

I have 4 LinearLayout in my activity i want to get the id of clicked layout how can i get it ??![enter image description here][1]
Url of view image: http://postimg.org/image/uq4hnmlkn/
LinearLayout lt = new LinearLayout(null) ;
lt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), String.valueOf(v.getId()),
Toast.LENGTH_LONG).show();
}
});
Try this way:
1. Xml File (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lnrMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"/>
2. Java File (MainActivity.java)
public class MainActivity extends Activity {
private LinearLayout lnrMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrMain = (LinearLayout) findViewById(R.id.lnrMain);
for (int i=1;i<5;i++){
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.setId(i);
TextView textView = new TextView(this);
textView.setText("Linear Layout "+i);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
layout.addView(textView);
layout.setTag(i);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Linear Layout "+view.getTag()+" Is Clicked...",Toast.LENGTH_SHORT).show();
}
});
lnrMain.addView(layout);
}
}
}

get EditText value from onclick function

How do I get the value of my EditText that the user typed in from the function that was called when the onClick was pressed. I tried this below but its not working. Thanks for the help.
<EditText android:id="#+id/myEditT" />
<Button android:text="MY BUTTON" android:onClick="GetThis" />
public void GetThis(View view) {
EditText x = (EditText)parentView.findViewById( R.id.myEditT);
// alert the x variable
}
EditText x = (EditText) findViewById(R.id.myEditT);
String your_text = x.getText().toString();
In XML,
<EditText android:id="#+id/myEditT"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<Button android:id="#+id/myButton"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
In Java,
public void onCreate(Bundle saved){
super.onCreate(saved);
setContentView(R.layout.your_xml);
Button btn = (Button) findViewById(R.id.myButton);
EditText edtText = (EditText) findViewById(R.id.myEdit);
btn.setOnClickListener(new onClickListener(
public void onClick(View v){
String value = edtText.getText().toString();
}
));
}
public void GetThis(View view) {
EditText x = (EditText)view.findViewById(R.id.myEditT);
String edittextvalue = x.getText().toString();
}
EditText x = (EditText)findViewById(R.id.myEditT);
public void GetThis(View view) {
String getEditTextValue = x.getText().toString();
Toast.makeText(getApplicationContext(), getEditTextValue, Toast.LENGTH_LONG).show();
}
EditText x;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xml);
x = (EditText)parentView.findViewById( R.id.myEditT);
public void GetThis(View view) {
String s=x.getText().toString();
}

Categories