How to replace a null value with a string with an EditText? - java

I have this app with an EditText and when you click a button it sends the value to the second screen/activity. There is a hint in the EditText upon opening the app, but does that count as not a null value? I currently have an if statement but it isn't working to replace the null value with "friend".
How can i change the code to display "friend" when nothing is typed into the EditText?
public class SecondActivity extends Activity {
public static final String TAG = SecondActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
Intent intent = getIntent();
String message = intent.getStringExtra("message");
if (message == null) {
message = "Friend";
}
Log.d(TAG, message);
TextView textView = (TextView) findViewById(R.id.button);
textView.append(message);
}
#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_second, 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);
}
}

Welcome to Stackoverflow!
The method getText() returns the content of a TextView as a CharSequence which may be empty but not null. You can check if it's empty by calling myTextView.getText().length == 0.
If a TextVew is empty or filled only by a hint, the char sequence is just empty. Your second activity gets an empty string but never null. Check rather for an empty string than null.

use something like this
Bundle extras = getIntent().getExtras();
if (extras!= null) {
textview.setText(extras.getString("message"));
}else{
textview.setText("Friend");
}
i guess your problem is with the append (you dont have anything to join/add at the textview), first try with a setText(),later in your code, use a append if you want

Related

How to pass String from One Activity to another Activity and use it in intent for Dialpad and Email

I have two one Adapter and another Activity . Adapter send the String Extra as per position in Firebase Data Structure into Next activity where data is displayed which is passed from Adapter.
It works pretty well. I am ablet to show the data in Textview. But When I user intent to Dial a phone or send Email , Then I'm not able to use Extras I"m receivng with but when I setText in Textview ..they show the exact Data. Please help
Here is the method in Adapter
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("gender");
g = bookslist.get(position);
holder.teacher_quali.setText(g.getBqualifications());
holder.profile_details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), gender_details.class);
intent.putExtra(NEAR_LOCATION, g.getBlocation());
intent.putExtra(AVAILAIBILITY, g.getBavailaile());
intent.putExtra(MOBILE, g.getSellermobile());
intent.putExtra(EMAIL, g.getSelleremail());
v.getContext().startActivity(intent);
}
});
where I have defined MOBILE and EMAIL as
public static final String MOBILE = "other_mobile";
public static final String EMAIL= "other_email";
in same adapter view and my activity is
public class gender_details extends AppCompatActivity {
private TextView tutor_email,tutor_mobile;
private ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details); // get the reference of Toolbar
toolbar.setTitle(getIntent().getStringExtra(KEY_NAME));
toolbar.setLogo(R.drawable.ic_person_black_24dp);
setSupportActionBar(toolbar);
String tutor_email_txt = "";
String tutor_mobile_txt = "";
tutor_email_txt = intent.getStringExtra(EMAIL);
tutor_mobile_txt = intent.getStringExtra(MOBILE);
// Setting values
TextView Email_Txt = (TextView) findViewById(R.id.tutor_email);
Email_Txt.setText(tutor_email_txt);
TextView Contact_Txt = (TextView) findViewById(R.id.tutor_contact);
Contact_Txt.setText(String tutor_mobile_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
// Activity's overrided method used to perform click events on menu items
#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
// Display menu item's title by using a Toast.
if (id == R.id.action_call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+tutor_mobile_txt));
startActivity(intent);
return true;
} else if (id == R.id.action_email) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, tutor_email_txt);
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(gender_details.this, MainActivity.class);
startActivity(intent);
}
}
As you can see in Textview , information are shown correctl but when I use to Intent Action Dail or send email...I'm not been able to do so.
Please help
Try this:
Declare the variable Globally
public class gender_details extends AppCompatActivity {
private TextView tutor_email,tutor_mobile;
private ImageView img;
String tutor_email_txt;
String tutor_mobile_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details); // get the reference of Toolbar
toolbar.setTitle(getIntent().getStringExtra(KEY_NAME));
toolbar.setLogo(R.drawable.ic_person_black_24dp);
setSupportActionBar(toolbar);
tutor_email_txt = intent.getStringExtra(EMAIL);
tutor_mobilee_txt = intent.getStringExtra(MOBILE);
// Setting values
TextView Email_Txt = (TextView) findViewById(R.id.tutor_email);
Email_Txt.setText(tutor_email_txt);
TextView Contact_Txt = (TextView) findViewById(R.id.tutor_contact);
Contact_Txt.setText(String tutor_mobile_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
// Activity's overrided method used to perform click events on menu items
#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
// Display menu item's title by using a Toast.
if (id == R.id.action_call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+tutor_mobile_txt));
startActivity(intent);
return true;
} else if (id == R.id.action_email) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, tutor_email_txt);
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(gender_details.this, MainActivity.class);
startActivity(intent);
}
}
Are You Declare Permission in Manifest If Not Then Declare it :
uses-permission android:name="android.permission.CALL_PHONE"
There are some serious naming problems in your code. First you need to make your tutor_mobile_txt variable global. Secondly inside onCreate your are initializing tutor_mobilee_txt instead of tutor_mobile_txt. Correct the spellings and then check.

Android studio: An error has occured

I'm working on programming a android application. But as soon as I would like to test my application in my simulator, I get an instant error.
This is my code.
public class MainActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button toPech = (Button)findViewById(R.id.toPech);
toPech.setOnClickListener(this);
ImageButton toInfo = (ImageButton)findViewById(R.id.toInfo);
toInfo.setOnClickListener(this);
//this button is not in the same layoutactivity as the other 2.
ImageButton backPech = (ImageButton)findViewById(R.id.backPech);
backPech.setOnClickListener(this);
}
#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 v) {
switch(v.getId()) {
case R.id.toPech:
startActivity(new Intent(getApplicationContext(), LocationActivity.class));
break;
case R.id.toInfo:
startActivity(new Intent(getApplicationContext(), InfoActivity.class));
break;
case R.id.backPech:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
break;
}
}
I would like to know what is wrong so that I can.
From your commented line:
//this button is not in the same layoutactivity as the other 2.
I think you have a NullPointerException.
While the Button "backPech" isn't in activity_main.xml, so calling findViewById(R.id.backPech); will return a null object ( backPech will be null).
And calling setOnClickListener(this); to a null object will cause the NullPointerException.

what to do if backpressed

i have a code to change the text of textview in a layout according to the value of the edittext (et) in the previous layout >> somethig like this
I cannot comment, so i will help you editing. Use SharedPreferences to store the string from the edittext in order to get persistance. Then get the string from the SharedPreferences and do the same thing that you are doing(pass it through the intent)
there is MorningDrsGeneral :
public class MorningDrsGeneral extends ActionBarActivity {
Button button ;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.morningdrs);
et = (EditText) findViewById(R.id.et);
addListenerOnButton1();
}
public void addListenerOnButton1() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, bookingKamal.class);
intent.putExtra("fn" , et.getText().toString());
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
}
and there is bookingKamal.java :
public class bookingKamal extends ActionBarActivity {
Button button;
TextView textView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookingkamal);
textView3 = (TextView) findViewById(R.id.textView3);
String A = textView3.getText().toString();
String N = " ";
if (A.equals(N)){
Intent intent = getIntent();
String texx = intent.getStringExtra("fn");
textView3.setText(texx);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
}
So i have to keep the text in the bookingKamal activity .. it means when i go back from this layout and back to it the text should be the same as previous. And in this code it back to null :/ or
You have two options here:
Save the value into the internal file system so it can still will be loaded after the app has been unloaded
Save the value in the Activity which holds the button to this activity and save the text over there in a variable and when the bookingkamal activity starts, it could be read from somewhere (hint: Intent#putExtra("KEY", "VALUE"))
I am not describing how you should do it because there is enough documentation about it out there and that is not the point of this answer. This should give you an idea how to it.
You can do that by using sharedpreferences.
The above link will help you undderstand how to use it.
To add data to SharedPreferences use
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.apply();
And to retrieve
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}
Note : that SharedPreferences will save the value such that, even of you close the application and restart it. The values will still remain. So, make sure you clear the data when you done with it. You can read more about it here at the SharedPreferences docs.

When passing the values into ListView I am getting an erroe NullPointerException but still the data is showing in the list after the error pop up

I am taking an array from another activity and passing it to the adapter to set it as the adapter for ListView. When I run the app and click on the button to see the ListView a message popped up saying "Unfortunately The app is stopped" but after that the list is showed. I don't know how this is happening cause after the message the app should be closed but it showing the list.
And when I am seeing in the Logcat it is showing NullPointerException. Please help me as I don't know what to do next.
Here is the code :
public class ForecastDisplay extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forecast_display);
Intent intent = getIntent();
String [] stringArray = intent.getStringArrayExtra("string-array");
Log.v(TAG, "The temperature of " + "is " + stringArray[2]);
lv = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<>(ForecastDisplay.this, android.R.layout.simple_list_item_1, stringArray);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.forecast_display, 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);
}
}
`
And here is the snapshot of the LogCat :
http://i.stack.imgur.com/rlU5i.png
It looks like your "item" array is not instantiated in your "onOptionsItemSelected". This would result in a NULL pointer whenever any item is highlighted or selected.
Make sure your array is instantiated, and in scope.

Null Pointer Exception when using LayoutInflator()?

I'm using the LayoutInflator to try and get the user's text to display in a TableLayout (Which is a child of a scrollView) But so far, it just keeps throwing the Null Pointer Exception. All the IDs are working fine, I tried cleaning the project to see if that would help but to no avail, can anyone help me out?
By the way, it tells me the error is in 2 places, reminderListTextView.setText(text); and in inflate("test");
Code:
public class MainActivity extends ActionBarActivity {
private TableLayout reminderTableScrollView;
// TextView and Button added
EditText reminderEditText;
Button addReminderButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reminderTableScrollView = (TableLayout) findViewById(R.id.reminderTableScrollView);
reminderEditText = (EditText) findViewById(R.id.reminderEditText);
addReminderButton = (Button) findViewById(R.id.enterButton);
addReminderButton.setOnClickListener(reminderClickListener);
}
private OnClickListener reminderClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (reminderEditText.getText().toString() == null || reminderEditText.getText().toString() == "") {
Toast.makeText(getApplicationContext(), "Enter reminder", Toast.LENGTH_SHORT).show();
} else {
inflate("Test");
reminderEditText.setText("");
}
}
};
public void inflate(String text) {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View reminder = inflator.inflate(R.layout.reminder_layout, null);
TextView reminderListTextView = (TextView) findViewById(R.id.reminderListTextView);
reminderListTextView.setText(text);
reminderTableScrollView.addView(reminder);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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.menuAdd) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It's actually in just one place that you get the exception : reminderListTextView.setText(text);, the 2 lines are the trace to tell you that you get the error at reminderListTextView.setText(text); when inflate("test"); is called.
Try reminder.findViewById(...);, you need to use the view in which you inflated the layout to be able to retrieve elements from it.
Try changing your inflate method to this:
public void inflate(String text) {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View reminder = inflator.inflate(R.layout.reminder_layout, null);
TextView reminderListTextView = (TextView)reminder.findViewById(R.id.reminderListTextView);
reminderListTextView.setText(text);
reminderTableScrollView.addView(reminder);
}
Without seeing your reminder_layout, I'm not certain, but I'm guessing the view with id reminderListTextView is in your reminder_layout.xml and not your activity_main.xml

Categories