I need help with the timer. I need a timer to activate in each question and when it is finished it should disable the radio group. The problem in this code is that when the timer finish it disable all the radio groups in all the questions.
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuizActivity extends AppCompatActivity {
TextView tv,mTextField;
Button btnNext;
RadioGroup rg;
RadioButton rb1,rb2,rb3,rb4;
String questions[]={"First Android Phone?","Name of Android Version 4.4?","Android is which kind of software?"};
String ans[]={"Motorola Droid","Kitkat","Operating-System"};
String opt[]={"HTC-G1","HTC-One","Motorola Droid","Samsung S4","Jelly Bean","Kitkat","Froyo","Lollipop",
"Operating-System","Antivirus","Application","Tools"};
int flag=0;
public static int marks,correct,wrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
tv = (TextView)findViewById(R.id.tvque);
mTextField = (TextView)findViewById(R.id.tv2);
btnNext = (Button)findViewById(R.id.btnNext);
rg = (RadioGroup)findViewById(R.id.radioGroup);
rb1 = (RadioButton)findViewById(R.id.radio0);
rb2 = (RadioButton)findViewById(R.id.radio1);
rb3 = (RadioButton)findViewById(R.id.radio2);
rb4 = (RadioButton)findViewById(R.id.radio3);
tv.setText(questions[flag]);
rb1.setText(opt[0]);
rb2.setText(opt[1]);
rb3.setText(opt[2]);
rb4.setText(opt[3]);
new CountDownTimer(20000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
for (int i=0; i< rg.getChildCount();i++){
rg.getChildAt(i).setEnabled(false);
}
//mTextField.setText("done!");
}
}.start();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
RadioButton uans=(RadioButton)findViewById(rg.getCheckedRadioButtonId());
String ansText = uans.getText().toString();
if (ansText.equalsIgnoreCase(ans[flag]))
{
correct++;
}
else
{
wrong++;
}
flag++;
if(flag<questions.length)
{
tv.setText(questions[flag]);
rb1.setText(opt[flag*4]);
rb2.setText(opt[(flag*4)+1]);
rb3.setText(opt[(flag*4)+2]);
rb4.setText(opt[(flag*4)+3]);
}
else
{
marks=correct;
Intent in = new Intent(getApplicationContext(),ResultActivity.class);
startActivity(in);
}
}
});
}
}
UI of the application
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id = "#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Question"
android:id="#+id/tvque" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioGroup"
android:layout_below="#+id/tvque"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton"/>
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"/>
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"/>
<RadioButton
android:id="#+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"/>
</RadioGroup>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Next Question"
android:id="#+id/btnNext"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnNext"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="41dp"
android:id="#+id/tv2" />
This code now worked for me.
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuizActivity extends AppCompatActivity {
TextView tv,mTextField;
Button btnNext;
RadioGroup rg;
RadioButton rb1,rb2,rb3,rb4;
String questions[]={"First Android Phone?","Name of Android Version 4.4?","Android is which kind of software?"};
String ans[]={"Motorola Droid","Kitkat","Operating-System"};
String opt[]={"HTC-G1","HTC-One","Motorola Droid","Samsung S4","Jelly Bean","Kitkat","Froyo","Lollipop",
"Operating-System","Antivirus","Application","Tools"};
int flag=0;
public static int marks,correct,wrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
tv = (TextView)findViewById(R.id.tvque);
mTextField = (TextView)findViewById(R.id.tv2);
btnNext = (Button)findViewById(R.id.btnNext);
rg = (RadioGroup)findViewById(R.id.radioGroup);
rb1 = (RadioButton)findViewById(R.id.radio0);
rb2 = (RadioButton)findViewById(R.id.radio1);
rb3 = (RadioButton)findViewById(R.id.radio2);
rb4 = (RadioButton)findViewById(R.id.radio3);
tv.setText(questions[flag]);
rb1.setText(opt[0]);
rb2.setText(opt[1]);
rb3.setText(opt[2]);
rb4.setText(opt[3]);
final CountDownTimer Counter1 = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
for (int i=0; i< rg.getChildCount();i++){
rg.getChildAt(i).setEnabled(false);
}
}
}.start();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
RadioButton uans=(RadioButton)findViewById(rg.getCheckedRadioButtonId());
String ansText = uans.getText().toString();
if (ansText.equalsIgnoreCase(ans[flag]))
{
correct++;
}
else
{
wrong++;
}
flag++;
if(flag<questions.length)
{
tv.setText(questions[flag]);
rb1.setText(opt[flag*4]);
rb2.setText(opt[(flag*4)+1]);
rb3.setText(opt[(flag*4)+2]);
rb4.setText(opt[(flag*4)+3]);
for (int i=0; i< rg.getChildCount();i++){
rg.getChildAt(i).setEnabled(true);
}
Counter1.start();
}
else
{
marks=correct;
Intent in = new Intent(getApplicationContext(),ResultActivity.class);
startActivity(in);
}
}
});
}
}
private CountDownTimer timer;
onCrate()....
....
timer = new CountDownTimer(20000, 1000) {....};
timer.start();
....
onClick(){....
rb4.setText(opt[(flag * 4) + 3]);
timer.start();
};
Related
I am trying to programmatically generate two RadioGroups. I have succesfully generated the first one but I need to generate the second one onCheckedChangeListener of the first radio group. Here is my code for the activity.
package com.packr.activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.avast.android.dialogs.fragment.SimpleDialogFragment;
import com.avast.android.dialogs.iface.ISimpleDialogListener;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import com.packr.R;
import com.packr.adapters.ShipmentsAdapter;
import com.packr.classes.Item;
import com.packr.classes.Packr;
import com.packr.classes.Shipment;
import com.packr.database.DBShipments;
import com.packr.logging.L;
import java.util.ArrayList;
public class ItemDetailsActivity extends AppCompatActivity implements ISimpleDialogListener, ImageChooserListener {
private Toolbar toolbar;
private ImageChooserManager imageChooserManager;
private SeekBar seekBar;
private Intent intent;
private RadioGroup itemTypeRadioGroup, deliveryMethod;
private TextView addImage;
private Bitmap myBitmap;
private ShipmentsAdapter mShipmentAdapter;
private static long back_pressed;
private MyShipmentsActivity activity;
private ImageView itemImage;
private LinearLayout itemDetailsLinearLayout, weightTypeLinearLayout;
private TextInputLayout itemDescriptionText, quantityText, valueOfItemText;
private EditText itemDescription, quantity, valueOfItem;
private TextView weightUnit, weightValue, selectWeight;
private ArrayList<Shipment> shipmentArrayList = new ArrayList<>();
private ArrayList<Item> deliveryTypeArrayList = new ArrayList<>();
private ArrayList<Item> itemTypeArrayList = new ArrayList<>();
private ArrayList<Item> shipmentTypeArrayList = new ArrayList<>();
private ArrayList<Item> weightTypeArrayList = new ArrayList<>();
private String city, state, pincode, recipientName, recipientContact, street, itemType = "", deliveryType = "", route;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_details);
initialize();
onClick();
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Item details");
setSupportActionBar(toolbar);
deliveryTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.DELIVERY_TYPE);
for (int i = 0; i < deliveryTypeArrayList.size(); i++) {
}
itemTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.ITEM_TYPE);
int itemId;
//first radio group
RadioButton rb = null;
float scale = getResources().getDisplayMetrics().density;
final int dpAsPixels = (int) (10 * scale + 0.5f);
RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
rg.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
final Drawable drawableTop = getResources().getDrawable(R.drawable.document_icon);
for (int i = 0; i < itemTypeArrayList.size(); i++) {
if (itemTypeArrayList.get(i).getActive() == 1) {
rb = new RadioButton(this);
rg.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
rb.setText(itemTypeArrayList.get(i).getCode());
rb.setId(itemTypeArrayList.get(i).getId());
L.m(itemTypeArrayList.get(i).getId() + "hello");
}
if (rb != null) {
rb.setAllCaps(true);
}
assert rb != null;
rb.setGravity(Gravity.CENTER_VERTICAL);
rb.setButtonDrawable(null);
rb.setPadding(dpAsPixels, 0, dpAsPixels, 0);
rb.setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null);
}
itemDetailsLinearLayout.addView(rg);
final RadioGroup weightTypeRadioGroup = new RadioGroup(this); //create the RadioGroup
weightTypeRadioGroup.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
weightTypeRadioGroup.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
shipmentTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.SHIPMENT_TYPE);
for (int i = 0; i < shipmentTypeArrayList.size(); i++) {
}
final RadioButton finalRb = rb;
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (finalRb != null) {
checkedId = finalRb.getId();
System.out.print(checkedId);
L.m(group.getCheckedRadioButtonId() + "");
weightTypeArrayList = Packr.getWritableDatabase().readWeightType();
for (int i = 0; i < weightTypeArrayList.size(); i++) {
L.m(weightTypeArrayList.get(i).getTitle());
//second radio group
RadioButton weightTypeRadioButton = null;
weightTypeRadioButton = new RadioButton(getApplicationContext());
weightTypeRadioGroup.addView(weightTypeRadioButton);
weightTypeRadioButton.setText(weightTypeArrayList.get(i).getTitle());
weightTypeRadioButton.setId(weightTypeArrayList.get(i).getId());
}
if (weightTypeRadioGroup.getParent() != null){
((ViewGroup)weightTypeRadioGroup.getParent()).removeView(weightTypeRadioGroup);
weightTypeLinearLayout.addView(weightTypeRadioGroup);
}
}
}
});
deliveryMethod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.normalDeliveryRadioButton) {
deliveryType = "Normal Delivery";
} else {
deliveryType = "Express Delivery";
}
}
});
}
#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_item_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_done) {
if (validationCheck()) {
Shipment shipment = new Shipment();
shipment.setRecipientName(recipientName);
shipment.setRecipientContact(recipientContact);
shipment.setCity(city);
shipment.setState(state);
shipment.setStreetNo(street);
shipment.setRoute(route);
shipment.setPostalCode(pincode);
shipment.setItemQuantity(quantity.getText().toString());
shipment.setItemType(itemType);
shipment.setDeliveryType(deliveryType);
shipmentArrayList.add(shipment);
Packr.getWritableDatabase().insertShipment(shipmentArrayList, false);
mShipmentAdapter = new ShipmentsAdapter(getApplicationContext(), activity);
mShipmentAdapter.setShipmentArrayList(shipmentArrayList);
Intent intent = new Intent(ItemDetailsActivity.this, MyShipmentsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void initialize() {
intent = getIntent();
recipientName = intent.getStringExtra("recipientName");
recipientContact = intent.getStringExtra("recipientContact");
city = intent.getStringExtra("city");
state = intent.getStringExtra("state");
pincode = intent.getStringExtra("pincode");
street = intent.getStringExtra("street");
route = intent.getStringExtra("route");
deliveryMethod = (RadioGroup) findViewById(R.id.radioGroupShippingMethod);
selectWeight = (TextView) findViewById(R.id.selectWeight);
addImage = (TextView) findViewById(R.id.addImage);
itemImage = (ImageView) findViewById(R.id.item_image);
itemDescriptionText = (TextInputLayout) findViewById(R.id.item_description_text_input_layout);
quantityText = (TextInputLayout) findViewById(R.id.item_quantity_text_input_layout);
valueOfItemText = (TextInputLayout) findViewById(R.id.item_value_text_input_layout);
itemDescription = (EditText) findViewById(R.id.item_description_edit_text);
quantity = (EditText) findViewById(R.id.item_quantity_edit_text);
valueOfItem = (EditText) findViewById(R.id.item_value_edit_text);
itemDetailsLinearLayout = (LinearLayout) findViewById(R.id.itemDetailsLinearLayout);
weightTypeLinearLayout = (LinearLayout) findViewById(R.id.weightTypeRadioButton);
}
public void onClick() {
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDialogFragment.createBuilder(getApplicationContext(), getSupportFragmentManager()).setTitle("Choose item image").setMessage(R.string.selectImage).setNegativeButtonText("Gallery").setPositiveButtonText("Camera").show();
}
});
}
public Boolean validationCheck() {
if (itemDescription.getText().length() == 0) {
itemDescriptionText.setErrorEnabled(true);
itemDescriptionText.setError("Please provide an item description");
} else if (quantity.getText().length() == 0) {
quantityText.setErrorEnabled(true);
quantityText.setError("Provide item quantity");
} else if (valueOfItem.getText().length() == 0) {
valueOfItemText.setErrorEnabled(true);
valueOfItemText.setError("Please provide value of item");
} else {
return true;
}
return false;
}
public void chooseImage() {
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_PICK_PICTURE);
imageChooserManager.setImageChooserListener(this);
try {
imageChooserManager.choose();
} catch (Exception e) {
e.printStackTrace();
}
}
public void snapImage() {
imageChooserManager = new ImageChooserManager(this, ChooserType.REQUEST_CAPTURE_PICTURE);
imageChooserManager.setImageChooserListener(this);
try {
imageChooserManager.choose();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onNegativeButtonClicked(int i) {
chooseImage();
}
#Override
public void onNeutralButtonClicked(int i) {
}
#Override
public void onPositiveButtonClicked(int i) {
snapImage();
}
#Override
public void onImageChosen(ChosenImage chosenImage) {
myBitmap = BitmapFactory.decodeFile(chosenImage.getFileThumbnail());
runOnUiThread(new Runnable() {
public void run() {
itemImage.setImageBitmap(myBitmap);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK &&
(requestCode == ChooserType.REQUEST_PICK_PICTURE ||
requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
imageChooserManager.submit(requestCode, data);
}
}
#Override
public void onError(String s) {
}
#Override
public void onBackPressed() {
AlertDialog.Builder alert = new AlertDialog.Builder(ItemDetailsActivity.this);
alert.setTitle("Cancel shipment");
alert.setMessage("Are you sure?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ItemDetailsActivity.this, MyShipmentsActivity.class);
startActivity(intent);
finish();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Cancel
}
});
alert.show();
}
}
Here is the code for my layout xml file.
<RelativeLayout
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context="com.packr.activities.ItemDetailsActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<ScrollView
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="80dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="What are you sending?"
android:fontFamily="sans-serif-light"
android:padding="20dp"
android:textColor="#color/textColorPrimary"/>
<LinearLayout
android:id="#+id/itemDetailsLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
tools:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="UseCompoundDrawables">
<ImageView
android:id="#+id/item_image"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:src="#drawable/image_background"
android:layout_margin="16dp"
android:contentDescription="#string/product_image" />
<TextView
android:id="#+id/addImage"
android:padding="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add an image"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:textColor="#color/textColorSecondary"
/>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_description_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="gone"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<EditText
android:id="#+id/item_description_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/item_description"
android:inputType="textMultiLine"
android:imeOptions="flagNoFullscreen"
android:lines="5"/>
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/selectWeight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Permitted weight"
android:fontFamily="sans-serif-light"
android:padding="20dp"/>
</RelativeLayout>
<LinearLayout
android:id="#+id/weightTypeRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_quantity_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="visible"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/item_quantity_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/itemQuantity"
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_value_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="visible"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/item_value_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/item_value"
android:inputType="number"
android:imeOptions="flagNoFullscreen"/>
</android.support.design.widget.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose shipping method"
android:fontFamily="sans-serif-light"
android:textColor="#color/textColorPrimary"
android:layout_marginLeft="25dp"
android:layout_marginStart="25dp"
android:layout_marginTop="25dp"/>
<RadioGroup
android:id="#+id/radioGroupShippingMethod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<RadioButton
android:id="#+id/normalDeliveryRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Normal Delivery"
android:checked="true"/>
<RadioButton
android:id="#+id/expressDeliveryRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Express Delivery"/>
</RadioGroup>
</LinearLayout>
</ScrollView>
//This contains the layout for the bottom price bar //
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/textColorPrimary"
android:padding="12dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<TextView
android:id="#+id/priceText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:textColor="#color/white"/>
<TextView
android:id="#+id/equals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/equals"
android:textSize="18sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textColor="#color/white"/>
<TextView
android:id="#+id/Rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Rs"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:textColor="#color/white"/>
<TextView
android:id="#+id/calculatedPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="550"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:textColor="#color/white"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
do you not just need to repeat the same proccess inside the onCheckChangedListener?
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//Create another radio group here
//then add it to the view
RadioGroup rg2 = new RadioGroup(this); //create the RadioGroup
rg2.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
rg2.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
final Drawable drawableTop = getResources().getDrawable(R.drawable.document_icon);
for (int i = 0; i < itemTypeArrayList.size(); i++) {
if (itemTypeArrayList.get(i).getActive() == 1) {
rb = new RadioButton(this);
rg2.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
rb.setText(itemTypeArrayList.get(i).getCode());
rb.setId(itemTypeArrayList.get(i).getId());
}
}
itemDetailsLinearLayout.addView(rg);
}
});
You may need to declare rg2 public at the top of the class so it can be accessed by the onCheckChangedListener
How to create an android mobile application that will do a counting in miliseconds (start from 0), and ask user to type"I Like to eat" in EditText and click submit. After user click submit, counting will stop and a dialog box will appear and show the counting result.
package com.example.labex4;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView textView1,textView2,textView3,textView4,displayValue;
EditText nameTxt;
Button button1;
int count = 0;
Timer T;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
displayValue.setText("count="+count);
count++;
}
});
}
}, 0, 1);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
textView4 = (TextView)findViewById(R.id.textView4);
displayValue = (TextView)findViewById(R.id.displayValue);
nameTxt = (EditText)findViewById(R.id.nameTxt);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
T.cancel();
dialog.editext.setText(""+count);
}
}
***Here is The 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"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="(Type Faster)"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="25dp"
android:text="Miliseconds: " />
<TextView
android:id="#+id/displayValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:text="displayvalue" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="Type this words: " />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Frankie Jones Anak Saing"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView4"
android:layout_marginTop="38dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/nameTxt"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:text="Check" />
</RelativeLayout>
Global Variable
int count = 0;
Timer T;
Put the below code in onCreate after setContentView
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
//myTextView.setText("count="+count);
count++;
}
});
}
}, 0, 1);
At Button OnCLick
UPDATE
T.cancel();
//Open popup or dialog or alert as per your choice and print the count value
//dialog.editext.setText(""+count);
AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
alertDialog.setTitle("You total time count");
alertDialog.setMessage(String.valueof(count));
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
alertDialog.dismiss();
}
});
alertDialog.show(); //<-- See This!
}
As Per Your Requirement I am pasting the whole class
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity implements OnClickListener {
TextView textView1,textView2,textView3,textView4,displayValue;
EditText nameTxt;
Button button1;
int count = 0;
Timer T;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
displayValue.setText("count="+count);
count++;
}
});
}
}, 0, 1);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
textView4 = (TextView)findViewById(R.id.textView4);
displayValue = (TextView)findViewById(R.id.displayValue);
nameTxt = (EditText)findViewById(R.id.nameTxt);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
T.cancel();
//Open popup or dialog or alert as per your choice and print the count value
//dialog.editext.setText(""+count);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_popup);
dialog.setTitle("Typing Result!");
// set the custom dialog components - text, image and button
TextView titletext = (TextView) dialog.findViewById(R.id.titletext);
//titletext.setText("Typing Result!");
titletext.setVisibility(View.GONE);
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Frankie Jones Igat, Your Typing Speed "+String.valueOf(count)+" miliseconds");
Button dialogButtonOK = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButtonOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
And Custom pop up layout in layout folder custom_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#999999"
android:layout_marginTop="10dp">
<TextView
android:id="#+id/titletext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="title"
android:textSize="18sp"
android:textColor="#android:color/black"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titletext"
android:layout_marginTop="5dp"
android:textSize="16sp"
android:text="titlekiefsjisejefsjeaij"
android:textColor="#android:color/black"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/dialogButtonOK"
android:layout_width="80dp"
android:layout_height="40dp"
android:text=" Ok "
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/text"
android:textSize="18sp"
android:textColor="#android:color/black"
android:layout_centerHorizontal="true"
android:gravity="center"
android:background="#FF0000"
android:layout_marginBottom="10dp"
/>
</RelativeLayout>
\how use sharedpreferences on all field?
Layout XML:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="75dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1." />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:layout_marginRight="10dp"/>
<TextView
android:id="#+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="www.google.co.in"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="75dp" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2." />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="00:00" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="www.yahoo.co.in"
android:ems="10" />
</LinearLayout>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:layout_weight="0.11"
android:text="WebView" />
</LinearLayout>
main activicty
package com.example.myproject5;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
public class MainActivity extends Activity {
private TextView tv6, tv7, tv11, tv12;
private EditText et1, et2;
private CheckBox cb1, cb2;
private Button submit, webview;
private int hour;
private int minute;
public static final String PREFS_NAME = "MyPrefsFile";
private static final int TIME_DIALOG_ID = 1;
private static final int TIME_DIALOG_ID1 = 2;
private static final int TIME_DIALOG_ID2 = 3;
private static final int TIME_DIALOG_ID3 = 4;
int cur = 0;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
private int savelogin;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv6 = (TextView) findViewById(R.id.textView6);
tv7 = (TextView) findViewById(R.id.textView7);
tv11 = (TextView) findViewById(R.id.textView11);
tv12 = (TextView) findViewById(R.id.textView12);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
cb1 = (CheckBox) findViewById(R.id.checkBox1);
cb2 = (CheckBox) findViewById(R.id.checkBox2);
submit = (Button) findViewById(R.id.button1);
webview = (Button) findViewById(R.id.button2);
tv6.setEnabled(false);
tv7.setEnabled(false);
tv11.setEnabled(false);
tv12.setEnabled(false);
et1.setEnabled(false);
et2.setEnabled(false);
loginPreferences = getSharedPreferences(PREFS_NAME, 0);
savelogin = loginPreferences.getInt("abc", 0); // save data
if (savelogin == 1) {
tv6.setText(savelogin);
} else if (savelogin == 2) {
tv7.setText(savelogin);
} else if (savelogin == 3) {
tv11.setText(0);
} else if (savelogin == 4) {
tv12.setText(0);
}
cb1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (cb1.isChecked()) {
tv6.setEnabled(true);
tv11.setEnabled(true);
et1.setEnabled(true);
} else {
tv6.setEnabled(false);
tv11.setEnabled(false);
et1.setEnabled(false);
}
}
});
cb2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (cb2.isChecked()) {
tv7.setEnabled(true);
tv12.setEnabled(true);
et2.setEnabled(true);
} else {
tv7.setEnabled(false);
tv12.setEnabled(false);
et2.setEnabled(false);
}
}
});
tv6.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
loadpreferences1("abc", 1);
}
});
tv7.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID1);
loadpreferences1("abc", 2);
}
});
tv11.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID2);
loadpreferences1("abc", 3);
}
});
tv12.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID3);
loadpreferences1("abc", 4);
}
});
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
webview.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, second.class);
startActivity(intent);
loadpreferences1("abc", 5);
}
});
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
cur = TIME_DIALOG_ID;
return new TimePickerDialog(this, timePickerListener, hour, minute, true);
case TIME_DIALOG_ID1:
cur = TIME_DIALOG_ID1;
return new TimePickerDialog(this, timePickerListener, hour, minute, true);
case TIME_DIALOG_ID2:
cur = TIME_DIALOG_ID2;
return new TimePickerDialog(this, timePickerListener, hour, minute, true);
case TIME_DIALOG_ID3:
cur = TIME_DIALOG_ID3;
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
if (cur == TIME_DIALOG_ID) {
tv6.setText(new StringBuilder().append(pad(hour)).append(":").append(pad(minute)));
} else if (cur == TIME_DIALOG_ID1) {
tv7.setText(new StringBuilder().append(pad(hour)).append(":").append(pad(minute)));
} else if (cur == TIME_DIALOG_ID2) {
tv11.setText(new StringBuilder().append(pad(hour)).append(":").append(pad(minute)));
} else if (cur == TIME_DIALOG_ID3) {
tv12.setText(new StringBuilder().append(pad(hour)).append(":").append(pad(minute)));
}
}
};
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
private void loadpreferences1(String str, int in) {
loginPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
loginPrefsEditor.putInt(str, in);
loginPrefsEditor.commit();
}
}
Use these method to save and get values from any where in your app change parameter according to your requirment
this method to save value in shared prefrences
public static void setPref(Context c, String pref, String val) {
Editor e = PreferenceManager.getDefaultSharedPreferences(c).edit();
e.putString(pref, val);
e.commit();
}
this method to get value from shared prefrences
public static String getPref(Context c, String pref, String val) {
return PreferenceManager.getDefaultSharedPreferences(c).getString(pref,
val);
}
Hi I'm trying to develop an application which runs for every interval time, lets say for every 1 minute it will display some Toast message.
But problem is I'm using RadioButton functionality is perfect but when I tap on one radio button it will be green, but when I close and re-open the activity I'll get as none of the radio buttons selected.
Here is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
//some code
}
break;
}
}
}
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/radio">
<RadioButton android:id="#+id/radio_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_one_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ten_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10 minute"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Please help me to solve this riddle.
Thanks in advance...
This code is useful for store the ratingbar state, when we start new activity, you will see the previous rating state..
package com.example.ratingbar;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class RatingbarMainActivity extends Activity {
RatingBar ratingbarClick;
Button sub_btn;
TextView textRatingView , textRatingViewSave;
Boolean val = true;
float ans = (float) 0.0;
//--------------------------------------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ratingbar_main);
ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
ratingbarClick.setOnRatingBarChangeListener(rateObj);
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
ans = sharePref.getFloat("Get_Rating", 0.0f);
System.out.println("--------------------------------------ans = " + ans);
if(val) {
ratingbarClick.setRating(ans);
}
else {
ratingbarClick.setRating(ans);
}
textRatingView = (TextView) findViewById(R.id.ratingView);
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
//textRatingView.setText(String.valueOf(rating));
ans = ratingbarClick.getRating();
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
SharedPreferences.Editor edit = sharePref.edit();
edit.putFloat("Get_Rating", ans);
edit.commit();
val = false;
}
};
//--------------------------------------------------------------------------------------------
}
---------------------------------------------------------------------------------------------------
activity_ratingbar_main.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" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ratingBar1"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="23dp"
android:text="Select Your Rating Bar Here"
tools:context=".RatingbarMainActivity" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="63dp" />
<TextView
android:id="#+id/ratingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ratingBar1"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Click To Save Rating In TextBox" />
</RelativeLayout>
it is the simplest way to do so,no need of sharedpreference at all.you will get confused while using it.keep the things simple like this
public class MainActivity extends Activity {
Public static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(flag==1)
radio_one_min.setChecked(true);
else if(flag==2)
radio_ten_min.setCheckek(true);
else if(flag==3)
radio_disable.setCheckek(true);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
flag =1;
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
flag=2 ;
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
flag=3;
//some code
}
break;
}
}
}
[EDITED]
I found developer.android.com/training/basics/activity-lifecycle/recreating.html document first, so my first guess was using Bundles and on Save/Resume Instace State methods. However this does not seem to work well. Here's my final attempt at a working solution (using SharedPreferences class, as suggested by some users):
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class MainActivity extends Activity {
final String PREFERENCES = "prefs";
final String RADIO_BUTTON = "prefsval";
SharedPreferences sp;
Editor e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
e = sp.edit();
}
#Override
protected void onResume() {
super.onResume();
if (sp != null) {
if (sp.getInt(RADIO_BUTTON, 0) != 0) {
RadioButton rb;
rb = (RadioButton) findViewById(sp.getInt(RADIO_BUTTON, 0));
rb.setChecked(true);
}
}
}
public void onRadioButtonClicked(View view) {
e.putInt(RADIO_BUTTON, view.getId());
e.apply();
}
}
Im trying to make a simple quote app, but every time I hit my back button after my next button it will go to the next array and not backwards. Im using an int num to keep track of with quote the user is on.
here is my back button
package me.me.quote;
public class Startme extends Activity {
Random gen= new Random();
int num;
String[] quotes = new String[15];
public void next(View N){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
if(num == 5){
num =0;}
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num++]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
public void back(View B){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num--]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);}
public void rand(View G) {
num = gen.nextInt(5);
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.startquotes);
TextView Dark=(TextView)findViewById(R.id.Quote);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/font1.ttf");
Dark.setTypeface(face);
}
}
//LAYOUT FILE text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:text="VISIBLE EVERY TIME"
android:visibility="visible" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="NEXT" >
</Button>
<Button
android:id="#+id/next"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="BACK" >
</Button>
</RelativeLayout>
///ACTIVITY CLASS
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
Button next;
Button back ;
TextView quoteText;
int currentSelectedQuote=0;
String[] quote={"QUOTE1","QUOTE2","QUOTE3","QUOTE4","QUOTE5",};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
quoteText=(TextView)findViewById(R.id.textView);
quoteText.setText(quote[currentSelectedQuote]);
next=(Button)findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentSelectedQuote++;
if(currentSelectedQuote == 5){
currentSelectedQuote =0;}
quoteText.setText(quote[currentSelectedQuote]);
}
});
back=(Button)findViewById(R.id.back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(currentSelectedQuote==0)
{
currentSelectedQuote=4;
}
else
{
currentSelectedQuote--;
}
quoteText.setText(quote[currentSelectedQuote]);
// TODO Auto-generated method stub
}
});
}
}