Android passing data between activities [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello this is my first question so please forgive me if its in bad format, I have my main activity with three buttons,Button 1 and 2 lead to numberpickers that allow user to pick from numbers to set a background image. My problem is once they pick the color (rgb) i need it sent back to the main activity but then i want the button to immediately change to the background color they chose then they can go to button two and do the same thing, at the end of the process both button1 and 2 should be the colors they have chosen. Which i will then mix in button 3(which i havent at all started on) My main problem is i pick one then it set but then i pick the other one and it onCreates() and sets the other back to a default , So i somehow need to change the colors immedietly after the activity returns to the main activity my code is a bit ugly but ive just been trying to get it working then i was gonna go back and make it more efficient so my apologize
//MAIN CONTENT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="50dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.MainActivity"
tools:showIn="#layout/activity_main">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/mixButton"
android:id="#+id/screen1MixerButton"
android:layout_below="#+id/screen1Button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="103dp" />
<Button
android:text="#string/Color1Text"
android:layout_width="162dp"
android:layout_height="188dp"
android:id="#+id/screen1Button1"
android:src="#ffffff"
android:background="#ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
<Button
android:text="#string/Color2Text"
android:layout_width="162dp"
android:layout_height="188dp"
android:id="#+id/screen1Button2"
android:background="#ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/screen1Button1" />
</RelativeLayout>
//COLORRPICKER1 ACTIVITY
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.ColorPicker1"
tools:showIn="#layout/activity_color_picker1">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/numberPicker1"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/numberPicker2"
android:orientation="horizontal"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/numberPicker2"
android:layout_alignParentEnd="true"
android:orientation="horizontal"
android:id="#+id/numberPicker3"></NumberPicker>
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="71dp"
android:id="#+id/surfaceView1"
android:layout_gravity="center_vertical"
android:background="#000000"
android:layout_below="#+id/numberPicker1"
android:layout_alignParentStart="true"
android:layout_marginTop="99dp"></SurfaceView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Color"
android:id="#+id/PickColor1"
android:layout_below="#+id/surfaceView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp" />
//COLORPICKER2 activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.bignerdranch.android.colormixer.ColorPicker2"
tools:showIn="#layout/activity_color_picker2">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/numberPicker1"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/numberPicker2"
android:orientation="horizontal"></NumberPicker>
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/numberPicker2"
android:layout_alignParentEnd="true"
android:orientation="horizontal"
android:id="#+id/numberPicker3"></NumberPicker>
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="71dp"
android:id="#+id/surfaceView2"
android:layout_gravity="center_vertical"
android:background="#000000"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"></SurfaceView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Color"
android:id="#+id/PickColor2"
android:layout_below="#+id/surfaceView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp" />
</RelativeLayout>
//MAIN ACTIVITY
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;'
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MYTAG";
public static Button colorButton1;
private Button colorButton2;
private Button mixerButton;
int red1, green1, blue1,red2, green2, blue2 =255;
public static final int REQUEST_CODE= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "in onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//START SETTING UP BUTTONS
colorButton1 = (Button) findViewById(R.id.screen1Button1);
colorButton2 = (Button) findViewById(R.id.screen1Button2);
mixerButton = (Button) findViewById(R.id.screen1MixerButton);
//ONCLICKLISTENER FOR MULTIPLE BUTTONS
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.screen1Button1:
Log.i(TAG, "screen1Button1 TAPPED");
Toast.makeText(MainActivity.this, "screen1Button1 TAPPED", Toast.LENGTH_LONG).show();
Intent i1 = new Intent(MainActivity.this,ColorPicker1.class);
startActivityForResult(i1,REQUEST_CODE);
break;
case R.id.screen1Button2:
Log.i(TAG, "screen1Button2 TAPPED");
Toast.makeText(MainActivity.this, "screen1Button2 TAPPED", Toast.LENGTH_LONG).show();
Intent i2 = new Intent(MainActivity.this,ColorPicker2.class);
startActivity(i2);
Log.i(TAG, "BACKFROM1");
break;
case R.id.screen1MixerButton:
Log.i(TAG, "screen1MixerButton TAPPED");
Toast.makeText(MainActivity.this, "screen1MixerButton TAPPED", Toast.LENGTH_LONG).show();
Intent i3 = new Intent(MainActivity.this,MixedColorScreen.class);
startActivity(i3);
Log.i(TAG, "test value recieved" + red1);
Log.i(TAG, "test value recieved" + green1);
Log.i(TAG, "test value recieved" + blue1);
Log.i(TAG, "test value recieved" + red2);
Log.i(TAG, "test value recieved" + green2);
Log.i(TAG, "test value recieved" + blue2);
red1 = getIntent().getIntExtra("ColorPicker1_red",0);
green1 = getIntent().getIntExtra("ColorPicker1_green",0);
blue1 = getIntent().getIntExtra("ColorPicker1_blue",0);
red2 = getIntent().getIntExtra("ColorPicker2_red",0);
green2 = getIntent().getIntExtra("ColorPicker2_green",0);
blue2 = getIntent().getIntExtra("ColorPicker2_blue",0);
colorButton1.setBackgroundColor(Color.rgb(red1, green1, blue1));
colorButton2.setBackgroundColor(Color.rgb(red2, green2, blue2));
break;
}
}
};
colorButton1.setOnClickListener(onClickListener);
colorButton2.setOnClickListener(onClickListener);
mixerButton.setOnClickListener(onClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "in onCreateOptionsMenu");
// 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) {
Log.i(TAG, "in onOptionsItemsSelected");
// 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);
}
}
//colorpicker1 activity
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;
public class ColorPicker1 extends AppCompatActivity {
private static final String TAG = "MYTAG";
NumberPicker np, np2, np3;
SurfaceView img;
int red, green, blue ;
private Button pickColorButton1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pickColorButton1 = (Button) findViewById(R.id.PickColor1);
pickColorButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {;
Intent colorPick1 = new Intent(ColorPicker1.this,MainActivity.class);
colorPick1.putExtra("ColorPicker1_red",red);
colorPick1.putExtra("ColorPicker1_green", green);
colorPick1.putExtra("ColorPicker1_blue", blue);
//TRY
//MainActivity.colorButton1 = (Button) findViewById(R.id.screen1Button1);
//colorPick1.setBackgroundColor(Color.rgb(red, green, blue));
//END TRY
Log.i(TAG, "PUTING IN PUTEXTRAS VALUES RED BLUE GREEN =" + red +green + blue);
startActivity(colorPick1);
}
});
//STARTING LOGS ----------------------------------------------------------------------------
Log.i(TAG,"IN COLORPICKER1");
Toast.makeText(ColorPicker1.this, "IN COLORPICKER1", Toast.LENGTH_LONG).show();
//SETUP NUMBERPICKERS-----------------------------------------------------------------------
np = (NumberPicker) findViewById(R.id.numberPicker1);
np.setMinValue(0);
np.setMaxValue(255);
np.setWrapSelectorWheel(true);
np2 = (NumberPicker) findViewById(R.id.numberPicker2);
np2.setMinValue(0);
np2.setMaxValue(255);
np2.setWrapSelectorWheel(true);
np3 = (NumberPicker) findViewById(R.id.numberPicker3);
np3.setMinValue(0);
np3.setMaxValue(255);
np3.setWrapSelectorWheel(true);
//VALUE CHANGED LISTENERS-------------------------------------------------------------------
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
red = np.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
green = np2.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np3.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
blue = newVal;
img = (SurfaceView) findViewById(R.id.surfaceView1);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
//CLOSE-------------------------------------------------------------------------------------
}
}
//colorpicker2 activity
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;
public class ColorPicker2 extends AppCompatActivity {
private static final String TAG = "MYTAG";
NumberPicker np, np2, np3;
SurfaceView img;
int red, green, blue ;//might not need
private Button pickColorButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pickColorButton2 = (Button) findViewById(R.id.PickColor2);
pickColorButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ColorPicker2.this, "COlorPick2", Toast.LENGTH_LONG).show();
Intent colorPick2 = new Intent(ColorPicker2.this,MainActivity.class);
colorPick2.putExtra("ColorPicker2_red",red);
colorPick2.putExtra("ColorPicker2_green", green);
colorPick2.putExtra("ColorPicker2_blue", blue);
Log.i(TAG, "PUTING IN PUTEXTRAS VALUES RED BLUE GREEN =" + red + green + blue);
startActivity(colorPick2);
}
});
//STARTING log -----------------------------------------------------------------------------
Log.i(TAG, "IN COLORPICKER2");
Toast.makeText(ColorPicker2.this, "IN COLOPICKER2", Toast.LENGTH_LONG).show();
//SETTING UP NUMBER PICKERS ----------------------------------------------------------------
np = (NumberPicker) findViewById(R.id.numberPicker1);
np.setMinValue(0);
np.setMaxValue(255);
np.setWrapSelectorWheel(true);
np2 = (NumberPicker) findViewById(R.id.numberPicker2);
np2.setMinValue(0);
np2.setMaxValue(255);
np2.setWrapSelectorWheel(true);
np3 = (NumberPicker) findViewById(R.id.numberPicker3);
np3.setMinValue(0);
np3.setMaxValue(255);
np3.setWrapSelectorWheel(true);
//SETTING UP LISTENERS ---------------------------------------------------------------------
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
red = np.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
green = np2.getValue();
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
np3.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
blue = newVal;
img = (SurfaceView) findViewById(R.id.surfaceView2);
img.setBackgroundColor(Color.rgb(red, green, blue));
}
});
//end --------------------------------------------------------------------------------------
}
}

For this you have to call startActivityForResult every time when you open ColorPicker1/2/3
Like this
Intent i1 = new Intent(MainActivity.this,ColorPicker1.class);
startActivityForResult(i1,REQUEST_CODE_COlLOR1);
//REQUEST_CODE must be greater than`0` so keep it `101` for example
and for ColorPicker2 keep REQUEST_CODE_COlLOR2 as 102 and for ColorPicker3 REQUEST_CODE_COlLOR2 as 103
and in your ColorActivity1/2/3 Call intent like this with respective request codes
Intent i = new Intent();
i.putExtra("color1", yourColor);
setResult(REQUEST_CODE_COlLOR1, i);
finish();
for in Second color activity
Intent i = new Intent();
i.putExtra("color2", yourColor);
setResult(REQUEST_CODE_COlLOR2, i);
finish();
In your mixed
Intent i = new Intent();
i.putExtra("color3", yourColor);
setResult(REQUEST_CODE_COlLOR3, i);
finish();
and then write OnActivityResult Override method in MainActivity to get the result from ColorPicker1/2/3
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_CODE_COlLOR1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your first button
yourColor = data.getExtras().get("color1");
}
}
if (requestCode == REQUEST_CODE_COlLOR2) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your second button
yourColor2 = data.getExtras().get("color2");
}
}
if (requestCode == REQUEST_CODE_COlLOR3) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
//Set your color on your mixed color button
yourColor3 = data.getExtras().get("color3");
}
}
}

Related

Why item on menu drawer can't click ? Android Navigation

I have a really interesting problem with my Navigator menu. I have no idea why... But I can click on any item from my menu, I don't want to say I click and nothing happened. I really want to say I can't click on any item, all my menu it's like a big image. I've try to make a new project witch already have Navigation Drawer Activity, of course it works.. but when I've try to copy that code and put on mine.. I have the same problem and vice versa, I've try to put my code into a new project with Navigation Drawer Activity, but again... I can't click on any item.
image - this trouble
image - can't click
this my code :
menu_bar.java
package com.database.m.lyburan;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.database.m.lyburan.adapter.EventAdapter;
import com.database.m.lyburan.app.AppController;
import com.database.m.lyburan.data.EventData;
import com.database.m.lyburan.util.Server;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static com.database.m.lyburan.Buddies.TAG_MESSAGE;
import static com.database.m.lyburan.Login.TAG_USERNAME;
import static com.database.m.lyburan.R.id.parent;
public class menu_bar extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
Toolbar toolbar;
DrawerLayout drawer;
NavigationView navigationView;
FragmentManager fragmentManager;
Fragment fragment = null;
ListView list;
SharedPreferences sharedpreferences;
SwipeRefreshLayout swipe;
List<EventData> eventList = new ArrayList<EventData>();
private static final String TAG = menu_bar.class.getSimpleName();
private static String url_list = Server.URL + "event.php?offset=";
private int offSet = 0;
int no;
EventAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
private Boolean isFabOpen = false;
private FloatingActionButton fab, fab1, fab2;
private CardView card1, card2;
private Animation fab_open, fab_close, rotate_forward, rotate_backward, card_open, card_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bar);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
fragment = new Root();
callFragment(fragment);
}
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
list = (ListView) findViewById(R.id.list_event);
eventList.clear();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(menu_bar.this, Buddies.class);
intent.putExtra(TAG_ID, eventList.get(position).getId());
startActivity(intent);
}
});
adapter = new EventAdapter(menu_bar.this, eventList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
});
list.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callEvent(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
Button meet_buddies = (Button) findViewById(R.id.meet_buddies);
meet_buddies.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,Buddies.class);
startActivity(intent);
}
});
Button upcoming = (Button) findViewById(R.id.upcoming);
upcoming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,asd.class);
startActivity(intent);
}
});
fab = (FloatingActionButton) findViewById(R.id.fab);
fab1 = (FloatingActionButton) findViewById(R.id.fab1);
fab2 = (FloatingActionButton) findViewById(R.id.fab2);
card1 = (CardView) findViewById(R.id.card1);
card2 = (CardView) findViewById(R.id.card2);
/*kenalkan animasi*/
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_backward);
card_open=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_open);
card_close=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_close);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
animateFAB();
}
});
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(menu_bar.this,Addhome.class);
startActivity(intent);
}
});
fab2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menu_bar.this, "New Call", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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_bar, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_payment) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_help) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.btn_logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "Action Settings", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_containers, fragment)
.commit();
}
public void animateFAB() {
/*jika fab dalam keadaan false*/
if (isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
card1.startAnimation(card_close);
card2.startAnimation(card_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
} else {
/*jika dalam keadaan true*/
fab.startAnimation(rotate_forward);
fab1.startAnimation(fab_open);
fab2.startAnimation(fab_open);
card1.startAnimation(card_open);
card2.startAnimation(card_open);
fab1.setClickable(true);
fab2.setClickable(true);
isFabOpen = true;
}
}
#Override
public void onRefresh() {
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
private void callEvent(int page){
swipe.setRefreshing(true);
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
EventData news = new EventData();
no = obj.getInt(TAG_NO);
news.setId(obj.getString(TAG_ID));
news.setJudul(obj.getString(TAG_JUDUL));
if (!Objects.equals(obj.getString(TAG_GAMBAR), "")) {
news.setGambar(obj.getString(TAG_GAMBAR));
}
news.setDatetime(obj.getString(TAG_TGL));
news.setIsi(obj.getString(TAG_ISI));
// adding news to news array
eventList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}
activity_menu_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layouts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_menu_bar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<Button
android:id="#+id/meet_buddies"
android:layout_width="fill_parent"
android:drawableLeft="#drawable/ic_profil_w"
android:background="#color/ijo"
android:textColor="#android:color/background_light"
android:layout_height="wrap_content"
android:padding="15dp"
android:onClick="meet"
android:layout_marginTop="70dp"
android:text="Meet Buddies"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/upcoming"
android:layout_width="170dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Notification"
android:layout_marginTop="135dp" />
<Button
android:id="#+id/myshared"
android:layout_width="190dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="135dp"
android:text="My Shared"
/>
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<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_margin="#dimen/fab_margin"
android:stateListAnimator="#null"
android:src="#drawable/ic_plus_w"
app:backgroundTint="#color/colorAccent"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="130dp"
android:stateListAnimator="#null"
android:layout_marginRight="#dimen/fab_margin"
android:visibility="invisible"
android:src="#drawable/ic_menu_camera"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="140dp"
android:layout_marginRight="75dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Event" />
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="80dp"
android:layout_marginRight="#dimen/fab_margin"
android:src="#drawable/ic_beranda"
android:visibility="invisible"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="90dp"
android:layout_marginRight="70dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Homestay" />
</android.support.v7.widget.CardView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="198dp" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_marginTop="222dp"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list_event"
android:layout_width="wrap_content"
android:layout_height="330dp"
android:divider="#null"
android:dividerHeight="2dp"
android:layout_marginTop="222dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
i've tried, how can i fix it ? anyone please help me. thanks.
Anyone else having similar problem. It appears the order in the XML matters too.
I had my NavigationView and after it I had a layout included and I couldn't click an item on the NavigationView.
After I switched them, so that my layout was being included AND THEN AFTER IT I had my NavigationView, it worked ...
this adapter.java
public class Adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataModel> item;
public Adapter(Activity activity, List<DataModel> item) {
this.activity = activity;
this.item = item;
}
#Override
public int getCount() {
return item.size();
}
#Override
public Object getItem(int location) {
return item.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_buddies, null);
TextView txt_nama = (TextView) convertView.findViewById(R.id.custom_list_item_text1);
txt_nama.setText(item.get(position).getNama());
return convertView;
}
}
You need to create this type of your layout xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<FrameLayout
android:id="#+id/container"
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
</android.support.v4.widget.DrawerLayout>
In FrameLayout you need to replace all fragment one by one like
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
Note: You can write your Coordinator layout and other in fragment itself, may be helpful for you.

Can someone who uses android studio tell me what to do?

My app shuts down when clicking a button, anyone knows why? And if you fins any errors please tell me ;)This activity is about two buttons that when pressed show a TimePickerDialog and save the time.
Here's my code:
package app.alexdickson.com.workout1;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
ImageButton botoFlexio;
ImageButton botoAbdominals;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
int hourDefinitivaFlexio;
int minuteDefinitvaFlexio;
int hourDefinitivaAbs;
int minuteDefinitivaAbs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
botoFlexio = (ImageButton) findViewById(R.id.botoFlexio);
botoAbdominals = (ImageButton) findViewById(R.id.botoAbdominals);
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.botoFlexio:
botoFlexio.setBackgroundResource(R.drawable.flexioclicat);
showDialog(DIALOG_ID);
hourDefinitivaFlexio = hour_x;
minuteDefinitvaFlexio = minute_x;
break;
case R.id.botoAbdominals:
botoFlexio.setBackgroundResource(R.drawable.abdominalsclicat);
showDialog(DIALOG_ID);
hourDefinitivaAbs = hour_x;
minuteDefinitivaAbs = minute_x;
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID)
return new TimePickerDialog(Main2Activity.this, kTimePickerListener, hour_x, minute_x, true);
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x = hourOfDay;
minute_x = minute;
Toast.makeText(Main2Activity.this, hour_x + ": " + minute_x, Toast.LENGTH_LONG).show();
}
};
And here's my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoAbdominals"
android:background="#drawable/abdominals"
android:contentDescription="ImatgeAbdominals"
android:layout_marginTop="50dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoFlexio"
android:layout_gravity="top"
android:layout_marginTop="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/flexio"
android:contentDescription="ImatgeFlexio"
/>
Thanks for your help !!!!
Register listener with your Button after initialize it.
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
You need to set listeners to the ImageButtons.
For example:
#Override
protected void onCreate(Bundle savedInstanceState) {
....
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
}

Android app crashes after launching intent and using setText() in TextView

I'm trying to launch an activity using intents and setting values in TextViews in the launched activity, but when I try to do that my app crashes. Heres the activity I'm trying to launch. It crashes when i try to set the text in the last two code lines
public class GameOver extends Activity {
TextView correctTxt;
TextView incorrectTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int correct = intent.getIntExtra("correct", 0);
int incorrect = intent.getIntExtra("incorrect", 0);
correctTxt = (TextView)findViewById(R.id.correct_txt);
incorrectTxt = (TextView)findViewById(R.id.incorrect_txt);
correctTxt.setText("" + correct);
incorrectTxt.setText("" + incorrect);
}
}
And the activity that's launching. I make use of the intent in the trueButton onClickListener method:
package com.example.beithia.geotest;
import android.app.Activity;
import java.util.*;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
public class TestActivity extends Activity {
private Button trueButton;
private Button falseButton;
private TextView questionTextView;
private TextView correctNum;
private TextView incorrectNum;
private TextView avgScore;
int numOfCorrect = 0;
int numOfIncorrect = 0;
double num = 1;
private TrueFalse[] questionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia,true),
new TrueFalse(R.string.question_channel_islands,true),
new TrueFalse(R.string.question_china,false),
new TrueFalse(R.string.question_mexico,true),
new TrueFalse(R.string.question_turkey,false),
new TrueFalse(R.string.question_everest,false),
new TrueFalse(R.string.question_colombia,false),
new TrueFalse(R.string.question_vatican,true),
new TrueFalse(R.string.question_nile,true),
};
private int currentIndex = 0;
private void updateQuestion() {
int question = questionBank[currentIndex].getQuestion();
questionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = questionBank[currentIndex].isTrueQuestion();
int msgId = 0;
if (userPressedTrue == answerIsTrue) {
msgId = R.string.correct_toast;
numOfCorrect++;
}
else {
msgId = R.string.incorrect_toast;
numOfIncorrect++;
}
Toast.makeText(this,msgId,Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTextView = (TextView)findViewById(R.id.question_text_view);
correctNum = (TextView)findViewById(R.id.correct_num);
incorrectNum = (TextView)findViewById(R.id.incorrect_num);
avgScore = (TextView)findViewById(R.id.average_score);
trueButton = (Button) findViewById(R.id.true_button);
trueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
double score = (numOfCorrect / num) * 100;
currentIndex = (currentIndex + 1) % questionBank.length;
correctNum.setText("Correct: " + numOfCorrect);
incorrectNum.setText("Incorrect: " + numOfIncorrect);
avgScore.setText("Score: " + String.format("%.2f", score) + "%");
updateQuestion();
num++;
if(num > 10) {
Intent intent = new Intent(TestActivity.this, GameOver.class);
intent.putExtra("correct", numOfCorrect);
intent.putExtra("incorrect", numOfIncorrect);
startActivity(intent);
}
}
});
falseButton = (Button) findViewById(R.id.false_button);
falseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
double score = (numOfCorrect / num) * 100;
currentIndex = (currentIndex + 1) % questionBank.length;
correctNum.setText("Correct: " + numOfCorrect);
incorrectNum.setText("Incorrect: " + numOfIncorrect);
avgScore.setText("Score: " + String.format("%.2f", score) + "%");
updateQuestion();
num++;
}
});
updateQuestion();
}
}
Here's the layout for activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/correct_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff00ff12" />
<TextView
android:id="#+id/incorrect_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffff5440" />
<TextView
android:id="#+id/average_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffff8c1a" />
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/true_button"/>
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/false_button"/>
</LinearLayout>
</LinearLayout>
And the layout for the activity_game_over.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/correct_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/incorrect_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
I can get it to work if I use the setContentView(R.layout.activity_game_over);
however when I try to launch the main activity again it starts the GameOver Activity, but it should start the GeoQuiz activity instead.
In the GameOver activity you don't set any content view setContentView(), hence you textViews cannot be found, findViewById returns null, hence you get NullPointerException when invoking setText().
I can get it to work if I use the setContentView(R.layout.activity_game_over); however when I try to launch the main activity again it starts the GameOver Activity, but it should start the GeoQuiz activity instead. Please help!
The activity that runs at start up is defined in the android manifest xml file of your project.
look for
action android:name="android.intent.action.MAIN"

Android getting value from selected radiobutton

I have a piece of code with three RadioButtons within a RadioGroup. I want to set an onCheckedListener that will show the value of the RadioButton in a Toast. However what I have gotten so far is not working. How do I get the value of the RadioButton and display it in a Toast? This is my code:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
RadioGroup rg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
final String value =
((RadioButton)findViewById(rg.getCheckedRadioButtonId()))
.getText().toString();
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast.makeText(getBaseContext(), value, Toast.LENGTH_SHORT).show();
}
});
}
}
XML file:
<RelativeLayout
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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="152dp" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 1" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 2" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 3" />
</RadioGroup>
</RelativeLayout>
Tested and working. Check this
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity {
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button btnDisplay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
radioGroup = (RadioGroup) findViewById(R.id.radio);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
xml
<RadioGroup
android:id="#+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_male"
android:checked="true" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_female" />
</RadioGroup>
In case, if you want to do some job on the selection of one of the radio buttons (without having any additional OK button or something), your code is fine, updated little.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio0:
// do operations specific to this selection
break;
case R.id.radio1:
// do operations specific to this selection
break;
case R.id.radio2:
// do operations specific to this selection
break;
}
}
});
}
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
}
}
);
int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();
Hope this works. You can convert your output to string in the above manner.
gender.getCheckedRadioButtonId(); - gender is the id of RadioGroup.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
}
});
For anyone who is populating programmatically and looking to get an index, you might notice that the checkedId changes as you return to the activity/fragment and you re-add those radio buttons. One way to get around that is to set a tag with the index:
for(int i = 0; i < myNames.length; i++) {
rB = new RadioButton(getContext());
rB.setText(myNames[i]);
rB.setTag(i);
myRadioGroup.addView(rB,i);
}
Then in your listener:
myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
int mySelectedIndex = (int) radioButton.getTag();
}
});
just use getCheckedRadioButtonId() function to determine wether if anything is checked, if -1 is the return value, you can avoid showing toast
Radiogroup rgteam;
String team;
rgteam.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
RadioButton rb= (RadioButton) findViewById(checkedId);
team = rb.getText().toString();
}
});
RadioGroup in XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"/>
</RadioGroup>
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:textSize="18dp"
android:text="Select Your Course"
android:textStyle="bold"
android:id="#+id/txtView"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/rdGroup"
android:layout_below="#+id/txtView">
<RadioButton
android:id="#+id/rdbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<Button
android:id="#+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_below="#+id/rdGroup"
android:text="Get Course" />
</RelativeLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioButton android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (RadioButton)findViewById(R.id.rdbAndroid);
angular = (RadioButton)findViewById(R.id.rdbAngular);
java = (RadioButton)findViewById(R.id.rdbJava);
python = (RadioButton)findViewById(R.id.rdbPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = "Selected Course: ";
result+= (android.isChecked())?"Android":(angular.isChecked())?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
});
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
String str="";
// Check which radio button was clicked
switch(view.getId()) {
case R.id.rdbAndroid:
if(checked)
str = "Android Selected";
break;
case R.id.rdbAngular:
if(checked)
str = "AngularJS Selected";
break;
case R.id.rdbJava:
if(checked)
str = "Java Selected";
break;
case R.id.rdbPython:
if(checked)
str = "Python Selected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
Thanks a lot to Chris.
This is my solution:
RadioGroup radgroup_opcionesEventos = null;
private static String[] arrayEventos = {
"CongestiĆ³n", "Derrumbe", "Accidente"
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
radgroup_opcionesEventos = (RadioGroup)findViewById(R.id.rg_opciones_evento);
int i=0;//a.new.ln
for(String evento : arrayEventos) {
//RadioButton nuevoRadio = crearRadioButton(evento);//a.old.ln
RadioButton nuevoRadio = crearRadioButton(evento,i);//a.new.ln
radgroup_opcionesEventos.addView(nuevoRadio,i);
}
RadioButton primerRadio = (RadioButton) radgroup_opcionesEventos.getChildAt(0);
primerRadio.setChecked(true);
}
private RadioButton crearRadioButton(String evento, int n)
{
//RadioButton nuevoRadio = new RadioButton(this);//a.old.ln
RadioButton nuevoRadio = new RadioButton(getApplicationContext());//a.new.ln
LinearLayout.LayoutParams params = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
nuevoRadio.setLayoutParams(params);
nuevoRadio.setText(evento);
nuevoRadio.setTag(evento);
return nuevoRadio;
}
#Override
protected void onResume()
{
radgroup_opcionesEventos.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
//int mySelectedIndex = (int) radioButton.getTag();
String mySelectedIndex = radioButton.getTag().toString();
}
});
super.onResume();
}
I have had problems getting radio buttons id's as well when the RadioButtons are dynamically generated. It does not seem to work if you try to manually set the ID's using RadioButton.setId(). What worked for me was to use View.getChildAt() and View.getParent() in order to iterate through the radio buttons and determine which one was checked. All you need is to first get the RadioGroup via findViewById(R.id.myRadioGroup) and then iterate through it's children. You'll know as you iterate through which button you are on, and you can simply use RadioButton.isChecked() to determine if that is the button that was checked.

How to get current displayed image position?

I want to display the images front and back ward. Like Windows Picture and Fax Viewer This is my code:
package com.my.imagechange;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class ImageChangeDemo extends Activity
{
/** Called when the activity is first created. */
// private Gallery gallery;
private ImageView imgView;
int i=0;
int j=6;
ImageButton btrt,btlt;
Button bt1,bt2;
private Integer[] Imgid ={R.drawable.androidlogo,R.drawable.androids, R.drawable.cool, R.drawable.cupcake2009, R.drawable.donut2009, R.drawable.eclair2009};
int imglength=Imgid.length;
//System.out.println(imglength);
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagechange);
System.out.println(imglength);
btlt=(ImageButton)findViewById(R.id.bt1);
btrt=(ImageButton)findViewById(R.id.bt2);
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageResource(Imgid[0]);
btlt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int choice1=j--;
switch(choice1)
{
case 5:imgView.setImageResource(Imgid[5]);
break;
case 4:imgView.setImageResource(Imgid[4]);
break;
case 3:imgView.setImageResource(Imgid[3]);
break;
case 2:imgView.setImageResource(Imgid[2]);
break;
case 1:imgView.setImageResource(Imgid[1]);
break;
}
}
});
btrt.setOnClickListener(new View.OnClickListener()
{ #SuppressWarnings("unused")
#Override
public void onClick(View v)
{
int choice2=i++;
switch(choice2)
{
case 1:imgView.setImageResource(Imgid[1]);
break;
case 2:imgView.setImageResource(Imgid[2]);
break;
case 3:imgView.setImageResource(Imgid[3]);
break;
case 4:imgView.setImageResource(Imgid[4]);
break;
case 5:imgView.setImageResource(Imgid[5]);
break;
}
}
});
}}
It works forward fine, but when I click backward it doesn't work. Where did I make my mistake? Can anybody tell me?
Thanks in advance.
Please change like this
int choice1=--j;
Edit:
Here the problem is after execution of this code int choice1=j--; choice1 contain value 6, which is not in the switch case
Hi now the code works finely. My code is
package com.my.imagechange;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
public class ImageChange extends Activity
{
private Gallery gallery;
private ImageView imgView;
private ImageButton btlt,btrt;
private Integer[] Imgid= {
R.drawable.androidlogo, R.drawable.androids, R.drawable.cool, R.drawable.cupcake2009, R.drawable.donut2009, R.drawable.eclair2009};
int imglength=Imgid.length;
int img_position;
int img_minus;
int img_plus;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageResource(Imgid[0]);
btlt=(ImageButton)findViewById(R.id.bt1);
btrt=(ImageButton)findViewById(R.id.bt2);
System.out.println("----->"+imglength +"----->");
btlt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
btrt.setEnabled(true);
System.out.println("left button has been clicked");
System.out.println("position: "+img_position);
img_minus=--img_position;
System.out.println("minus:"+img_minus);
imgView.setImageResource(Imgid[img_minus]);
//imgView.setBackgroundDrawable(getResources().getDrawable(id));
if(img_minus==0)
{
btlt.setEnabled(false);
}
}
});
btrt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
btlt.setEnabled(true);
System.out.println("right button has been clicked");
System.out.println("position: "+img_position);
img_plus=++img_position;
System.out.println("plus: "+img_plus);
imgView.setImageResource(Imgid[img_plus]);
if(img_plus==5)
{
btrt.setEnabled(false);
}
}
});
} }
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#ffffff">
<ImageView android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/androidlogo"/>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom"
android:layout_gravity="fill_horizontal"
>
<ImageButton android:id="#+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/butleft"
android:layout_alignParentLeft="true">
</ImageButton>
<ImageButton android:id="#+id/bt2"
android:src="#drawable/butright"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true">
</ImageButton>
</RelativeLayout>
</LinearLayout>

Categories