Why is my activity only running once? - android

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

Related

Polygon Onclick Openwindow

I want make application on Android with multiple polygon, and when i click one polygon it show something like open window and show detail of the polygon. Is there any solution to make function like that?
Yes you can use ImageButtons for polygon images and handle their click events by opening new activity or dialog for showing information about the polygons.
You will handle the click events like this:
ImageButton ib = findViewById(R.id.polygon1);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//show dialog or new activity with details
Intent i=new Intent();
int polygon_id = id_of_polygon;
i.putExtra("id", polygon_id);
i.startActivity(this,DetailsActivity.class);
finish();
}
});
You can get this value in details activity like this:
int id;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
id= 0;
} else {
id= extras.getInt("id");
}
}
Then in this activity you can show details about the polygon.
All this code will be added to the onCreate() methods of the activities.

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?

TableLayout, Different Button actions depending on data in TableRow

I have the following problem:
I have a TableLayout along with several TableRows, which are dynamically created.
On the right side of every row I create a button, which should call another activity.
Now I want to pass some information with intent.putExtra(). In this case I want so pass the row number, which is also the first information in the row.
Here is a picture of the current state:
This is how I create the buttons during run-time (in a loop):
Button b1 = new Button (this, null, android.R.attr.buttonStyleSmall);
b1.setId(1000+grButtonId);
b1.setText("Request GR");
b1.setLayoutParams(params);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Some code, taken out for clarity
// See next code snippet
}
});
grButtonId++;
tr.addView(b1);
My idea so far is to use the id of the button (of course), and get the line number by the value of grButtonId.
Now comes my problem, let's have a detailed look at my onClickmethod:
#Override
public void onClick(View view) {
// finished is true, as soon as GRRequest has recieved the data
if(!finished & !dataRequested){
new GRRequest().execute(getIntent().getLongExtra("poNr", 0),(long)view.getId());
b1.setText("Show GR");
Log.d("DataList", detailList.toString());
dataRequested=true;
}
else{
if (dataRequested){
b1.setText("Show GR");
}
Intent intent = new Intent(DataTableCreater.this, GRTableCreater.class);
intent.putExtra("lineNr",view.getId());
intent.putExtra("dataList", detailList);
startActivity(intent);
}
}
When I request my data, the button I clicked on gets set to "Show GR" , as intended. The other buttons stay on "Request GR", this is also fine. But now I want these Buttons to Change to "Show GR" when tapped first and on second tap start the activity.
By now, the buttons change to "Show GR" and directly start the activity.
What would be a solution, to make this work?
Create a boolean Array clickedOnce[] = new boolean[grButtonId+1] one field for every Button.
Then have this
public void onClick(View view) {
if(!finished){
new GRRequest().execute(getIntent().getLongExtra("poNr", 0),(long)view.getId());
b1.setText("Show GR");
Log.d("DataList", detailList.toString());
clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]=true; //sets the clickedOnce for this button to true, substring(1,4) is needed to cancle the leading 1 from the id
}
else{
//Checks, if the button was clicked once
if (!clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]){
b1.setText("Show GR");
clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]=true;
}
else{
Intent intent = new Intent(DataTableCreater.this, GRTableCreater.class);
intent.putExtra("lineNr",view.getId());
intent.putExtra("dataList", detailList);
startActivity(intent);
}
}
}

Android JUnit HorizontalListView performItemClick() not working

During my unit Tests I want to basically test if an Activity is started by a simple pressure on a button, that is in an HorizontalListView. I've already succeed in starting new Activities during previous unit test but this one is not acting as wanted. I've got an assertion failure telling me that the activity that I want to start is still null.
Actually, when I launch my unit test, it seems to not perform the click. I have to perform it myself during the test by using my little finger for the test to pass.
To see if I was clicking on the right View I used Logs to see which view my test was clicking and which I actually want to click: and it seems to be the right view (the right Id, the right Position and the right View). So i think the problem isn't where I'm clicking.
The Activity i'm testing is called StudioActivity and the Activity i want to start is called AddBoasterActivity.
My Unit test method:
public void testSwitchToAddBoaster(){
assertTrue(mBoasterPreviewFragment.getWithAddButton());
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(AddBoasterActivity.class.getName(), null, false);
mStudioActivity.runOnUiThread(new Runnable() {
#Override
public void run(){
int lPosition = mBoasterPreviewFragment.getAdapter().getCount()-1;
View lView = mBoasterPreviewFragment.getBoaster().getChildAt(lPosition);
//HERE ARE LOGS TO SEE IF MY TEST IS PERFORMING
//THE CLICK ON THE RIGHT VIEW AT THE GOOD POSITION
Log.i("TEST POSITION:", ""+lPosition);
Log.i("TEST ID: ",""+lView.getId());
Log.i("TEST VIEW: ", ""+lView);
//AND IT'S THE GOOD VIEW!
mBoasterPreviewFragment.getBoaster().performItemClick(lView,lPosition,lView.getId());
}
});
AddBoasterActivity lAddBoasterActivity = (AddBoasterActivity) getInstrumentation().waitForMonitorWithTimeout(activityMonitor,5000);
assertNotNull(lAddBoasterActivity); //HERE IS THE FAILURE, THE ACTIVITY HASN'T BEEN STARTED
mWFBoasterPreviewFragment = new WeakReference<BoasterPreviewFragment>((BoasterPreviewFragment) lAddBoasterActivity.getSupportFragmentManager().findFragmentById(R.id.fragment_preview));
mBoasterPreviewFragment = mWFBoasterPreviewFragment.get();
assertNotNull(mBoasterPreviewFragment);
lAddBoasterActivity.finish();
}
The OnItemClickListener:
mBoaster.setAdapter(mAdapter);
if (withAddBoasterButton) {
mBoaster.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == mAdapter.getCount() - 1) {
//HERE IS THE CURRENT VIEW
Log.i("POSITION:", ""+position);
Log.i("ID: ",""+id);
Log.i("VIEW: ", ""+view);
Intent intent = new Intent(getActivity().getApplicationContext(), AddBoasterActivity.class);
intent.putExtra(AddBoasterActivity.EXTRA_BOASTER_SELECTED, mSelectedUsers);
intent.putExtra(AddBoasterActivity.EXTRA_IS_STREAM, isStream);
startActivityForResult(intent, AddBoasterActivity.REQUEST_CODE_ACTIVITY);
}
}});
}
Performing manually a click is quite embarrassing for tests which have to be automated. So if someone has any idea why it is acting like this.
Thanks for the help!
Well I finally found it... just a night to sleep and it was okay. I should have think about it earlier, but Robotium already helped me a few times ago.
Check it out if you haven't test it yet: https://code.google.com/p/robotium/
So here's how it looks like with Robotium:
public void testSwitchToAddBoaster(){
Solo solo = new Solo(getInstrumentation(), getActivity());
getInstrumentation().waitForIdleSync();
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(AddBoasterActivity.class.getName(), null, false);
assertTrue(mBoasterPreviewFragment.getWithAddButton());
int lPosition = mBoasterPreviewFragment.getAdapter().getCount()-1;
View lView = mBoasterPreviewFragment.getBoaster().getChildAt(lPosition);
solo.clickOnView(lView); //SIMPLE CLICK
AddBoasterActivity lAddBoasterActivity = (AddBoasterActivity) getInstrumentation().waitForMonitorWithTimeout(activityMonitor,5000);
assertNotNull(lAddBoasterActivity); //NOW THE ACTIVITY IS STARTED
mWFBoasterPreviewFragment = new WeakReference<BoasterPreviewFragment>((BoasterPreviewFragment) lAddBoasterActivity.getSupportFragmentManager().findFragmentById(R.id.fragment_preview));
mBoasterPreviewFragment = mWFBoasterPreviewFragment.get();
assertNotNull(mBoasterPreviewFragment);
lAddBoasterActivity.finish();
}

How to pass value through Intent

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);

Categories

Resources