How to pass value through Intent - android

HI all,
this is my class A, where on button click , i m sending a int variable to class B
Intent bgIntent = new Intent(Background.this, MainScreen.class);
bgIntent.putExtra("background", bgColor);
startActivity(bgIntent);
and on class B
Intent bgIntent = getIntent();
bgGlobal = bgIntent.getIntExtra("background",-1 );
if(bgGlobal == 0)
{
DetailsTextView.setBackgroundResource(R.color.a0);
}
else
if(bgGlobal == 1)
{
DetailsTextView.setBackgroundResource(R.color.a1);
}
But the problem is i am getting a blank view.My view is not coming up with textview.
is this proper to set background
"DetailsTextView.setBackgroundResource"???

If you want to change the color of a View use http://developer.android.com/reference/android/view/View.html#setBackgroundColor(int)
for example:
DetailsTextView.setBackgroundColor(getResources().getColor(R.color.txt_green));
Anyway, it's not clear if you want to change the screen's background or the textview's background.
Also
if(bgGlobal == 0){...} else ...
is wrong. You should do something of the like
if(bgGlobal != -1)
{
[Use intent to read color]
}else{
[set default color]
}
If you see a blank view it's possibly due to a wrong XML layout.
Edit: To retrieve the extra
getIntent().getExtras().getInt("background",-1);

Related

change application background through a button

i want to set a different background color to all application activities through a click on a button, but at now i ve done it only for one activity and i can't do it for all activities. this is the rude code:
optionlayout = (RelativeLayout) findViewById(R.id.optionlayout);
backgroundbutton = (Button) findViewById(R.id.backgroundbutton);
int counter = 0;
backgroundbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter ==0) {
optionlayout.setBackgroundColor(0xFF5774B3);
counter++;
}else if (counter == 1){
optionlayout.setBackgroundColor(0xFF0CC258);
counter++;
} else if (counter==2){
optionlayout.setBackgroundColor(0xCC000000);
counter++;
}else if (counter== 3){
optionlayout.setBackgroundColor(0xFFFFFFFF);
counter = 0;
}
}
});
i want to change the
optionlayout.setBackgroundColor(0xFF0CC258);
with an action that changes the background in all activities permanently. thanks
You can use shared preferences and store your counter there, and in onCreate of activities first look in your shared preferences to determine what color to set your background.
You can't. There's no way to change a property of a whole application through an activity. You can create a custom class that extends Activity and implements OnClickListener.
Something like that:
class MyCustomActivity extends Activity implements View.OnClickListener{
#Override
public void onClick(View v) {
//your code inside onClick()
}
}
And then you can extend your activities to this one, for example:
class MainActivity extends MyCustomActivity { ... }
You could try to use the extras method.
Pass the changes on from activity to activity maybe it helps.
Its a longer process to set up your page each time but i don't see any other way. I'm still open to suggestions
// you can have multiple extras.
String bgColor = "yourColor";
Intent newIntent = new Intent(thisActivity.this, theNextActivity.class);
// Start new activity
dispatchIntent.putExtra("bgColor", bgColor);
// Send color to new activity
startActivity(newIntent);
finish();
// Get the background color in the new page
Bundle extras = getIntent().getExtras();
String bgColor = extras.getString("bgColor");
// The trick is to get the string into your background color format such as
0xFF5774B3

Android: deleting programmatically added image buttons with ID's

hows it going? I'm creating a little training app for a project, its going fine except for a formatting problem im getting. So, ive a csv file with a name and age for a client. an array is created from this, then I've got a scroll View containing a grid layout and i create Image Buttons from the client array. that's all fine. ive got an add client button at the end of this, the button and its activity work fine, but when you come back to the main screen, the buttons are all screwed up (huge, misplaced etc). So i figured i would loop through and delete all the buttons and repopulate the main screen, except, since i programmatically created them, i cant figure out how to find them to delete them. i tried setting their id's to the index of the array, but then i get a null pointer error.
Function where the buttons are created:
public void fillActivity_main(){
if(listPopulated == false) { // check to see if its aready been created
populateClientList();//fill array with client objects
listPopulated = true;
}
//setup asset manager
AssetManager am = getApplicationContext().getAssets();
//Create the "GridLayout Image Board"
GridLayout buttonBoard = (GridLayout) findViewById(R.id.buttonboard);
int idealWidth = buttonBoard.getWidth(); //get width of the board
int idealHeight = buttonBoard.getHeight() / 2;//same
//create the Listeners, this is a place holder for now but will eventually use SetCurrentClient() (or maybe just switch to Start screen, with the current client?)
View.OnClickListener imageClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("CLICK AT: " + v.getId());
Client temp = clientList[v.getId()];
Intent i = new Intent(getApplicationContext(), DisplayClient.class);
System.out.println(temp.getName());
i.putExtra("name", temp.getName());
System.out.println(i.getStringExtra("name"));
i.putExtra("age", Integer.toString(temp.getAge()));
startActivity(i);
}
};
int j = 0; //used the keep track of the id's we set for the buttons
for (int i = 0; i < clientList.length; i++) {
if (clientList[i] != null) {
//creation and ID setting
ImageButton imgbutton = (ImageButton) new ImageButton(this);
imgbutton.setId(i);
//Layout shit
imgbutton.setImageResource(R.mipmap.ic_launcher);
imgbutton.setMinimumWidth(idealWidth);
imgbutton.setMinimumHeight(idealHeight);
imgbutton.setOnClickListener(imageClickListener);
//check and set image
if(clientList[i].getClientImage().equals(" ")) {
try{
imgbutton.set(am.openFd(clientList[i].getClientImage()));}
catch(Exception ex){
ex.toString();
}
Log.d("ClientImageCheck", "No picture found for " + clientList[i].getName());
}
buttonBoard.addView(imgbutton);
j++;
}
}
//create the new Client Button at the end of all the rest.
Button newClientButton = (Button) new Button(this);
newClientButton.setText("+"); // obvious
newClientButton.setLayoutParams(new LinearLayout.LayoutParams(GridLayout.LayoutParams.WRAP_CONTENT, GridLayout.LayoutParams.WRAP_CONTENT));
newClientButton.setWidth(idealWidth);
newClientButton.setHeight(idealHeight);
View.OnClickListener newClientListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), CreateClientForm.class);
startActivityForResult(i, 199);
//System.out.println("Doing good so far, leaving the createclient form bnut still in main");
}
}; // create listener
newClientButton.setOnClickListener(newClientListener); // assign listener
buttonBoard.addView(newClientButton); //add the button the buttonBoard, after all the clients have been added
}
Function where i do the deleting:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check which request we're responding to
if (requestCode == 199) {
// Make sure request was successful
if (resultCode == RESULT_OK) {
// The user made a name and crap.
Bundle extras = data.getExtras();
String name = extras.getString("name");
int age = extras.getInt("age");
Client temp = new Client(name, age);
addClientToArray(temp);
System.out.println(name + "attempted add to array");
}
for(int i = 0; i<clientList.length; i++ ){
View v = findViewById(i);
((ViewManager) v.getParent()).removeView(v);
}
fillActivityMain();
}
if i've got the logic right, the 'i' in the loop should be the appropriate id. Granted, the teach has kind of thrown us in the deep end for this project, never taken mobile apps or anything, so all this code is the result of me googling issues as i run into them. I've read the basics for Views, intents, etc, but there must be something i'm missing.
I've tried making the gridLayout that the buttons sit on a class variable so i could call it buttonBoard.removeView(i) or something.
ive also tried `
for(int i = 0; i<clientList.length; i++ ){
ImageButton btn = (ImageButton) findViewByid(i);
((ViewManager) v.getParent()).removeView(btn);
}
Can you add the replacement images at the same time that you delete the existing images? If so, try this:
for(int i = 0; i < buttonBoard.getChildCount(); i++) {
ImageButton tempButton = (ImageButton) buttonBoard.getChildAt(i);
tempButton.setVisibility(View.INVISIBLE);
buttonBoard.addView(yourImageButtonHere, i); //adds a new ImageButton in the same cell you are removing the old button from
buttonBoard.removeView(tempButton);
}
This approach should also prevent the GridLayout from rearranging where the children are. I believe the default behavior if you delete a child view is that the GridLayout will re-order the children so there is not empty cell at the beginning of the grid. I hope that makes sense.
There is so much wrong with this approach.
Mainly you don't have to create the ImageButtons manually and add them to the GridLayout. That is what recycled views such as GridView or RecyclerView are for. In fact you should use those to avoid OutOfMemoryError from having too much images in your layout.
But also you cannot just call setId(i) in the for loop. Android holds many ids already assigned and you can never be sure whether the id is safe. (Unless you use View.generatViewId())
And since you only want to remove all views added to your GridLayout why don't you just call removeAllViews() on the buttonBoard?

How to accept an int in a another activity & use if statement

This is basically the situation im in
(view link)
Getting RadioButton cannot be resolved to a type
i have an integer storing values for the radio buttons - however, i dont know how to accept it in the other activity.
This is what i have so far (but i get an error)
Intent i = getIntent();
int value = intent.getIntExtra("inputValue", a);
if(a = 1)
{
//Enter action
}
Use value in if condition to check inputValue from previous Activity :
int value = intent.getIntExtra("inputValue", 0);
if(value == 1) {
//Enter action
}
Also Intent.getIntExtra take first argument as key and second as default value an int if key not found in intent.

Why is my activity only running once?

I made this application go from one activity to the next. and then come back, but after it comes back to my main activity the button to go to the next view again does not do anything? I thought it was from startActivityForResult but I did it a different way and its still not working...
Here is some code: if button is pushed
if (search.isPressed() && searchPressed == false) {
// show search list
switch1 = new Intent(MainActivity.this, SearchActivity.class);
// startActivityForResult(switch1, 0);
startActivity(switch1);
}
in next activity:
private OnItemClickListener listListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String text = (String) ((TextView) arg1).getText();
String[] selected = text.split(" - ");
selected[0] = selected[0].replace(' ', '_');
Log.w("COMPANY", selected[0]);
Log.w("PART", selected[1]);
// Intent data = new Intent(SearchActivity.this,
// MainActivity.class);
// data.putExtra("key", selected);
// setResult(RESULT_OK, data);
MainActivity.searchData = selected;
finish();
// startActivity(switch2);
}
};
////\ when item is pushed it goes back to main screen
My guess from what you've posted so far is that you are actually having trouble because of the if statement, not the startActivity().
Try putting a log output inside this if statement:
if (search.isPressed() && searchPressed == false) {
Log.d(TAG, "Search has been pressed");
// show search list
switch1 = new Intent(MainActivity.this, SearchActivity.class);
// startActivityForResult(switch1, 0);
startActivity(switch1);
}
If you don't see your out put in the log cat then the problem is with the if statement. If you post some more of the code from around this if I can try to help figure it out for you. But it seems like your condition is contradicting. To me it looks like you are checking to see if search is both pressed and not pressed.
Post a bit more of the MainActivity code, especially where the searchPressed boolean gets set.
One of the two conditions in your first part of the code will fail after the first time.
So either condition
search.isPressed()
or condition
searchPressed == false
is not true

Android programming help

I'm working on an app where i have textview's in one layout and a button that sends you to a second layout with Edittext's. Every edittext is for an textview. How can i replace text in a textview with the text in edittext with a button in the second layout?
you mean like this ??
in the method onCreate() :
btn.setOnClickListener(this);
txtView = (TextView)findViewById(R.id.mytxtView);
editTxt = (EditText) findViewById(R.id.myeditText);
and then , ovverride the onClick method like this :
#Override
public void onClick(View v ) {
txtView.setText(editText.getText());
}
textview textview = (textview)findViewById(R.layout.nameoftextview);
edittext edittext = (edittext)findViewById(R.layout.nameofedittext);
textview.settext(edittext.text());
First of all, you will have to pass the edittext value to the first activity through intent.
Eg:
Intent i = new Intent(this, FirstActivity.class);
i.putExtra("edittext_value", edittext.getText().toString());
startActivity(i);
Then inside your first activity, you will have to fetch this data as:
String value;
Bundle extras = this.getIntent().getExtras();
if (extras != null) {
value = extras.getString("edittext_value");
textview.setText(value);
}
Hope this may help you.
From what I understand is that you want your second activity (let's call it Activity2) to pass text back to the first one (Activity1). To do that, you have to (some code comes from :
Change the way you open Activity2 to
Intent EditIntent = new Intent(this, Activity2.class);
//Other stuff you may want to do with intent
startActivityForResult(EditIntent , 0);
Add override to you Activity1
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
if (data.hasExtra("myText")) {
//get your data with data.getExtras().getString("myText")
}
}
}
Change what button on your Activity2 does
{
Intent returnData= new Intent();
returnData.putExtra("myText", /*Text from your EditText*/);
if (getParent() == null) { //This part was taken from StackOverflow by Ilya Taranov
setResult(Activity.RESULT_OK, returnData);
} else {
getParent().setResult(Activity.RESULT_OK, returnData);
}
finish();
}
This should return text from EditText from Activity2 to Activity1. Code was not tested
create a variable for the textview to access it like
Textview txt = (Textview) finviewByid........;
implement the following code on button click listener
txt.setText(edittext.getText().toString());

Categories

Resources