Android sent string from one activity to another not working - java

I want to ask something that maybe simple, but I still can't find the problem.
I sent a string from one activity to another activity, but its show nothing.
I already checked it several times, and I think there's nothing wrong with my code.
Here's My first java code ( FoodFilter.class)
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.filter_type))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.item_list))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.category_name))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
FoodFilterDetail.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
This is the FoodFilterDetail.class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.foods_filterdetail);
TextView txtProduct = (TextView) findViewById(R.id.filterItemList);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("TAG_NAME");
// displaying selected product name
txtProduct.setText(product);
}
Here's my xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:layout_marginLeft="7dip"
android:layout_marginRight="7dip" >
<TextView
android:id="#+id/filterItemList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="15dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:text="Sort By"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
I get the data on FoodFilter.class from json parse and it works fine. I can show all the data on ListView, but when I send the string to FoodFilterDetail.class it show nothing and there's no error or warning in my code.
Is there anyone can help me to fix this? I've been searching the problem for whole day.
Thanks Before

use i.getStringExtra(TAG_NAME); instead of i.getStringExtra("TAG_NAME");

create one variable in FoodFilter.java
public static final String TAG_NAME = "name";
use this
in FoodFilter.java
in.putExtra(TAG_NAME, name);
and in FoodFilterDetail.java
String product = i.getStringExtra(FoodFilter.TAG_NAME);
Do the same for all other variable

I am assuming that you are defining TAG_NAME like this in the first activity:
public static final String TAG_NAME = "some_random_key";
Then you are setting it as the key for Intent like this:
in.putExtra(TAG_NAME, name);
And in the second activity you are trying to access it like this:
String product = i.getStringExtra("TAG_NAME");
Which will not work since the key is not "TAG_NAME" but "some_random_key". So to access it in the second activity you need to define TAG_NAME in the second activity as well just like you did in the first activity:
public static final String TAG_NAME = "some_random_key";
And then access the string like:
String product = i.getStringExtra(TAG_NAME);

Related

checking number with regex if it is match or not

EditText view
<EditText
android:id="#+id/inputField"
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="#string/input_placeholder"
android:textColorHint="#color/colorAccent"
android:inputType="number"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimary"
android:textSize="25sp"
android:padding="10dp"
android:layout_marginTop="100dp"
android:gravity="center"/>
class for hold number
package com.example.kassammustapha.samplecode;
public class regexHolder{
String patten_one()
{
return "[2550]{1}[7]{1}[1]{1}[2-9]{1}\\d{6}";
}}
mainActivity
the problem is when user enter the number from editText from the view, i receive the number and convert it into string then i test with regular expression but it won't work i dont what is the problems.
regexHolder operatorPatterns = new regexHolder();
final Pattern tigoOne = Pattern.compile(operatorPatterns.patten_one());
Button mBtn =findViewById(R.id.loginBtn);
mBtn.setOnClickListener(
new View.OnClickListener()
{
EditText texEdit = findViewById(R.id.inputField);
TextView viewText = findViewById(R.id.operatorDisplay);
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
public void onClick(View view)
{
if (tigoMatcher.matches())
{
String message = "valid";
viewText.setText(message);
}else{
String message = "not valid";
viewText.setText(message);
}
}
}
);
First you need to fix your regex. From your attempted regex and your comments, I am guessing that you want this:
(?:255|0)71[2-9]\\d{6}
Start with either 255 or 0, followed by 71, followed by a digit that is in the range 2-9, followed by 6 other digits.
Secondly, fix your on click listener.
These two lines:
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
Will be run the instant you create the listener, at which point the text edit is empty. You need to move these lines to the onClick method:
new View.OnClickListener()
{
EditText texEdit = findViewById(R.id.inputField);
TextView viewText = findViewById(R.id.operatorDisplay);
public void onClick(View view)
{
String content = texEdit.getText().toString();
Matcher tigoMatcher = tigoOne.matcher(content);
if (tigoMatcher.matches())
{
String message = "valid";
viewText.setText(message);
}else{
String message = "not valid";
viewText.setText(message);
}
}
}

Use EditText value in another activity or in an enum Android

I want to make an app which plays sounds with different amount of times between sounds but I don't know how to do it.
The amount of times are defined by the user in EditText in a setting activity and then the songs are played in another activity so I need to link the EditText value in the other activity.
Here is my code to transform the content of my EditText into a variable but I don't know how to use it in my other interface :
EditText myEdit = (EditText) findViewById(R.id.editText1);
String myEditValue = myEdit.getText().toString();
time = Integer.parseInt(myEditValue);
It would be even better if someone can tell me how to transfer my EditText value in an enum but if you only know how to transfer between activities and not from an activity to an enum it will be ok.
Here is my enum code :
public enum phaseTimer {
WAITING("APPUYEZ", valueInEditText1),
LOADING("ATTENTE", valueInEditText2),
ON_YOUR_MARK("A VOS MARQUES", valueInEditText3),
READY("PRET", valueInEditText4),
GO("PARTEZ", valueInEditText5);
public String message;
public int time;
phaseTimer(String message, int time) {
this.message = message;
this.temps = temps;
}
public String getMessage() {
return message;
}
}
Intent i = new Intent(this, theotheractivityname.class);
i.putExtra("myEditValue",myEditValue );
startActivity(i);
from the other activity, you can get your string with
String newString;
Bundle extras = getIntent().getExtras();
newString= extras.getString("myEditValue");
This is a simple way here:
Intent intent = new Intent(getBaseContext(), YourClass.class);
intent.putExtra("EXTRA_SESSION_ID", yourVariable);
startActivity(intent);
Access that intent on next activity
String s = getIntent().getStringExtra("EXTRA_SESSION_ID");
Credit to this answer: How do I pass data.....

Getting a decimal number from EditText on Android Studio

EDIT:Solved!
I know this has been posted before, but the answers I've seen from those are not working for me.
I'm trying to get the input from one textfield (which i've specified as a decimal input) but can't think of any other way to get the value of it other than to toString it.
What I have below crashes and the error logs say
java.lang.IllegalStateException: Could not execute method of the activity
public void buttonOnClick(View v){
// do something when the button is clicked
Double inputNum;
TextView mField = (TextView) findViewById(R.id.mField);
TextView kmField = (TextView) findViewById(R.id.kmField);
if(mField.length() > 0){
inputNum = ( Double.valueOf(kmField.getText().toString()) )/ 0.62137;
mField.setText(inputNum.toString());
}
}
java.lang.IllegalStateException: Could not execute method of the
activity
Possible reason that this issue occur is kmField.getText().toString() return null. So please put some validation over here for kmField
public void buttonOnClick(View v){
// do something when the button is clicked
Double inputNum;
TextView mField = (TextView) findViewById(R.id.mField);
TextView kmField = (TextView) findViewById(R.id.kmField);
if(kmField.getText().toString().isEmpty()){
inputNum = ( Double.valueOf(kmField.getText().toString()) )/ 0.62137;
mField.setText(inputNum.toString());
}
}
xml file:
<EditText
android:id="#+id/editS0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/S0"
android:inputType="numberDecimal" />
<Button
android:id="#+id/getS0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/setS0" />
in your java file:
EditText textS0 = (EditText)findViewById(R.id.editS0);
Button btn_S0 = (Button)findViewById(R.id.getS0);
btn_S0.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
double S0 = Double.parseDouble(textS0.getText().toString());
}
});

About variables and screen touch events

I'm rather new to all this, so please bear with me.
what I want to do: interchange the position of two squares on the screen as soon as the user touches the screen.
what I've done so far: in my layout xml, I've used a frame layout end defined the two squares:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frame1"
android:layout_width="260dp"
android:layout_height="540dp"
android:layout_gravity="center_horizontal" >
<EditText
android:id="#+id/square1"
android:enabled="false"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/textlines"
android:clickable="false"
android:gravity="center"
android:inputType="none"
android:text="#string/C1"
android:textSize="25sp" />
<EditText
android:id="#+id/square2"
android:enabled="false"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/textlines"
android:clickable="false"
android:gravity="center"
android:inputType="none"
android:text="#string/C2"
android:textSize="25sp" />
Then in Java, I've done the following:
public class Activity1 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
EditText square1 = (EditText) findViewById(R.id.square1);
int cc1x = 210;
int cc1y = 410;
square1.setX(cc1x);
square1.setY(cc1y);
EditText square2 = (EditText) findViewById(R.id.square2);
int cc2x = 310;
int cc2y = 410;
square2.setX(cc2x);
square2.setY(cc2y);
int ccdumx = 410;
int ccdumy = 410;
}
In order to get the initial screen - so far so good. The two variables ccdumx and ccdumy are just there for an intermediate storage of one of the two squares when interchanging them
So now I add an event listener to detect a screen touch, followed by the changing of the coordinate variables:
#Override
public boolean onTouchEvent(MotionEvent event) {
ccdumx = cc1x;
ccdumy = cc1y;
cc1x = cc2x;
cc1y = cc2y;
cc2x = ccdumx;
cc2y = ccdumy;
square1.setX(cc1x);
square1.setY(cc1y);
square2.setX(cc2x);
square2.setY(cc2y);
}
but then the variables aren't recognized, nor are the squares' names. When I declare them all again in this bloc, it does work, but then my logic only works one time; I can't switch the squares back, since the variables of the coordinates are always reset by the declaration, followed by the switch of positions... I'm kinda stuck here I was thinking maybe switching first to another activity, but then again, I might have the same problem there... Any help is most appreciated.
PS. I hope the formatting of the code turns out ok, first timer for me. If not, please accept my apologies.
Because all these variables are local to method onCreate(). You need to define them globally to whole class, i.e. outside method onCreate().
The java code in first block of your question should be changed to this.
public class Activity1 extends ActionBarActivity {
int cc1x, cc1y, cc2x, cc2y, ccdumx, ccdumy;
EditText square1, square2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
square1 = (EditText) findViewById(R.id.square1);
cc1x = 210;
cc1y = 410;
square1.setX(cc1x);
square1.setY(cc1y);
square2 = (EditText) findViewById(R.id.square2);
cc2x = 310;
cc2y = 410;
square2.setX(cc2x);
square2.setY(cc2y);
ccdumx = 410;
ccdumy = 410;
}
//... rest of the code
You could just make your variables Global
like this
EditText square1;
EditText square2;
int cc1x;
....
protected void onCreate(Bundle savedInstanceState){
square1 = (EditText) findViewById(R.id.square1);
.....
}

Android changing XML layout Changes data fields

Here's a head scratcher...(at least for me)
I have a contact list that displays a list of contacts from my Db. When a user clicks on one of the contacts an edit activity comes up. It all works perfectly as laid out currently, but I need to have the edit activity display the last name entry before the first name. Thinking that all the fields should have a one to one relationship, I went ahead and moved the editText(XML) for the last name above the first name in the edit activity thinking that this should be referenced by the id of the EditText. After doing so, the program is now displaying the first name in the last name field and vise-versa. I have tried wiping the user data on the emulator with no difference. I already realize this is probably one of those UH-DUH! type questions, but if anyone can point out the obvious for me, it would be appreciated. All the code shown is in the now-working state:
I've removed some chunks that would have nothing to do with my issue.
Thanks to anyone having a look at this for me!
Ken
XML:
<EditText
android:id="#+id/contact_edit_first_name"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/contact_edit_first_name"
android:imeOptions="actionNext"
android:background="#color/warn" >
</EditText>
<EditText
android:id="#+id/contact_edit_last_name"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top"
android:hint="#string/contact_edit_last_name"
android:imeOptions="actionNext"
android:background="#color/warn" >
</EditText>
This is the contact activity that displays the listView rows, and calls
createContact which sends an intent to add, edit or delete rows.
public class ContactsActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate //DO THE ON CREATE STUFF -removed
fillData();
registerForContextMenu(getListView());
Button add_contact = (Button) findViewById(R.id.add_contact_button);
add_contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
createContact();
}
});
}
// Create the options menu to INSERT from the XML file
// removed - not relevant
// return true for the menu to be displayed
}
// When the insert menu item is selected, call CreateContact
//Removed
createContact();
return true;
}
return super.onOptionsItemSelected(item);
}
private void createContact() {
Intent i = new Intent(this, ContactEditActivity.class);
startActivity(i);
}
//The onListItemClick sends a URI which flags the contactEditActivity
//that this is an edit rather than a new insert.
#Override
protected void onResume() {
super.onResume();
//Starts a new or restarts an existing Loader in this manager
getLoaderManager().restartLoader(0, null, this);
}
//The fillData method binds the simpleCursorAadapter to the listView.
private void fillData() {
//The desired columns to be bound:
String[] from = new String[] { ContactsDB.COLUMN_LAST_NAME, ContactsDB.COLUMN_FIRST_NAME };
//The XML views that the data will be bound to:
int[] to = new int[] {R.id.label2, R.id.label};
// The creation of a loader using the initLoader method call.
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.contact_row, null, from,
to, 0);
setListAdapter(adapter);
}
// Sort the names by last name, then by first name
String orderBy = ContactsDB.COLUMN_LAST_NAME + " COLLATE NOCASE ASC"
+ "," + ContactsDB.COLUMN_FIRST_NAME + " COLLATE NOCASE ASC" ;
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//ETC
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data); //Call requires Min API 11
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// swap the cursor adapter
}
And Finally, this is the contact edit code that is likely the source of my grief...maybe not. Could be the save state doesn't map to the id's?
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_contact_edit);
Log.i(TAG, "INSIDE ONCREATE");
mCategory = (Spinner) findViewById(R.id.category);
mLastName = (EditText) findViewById(R.id.contact_edit_last_name);
mFirstName = (EditText) findViewById(R.id.contact_edit_first_name);
mHomePhone = (EditText) findViewById(R.id.contact_edit_home_phone);
mCellPhone = (EditText) findViewById(R.id.contact_edit_cell_phone);
//****************ECT. ETC.
//DECLARE THE BUTTONS AND SET THE DELETE ENABLED FALSE - REMOVED - NOT PERTINANT
Bundle extras = getIntent().getExtras();
// Check if the URI is from a new instance or a saved record
}
// Set the save button to check the required fields, save the contact and finish
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (TextUtils.isEmpty(mLastName.getText().toString()) ||
TextUtils.isEmpty(mFirstName.getText().toString())) {
makeToast();
} else {
setResult(RESULT_OK);
finish();
}
}
});
// Set the delete button to delete the contact and finish - REMOVED - NOT PERTINANT
private void fillData(Uri uri) {
// QUERY PARAMETER projection - A list of which columns to return.
// Passing null will return all columns, which is inefficient (but used now!)
// null, null and null are: selection, selection args, and sort order for specific items
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String category = cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_CATEGORY));
for (int i = 0; i < mCategory.getCount(); i++) {
String s = (String) mCategory.getItemAtPosition(i);
Log.i("CATEGORY", s); ////////////////////////////////////////////
if (s.equalsIgnoreCase(category)) {
mCategory.setSelection(i);
}
};
mLastName.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_LAST_NAME)));
mFirstName.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_FIRST_NAME)));
mHomePhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_PHONE_NUMBER)));
mCellPhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_CELL_NUMBER)));
mWorkPhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_WORK_NUMBER)));
mFax.setText(cursor.getString(cursor
//****************ECT. ETC.
//close the cursor
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putParcelable(whateverContentProvider.CONTENT_ITEM_TYPE, contactUri);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
private void saveState() {
String category = (String) mCategory.getSelectedItem();
String someLAST = mLastName.getText().toString().valueOf(findViewById(R.id.contact_edit_last_name));
String lastName = mLastName.getText().toString();
String firstName = mFirstName.getText().toString();
String someFIRST = mFirstName.getText().toString().valueOf(findViewById(R.id.contact_edit_first_name));
String homePhone = mHomePhone.getText().toString();
String somePhone = mHomePhone.getText().toString().valueOf(findViewById(R.id.contact_edit_home_phone));
String cellPhone = mCellPhone.getText().toString();
String workPhone = mWorkPhone.getText().toString();
//****************ECT. ETC.
//Some logging I used to show that the first name field still came up first
//after changing the order of the editTexts.
Log.i("LAST NAME", lastName);
Log.i("SOME LAST", someLAST);
Log.i("FIRST NAME", firstName);
Log.i("SOME FIRST", someFIRST);
Log.i("Home Phone", homePhone);
Log.i("SOME PHONE", somePhone);
// Save if first name and last name are entered
// The program will save only last name when a user presses back button with text in last name
if (lastName.length() == 0 || firstName.length() == 0) {
return;
}
// ContentValues class is used to store a set of values that the contentResolver can process.
ContentValues values = new ContentValues();
values.put(ContactsDB.COLUMN_CATEGORY, category);
values.put(ContactsDB.COLUMN_LAST_NAME, lastName);//ANNIE
values.put(ContactsDB.COLUMN_FIRST_NAME, firstName);
values.put(ContactsDB.COLUMN_PHONE_NUMBER, homePhone);
//****************ECT. ETC.
if (contactUri == null) {
// Create a new contact
contactUri = getContentResolver().insert(whateverContentProvider.CONTENT_URI, values);
} else {
// Update an existing contact
getContentResolver().update(contactUri, values, null, null);
}
}
//MAKE A TOAST DOWN HERE - REMOVED - NOT PERTINANT
}
Have you tried cleaning the project (regenerating de R).
Also, try restarting your IDE.
This may seem stupid but actually can solve the issue...
try cleaning your project. Weird things happen sometimes within Eclipse.

Categories