Unable to set RadioGroup programmatically when another radiogroup element is checked - android

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

Related

How to create nested child on firebase android

[Solved. I solved it myself]
Tips: if you want to access a child in the firebase realtime database for collecting data and then by using that data u store or upload something at that child on the firebase realtime database again, then you can't access it. Either u have to create another child or u must not use that child. (I don't no the actual solution but It works for me)]
I want to create a child under the reference of the user phone number. That child will store one or more childs. These child will be called "serialNo" of the item. And under serialNo child, the item name and amount of piece will store. I want to create like this:
[N: B: I've created this on firebase directly, not by my application.]
But when I put my data object as .setValue(dtObject) the previous one will always be replaced.
"orderNo: 1" child was replaced by "orderNo: 2" child
I also use .updateChildren(dtMap) but everytime previous orderNo child was replaced.
My Code of confirm Fragment(from where I upload):
package com.binarysoftwareltd.airaid;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class AddressFragment extends Fragment {
private int orderNo = 1;
private int orderSerial = 0;
private DatabaseReference dbReference, dbr;
private static final String STATE_USER = "user";
private String mUser;
private View oldView;
private TextView numWarning;
private EditText nameField, phoneField, areaField, addressField,
detailsField;
private CardView confirmCV;
private int len;
private String nameOfPerson, phoneNumber, areaName, addressOfOrder,
detailsOfOrder;
private int[] serialNos = new int[100];
private String[] names = new String[100];
private int[] pieces = new int[100];
private String imageUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mUser = savedInstanceState.getString(STATE_USER);
} else {
// Probably initialize members with default values for a new
instance
mUser = "NewUser";
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
if (oldView != null) {
return oldView;
}
View v = inflater.inflate(R.layout.fragment_address, container,
false);
initializeAll(v);
Bundle bundle = getArguments();
if (bundle != null) {
len = bundle.getInt("cValue");
imageUri = bundle.getString("imgUri");
serialNos = bundle.getIntArray("mSerialNos");
names = bundle.getStringArray("mNames");
pieces = bundle.getIntArray("mPieces");
}
confirmCV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
collectAllData();
if (!phoneNumber.equals("")) {
checkOrderSerial();
} else {
phoneField.requestFocus();
Toast.makeText(getContext(), orderSerial,
Toast.LENGTH_SHORT).show();
}
}
});
oldView = v;
return v;
}
private void checkOrderSerial() {
dbr=FirebaseDatabase.getInstance().getReference(phoneNumber).
child("currentOrderSerial");
dbr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Integer value = dataSnapshot.getValue(Integer.class);
if (value != null)
orderSerial = value;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
showConfirmDialog();
}
private void showConfirmDialog() {
AlertDialog.Builder alb = new AlertDialog.Builder(getContext());
alb.setIcon(R.drawable.question);
alb.setTitle("Confirm");
alb.setMessage("Are you sure want to order?");
alb.setPositiveButton(R.string.exit_no, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alb.setNegativeButton(R.string.exit_yes, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setOrderSerial();
}
});
AlertDialog ald = alb.create();
ald.show();
}
private void setOrderSerial() {
dbr = FirebaseDatabase.getInstance().getReference(phoneNumber);
if (orderNo <= orderSerial) {
orderNo = orderSerial;
orderNo += 1;
}
OrderSerial osObject = new OrderSerial(orderNo);
dbr.setValue(osObject);
uploadAllData();
}
private void uploadAllData() {
dbReference =
FirebaseDatabase.getInstance().getReference(phoneNumber).child("orderNo:
"+orderNo);
DataTemplate dtObject;
int i;
for (i = 0; i < len; i++) {
if (pieces[i] != 0) {
dtObject = new DataTemplate(names[i],pieces[i]);
dbReference.child("serialNo:
"+serialNos[i]).setValue(dtObject);
}
}
}
private void collectAllData() {
nameOfPerson = nameField.getText().toString();
phoneNumber = phoneField.getText().toString();
areaName = areaField.getText().toString();
addressOfOrder = addressField.getText().toString();
detailsOfOrder = detailsField.getText().toString();
}
private void initializeAll(View v) {
numWarning = v.findViewById(R.id.numWarning);
nameField = v.findViewById(R.id.nameField);
phoneField = v.findViewById(R.id.phoneField);
areaField = v.findViewById(R.id.areaField);
addressField = v.findViewById(R.id.addressField);
detailsField = v.findViewById(R.id.detailsField);
confirmCV = v.findViewById(R.id.confirmCV);
}
}
My OrderSerial Class::
package com.binarysoftwareltd.airaid;
public class OrderSerial {
private int currentOrderSerial;
public OrderSerial() {
}
public OrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
public int getCurrentOrderSerial() {
return currentOrderSerial;
}
public void setCurrentOrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
}
The XML code of the AddressFragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/app_main_bg"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="120dp"
android:text="#string/address_fragment_title"
android:textColor="#color/pureBlack"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:id="#+id/numWarning"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="15dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="#string/number_warning"
android:textColor="#color/img_warning"
android:textSize="15sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/name_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_person"/>
<EditText
android:id="#+id/nameField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_weight="7"
android:layout_height="70dp"
android:hint="#string/name_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/phone_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_phone"/>
<EditText
android:id="#+id/phoneField"
android:layout_marginStart="5dp"
android:inputType="phone"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="4"
android:hint="#string/phone_field" />
<EditText
android:id="#+id/areaField"
android:layout_marginStart="10dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3"
android:hint="#string/area_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/address_fragment_title"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_location"/>
<EditText
android:id="#+id/addressField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/address_fragment_title" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/details_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_details"/>
<EditText
android:id="#+id/detailsField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/details_field" />
</LinearLayout>
<androidx.cardview.widget.CardView
android:id="#+id/confirmCV"
android:layout_width="match_parent"
android:layout_height="40dp"
android:clickable="true"
android:focusable="true"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
app:cardCornerRadius="18dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/card_view_bg"
android:gravity="center">
<ImageView
android:contentDescription="#string/order_now"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/ic_confirm" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="#string/order_now"
android:textColor="#color/pureWhite"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>
here my JSON::
{
"23" : {
"currentOrderSerial" : 2,
"orderNo: 2" : {
"serialNo: 1" : {
"name" : "napa Extra",
"piece" : 200
}
}
}
}
[I use phone number as primary Identifier for every user. That's why phone numbers must be required.]
Please help to fix this...
Thanks in Advance...

button not functioning?

I created a android studio button for my app and when I click on the register button it doesn't work . I don't get any errors it just doesn't work . When the user clicks the quiz button I want to go to the quiz activity
MainActivity.java
package com.littlekidsmath.yoong.mathlearningforkids;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemSelectedListener{
Button addBtn, subBtn, multiBtn, divisionBtn,quiz;
String[] levels = {"Easy","Medium","Hard"};
SharedPreferences prefs;
Switch settings;
Spinner language;
public String[] languages = {GameActivity.ENG,GameActivity.ARABIC,"বাংলা",GameActivity.FRENCH,GameActivity.GERMAN,GameActivity.MALAY};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("MyPref",MODE_PRIVATE);
settings = (Switch) findViewById(R.id.settings);
if(prefs.getBoolean("SOUND", false)){
settings.setChecked(true);
}
settings.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
prefs.edit().putBoolean("SOUND",b).commit();
}
});
addBtn = (Button) findViewById(R.id.addtion);
subBtn = (Button) findViewById(R.id.sub);
multiBtn = (Button) findViewById(R.id.multi);
divisionBtn = (Button) findViewById(R.id.divide);
quiz = (Button) findViewById(R.id.quiz);
language = (Spinner) findViewById(R.id.language);
addBtn.setOnClickListener(this);
subBtn.setOnClickListener(this);
multiBtn.setOnClickListener(this);
divisionBtn.setOnClickListener(this);
quiz.setOnClickListener(this);
language.setOnItemSelectedListener(this);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);
language.setAdapter(adapter);
int pos = 0;
//
for(int i=0;i<languages.length;i++){
if(prefs.getString(GameActivity.LANGUAGE,"").equals(languages[i])){
pos = i;
break;
}
}
language.setSelection(pos);
if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.BANGLA)){
setBangla();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ARABIC)){
setArabic();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.FRENCH)){
setFrence();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.GERMAN)){
setGerman();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ENG)){
setEnglish();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.MALAY)){
setMalay();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addtion: {
levelChooseDialog("+");
break;
}
case R.id.sub: {
levelChooseDialog("-");
break;
}
case R.id.multi: {
levelChooseDialog("X");
break;
}
case R.id.divide: {
levelChooseDialog("/");
break;
}
case R.id.quiz: {
Intent intent = new Intent(MainActivity.this, HomeScreen.class);
startActivity(intent);
}
}
}
public void levelChooseDialog(final String operator){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = View.inflate(this,R.layout.level_dialog,null);
builder.setView(view);
ListView listView = (ListView) view.findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,levels);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int level = 0;
if (position == 0){
level = 0;
}else if(position == 1){
level = 1;
}else {
level = 2;
}
startActivity(new Intent(MainActivity.this,LessonActivity.class).putExtra("level",level)
.putExtra("operator",operator));
}
});
builder.create().show();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
prefs.edit().putString(GameActivity.LANGUAGE,languages[position]).commit();
if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.BANGLA))
{
setBangla();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ARABIC)){
setArabic();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.FRENCH)){
setFrence();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.GERMAN)){
setGerman();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ENG)){
setEnglish();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.MALAY)){
setMalay();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void setBangla(){
addBtn.setText(Languages.BANGLA[0]);
subBtn.setText(Languages.BANGLA[1]);
multiBtn.setText(Languages.BANGLA[3]);
divisionBtn.setText(Languages.BANGLA[2]);
settings.setText(Languages.BANGLA[4]);
levels[0] = Languages.BANGLA[7];
levels[1] = Languages.BANGLA[8];
levels[2] = Languages.BANGLA[9];
}
public void setArabic(){
addBtn.setText(Languages.ARABIC[0]);
subBtn.setText(Languages.ARABIC[1]);
multiBtn.setText(Languages.ARABIC[3]);
divisionBtn.setText(Languages.ARABIC[2]);
settings.setText(Languages.ARABIC[4]);
levels[0] = Languages.ARABIC[7];
levels[1] = Languages.ARABIC[8];
levels[2] = Languages.ARABIC[9];
}
public void setMalay(){
addBtn.setText(Languages.MALAY[0]);
subBtn.setText(Languages.MALAY[1]);
multiBtn.setText(Languages.MALAY[3]);
divisionBtn.setText(Languages.MALAY[2]);
settings.setText(Languages.MALAY[4]);
levels[0] = Languages.MALAY[7];
levels[1] = Languages.MALAY[8];
levels[2] = Languages.MALAY[9];
}
public void setFrence(){
addBtn.setText(Languages.FRENCH[0]);
subBtn.setText(Languages.FRENCH[1]);
multiBtn.setText(Languages.FRENCH[3]);
divisionBtn.setText(Languages.FRENCH[2]);
settings.setText(Languages.FRENCH[4]);
levels[0] = Languages.FRENCH[7];
levels[1] = Languages.FRENCH[8];
levels[2] = Languages.FRENCH[9];
}
public void setGerman(){
addBtn.setText(Languages.GERMAN[0]);
subBtn.setText(Languages.GERMAN[1]);
multiBtn.setText(Languages.GERMAN[3]);
divisionBtn.setText(Languages.GERMAN[2]);
settings.setText(Languages.GERMAN[4]);
levels[0] = Languages.GERMAN[7];
levels[1] = Languages.GERMAN[8];
levels[2] = Languages.GERMAN[9];
}
public void setEnglish(){
addBtn.setText(Languages.ENGLISH[0]);
subBtn.setText(Languages.ENGLISH[1]);
multiBtn.setText(Languages.ENGLISH[3]);
divisionBtn.setText(Languages.ENGLISH[2]);
settings.setText(Languages.ENGLISH[4]);
levels[0] = Languages.ENGLISH[7];
levels[1] = Languages.ENGLISH[8];
levels[2] = Languages.ENGLISH[9];
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
android:gravity="center_vertical"
android:orientation="vertical"
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="com.littlekidsmath.yoong.mathlearningforkids.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/addtion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/add"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Addition" />
<Button
android:id="#+id/sub"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/minus"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Subtraction" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/multi"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/cancel"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Multiplication" />
<Button
android:id="#+id/divide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/division"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Division" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/quiz"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:paddingBottom="20dp"
android:paddingTop="20dp"
android:text="Quiz" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text=""
android:textColor="#color/white"
android:textSize="18sp" />
<Switch
android:id="#+id/settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="#dimen/activity_horizontal_margin"
android:text="Sound"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:text="Language" />
<Spinner
android:id="#+id/language"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:background="#color/white"
android:padding="10dp"></Spinner>
</LinearLayout>
Can anyone help please? When click on the quiz button the application will close. I want it to go to quiz page which called HomeScreen.java
looks good to me, did u declare the second activity in the manifest file? :
<activity android:name="HomeScreen"/>
If that doesn't work, use some break points and the debugger, hope it helps.

onOptionsItemClick or onMenuItemClick not being called

(Very first thing i want to make clear is that i am COMPLETELY NEWBIE, very beginner in android, in fact in programming/coding!)
The menu is referred in onCreateOptionMenu and the calling method is also onOptionsItemSelected to open up menu but the method for each option/item is set as onMenuItemClick and onMenuItemLongClick which is ideal for context menu options/items!
The problem is onMenuItemClick have input parameters as (View v, int position) and I cannot change it to only (View v) or to (MenuItem item).
What I want is clicking on each item of menu should bring out new activity!
I also tried putting all my switch-case-break statements to onOptionsItemSelected method but it is still not working!
I also tried in fragment class, setHasOptionsMenu (true); but it did not work!
onMenuItemClick doesn't get called
(Deprecated) Fragment onOptionsItemSelected not being called
Below is the activity_main_menu.xml layout
<?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="match_parent"
android:orientation="vertical"
android:background="#color/menu_item_background">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Below is the fragment_main.xml layout
<ScrollView 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="com.example.android.coffeeshop.MainFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/menu_item_background">
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/Toppings" />
<CheckBox
android:id="#+id/whippedCreamcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/WhippedCream"
android:textSize="16sp" />
<CheckBox
android:id="#+id/Chocolatebox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/Chocolate"
android:textSize="16sp" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/quantity" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="decrement"
android:text="#string/minus" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="16dp"
android:text="#string/Zero"
android:textColor="#android:color/black"
android:textSize="20sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="increment"
android:text="#string/plus" />
</LinearLayout>
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/OrderSummary" />
<TextView
android:id="#+id/order_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/Price"
android:textColor="#android:color/black"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="submitOrder"
android:text="#string/Order" />
<Button
android:id="#+id/placeOrder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:onClick="placeOrder"
android:text="#string/PlaceOrder" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Below is the MainMenu.java class file from where i am trying to handle fragment menu!
package com.example.android.coffeeshop5profile;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* This app displays an order form to order coffee.
*/
public class MainMenu extends AppCompatActivity implements ActionMenuView.OnMenuItemClickListener, OnMenuItemLongClickListener {
private FragmentManager fragmentManager;
private ContextMenuDialogFragment mMenuDialogFragment;
int quantity = 1;
int price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
fragmentManager = getSupportFragmentManager();
initToolbar();
initMenuFragment();
addFragment(new MainFragment(), true, R.id.container);
}
private void initMenuFragment() {
MenuParams menuParams = new MenuParams();
menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
menuParams.setMenuObjects(getMenuObjects());
menuParams.setClosableOutside(false);
mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
mMenuDialogFragment.setItemLongClickListener(this);
}
private List<MenuObject> getMenuObjects() {
List<MenuObject> menuObjects = new ArrayList<>();
MenuObject close = new MenuObject();
close.setResource(R.drawable.icn_close);
MenuObject send = new MenuObject("Send message");
send.setResource(R.drawable.icn_1);
MenuObject like = new MenuObject("Like profile");
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
like.setBitmap(b);
MenuObject addFr = new MenuObject("Add to friends");
BitmapDrawable bd = new BitmapDrawable(getResources(),
BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
addFr.setDrawable(bd);
MenuObject addFav = new MenuObject("Add to favorites");
addFav.setResource(R.drawable.icn_4);
MenuObject block = new MenuObject("Block user");
block.setResource(R.drawable.icn_5);
menuObjects.add(close);
menuObjects.add(send);
menuObjects.add(like);
menuObjects.add(addFr);
menuObjects.add(addFav);
menuObjects.add(block);
return menuObjects;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.btn_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mToolBarTextView.setText(R.string.title_text);
}
protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStackName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(containerId, fragment, backStackName)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackStack)
transaction.addToBackStack(backStackName);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_menu:
if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
}
break;
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
}
return false; //Turning this true or to super.OnOptionsItemSelected did nothing!
}
#Override
public void onBackPressed() {
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
mMenuDialogFragment.dismiss();
} else {
finish();
}
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
} return true;
}
#Override
public void onMenuItemLongClick(View clickedView, int position) {
Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
public void submitOrder(View view) {
String orderSummaryString = createOrderSummary(quantity);
displayMessage(orderSummaryString);
}
public void placeOrder(View view) {
TextView useremail = (TextView) findViewById(R.id.useremail);
String useremailString = useremail.getText().toString();
String orderSummaryString = createOrderSummary(quantity);
sendMail(useremailString, "Coffee Order By: " + useremailString, orderSummaryString);
}
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private Message createMessage(String email, String subject, String messageBody, Session session)
throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("clientaddress#gmail.com", "Coffee Order By"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("clientaddress#gmail.com", "************");
}
});
}
public class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainMenu.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
#Override
public Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
if (quantity < 100) {
quantity = quantity + 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You have reached maximum numbers of coffees to be allowed!", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if (quantity >= 2) {
quantity = quantity - 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You can not place order in negative number!", Toast.LENGTH_SHORT).show();
}
}
public String createOrderSummary(int quantity) {
CheckBox whippedCreamCheckbox = (CheckBox) findViewById(R.id.whippedCreamcheckbox);
boolean hasWhippedCream = whippedCreamCheckbox.isChecked();
CheckBox chocolatebox = (CheckBox) findViewById(R.id.Chocolatebox);
boolean hasChocolate = chocolatebox.isChecked();
price = 5;
if (hasWhippedCream) {
price = price + 1;
}
if (hasChocolate) {
price = price + 2;
}
int finalPrice = quantity * price;
EditText usernameTextView = (EditText) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
EditText usercontact = (EditText) findViewById(R.id.usercontact);
String userContactString = usercontact.getText().toString();
EditText useremail = (EditText) findViewById(R.id.useremail);
String userEmailString = useremail.getText().toString();
String OrderSummary = getString(R.string.username) + ": " + usernameString;
OrderSummary += "\n" + getString(R.string.ContactNumber) + " " + userContactString;
OrderSummary += "\n" + getString(R.string.eAddress) + " " + userEmailString;
OrderSummary += "\n" + getString(R.string.AddedWhippedCream) + " " + hasWhippedCream;
OrderSummary += "\n" + getString(R.string.AddedChocolate) + " " + hasChocolate;
OrderSummary += "\n" + getString(R.string.quantity) + ": " + quantity;
OrderSummary += "\n" + getString(R.string.totalprice) + finalPrice;
OrderSummary += "\n" + getString(R.string.thankyou);
return OrderSummary;
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(String.format("%d", number));
}
/**
* This method displays the given text on the screen.
*/
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
}
Below is the MainFragment.java class file
package com.example.android.coffeeshop5profile;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
setMenuVisibility(false);
return rootView;
}
}
Following is the Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue_grey_700"
android:orientation="vertical"
android:weightSum="4"
tools:context=".legacy.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/google_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:contentDescription="#string/desc_google_icon"
android:src="#drawable/googleg_color" />
<TextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_gravity="center"
android:text="#string/title_text"
android:textColor="#android:color/white"
android:textSize="36sp" />
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/signed_out"
android:textColor="#android:color/white"
android:textSize="14sp" />
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="true"
android:gravity="center"
android:maxLines="5"
android:padding="10dp"
android:scrollbars="vertical"
android:textColor="#android:color/white"
android:textSize="14sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/blue_grey_900">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
tools:visibility="gone" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:visibility="gone"
tools:visibility="visible">
<Button
android:id="#+id/sign_out_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/sign_out"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/disconnect_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/disconnect"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/secondpage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/secondpage"
android:theme="#style/ThemeOverlay.MyDarkButton" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
below is the res/menu/context_main_menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/context_menu"
android:title="#string/context_menu"
android:icon="#drawable/btn_add"
android:orderInCategory="100"
app:showAsAction="always" />
</menu>
...unfortunately, 30000 characters limit has been reached so i cant upload mainActivity.java file!
Kindly help!
Best regards,
sagar
try this code on
Change the following code
onMenuItemClick(MenuItem item)
to
onMenuItemClick(View clickedView, int position)
like this
`#override
public void onMenuItemClick(View clickedView, int position) {
switch (position) {
case 1:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
case 2:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
}
}`
i hope this help you
If onOptionsItemSelected() method is not called in fragment then just make sure you return false from the onOptionsItemSelected() method of Activity.

Datepicker and TimePicker dialogs take two clickes of button

So for the life of me I can not find the reason behind needing to click twice on the start date and start time for the picker dialog to open. I have searched these forums many times and they have all been mostly related to edit text fields whereas mine is a simple button but the onClickListener takes two hits. Thanks in advance.
This is my Class:
package com.shotsevolved.app
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.List;
public class DealCreator extends FragmentActivity {
String mUsername;
String companyName;
ParseGeoPoint location;
String title;
double mOldPrice;
double mNewPrice;
boolean isFree;
boolean isUnlimited;
String mDescription;
int mUses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "Ztgl9DAaj4XPrDnS2Ro8jNHiaNnTPFCeF6V1Gm71", "26QMHWwfHmxKfwMvKemaEXH2XsFxpO5sR8Csuo9v");
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_deal_creator);
final Button create = (Button)findViewById(R.id.createButton);
final ProgressBar progress = (ProgressBar)findViewById(R.id.progressIcon);
final LinearLayout view = (LinearLayout)findViewById(R.id.linView);
final LinearLayout view1 = (LinearLayout)findViewById(R.id.linView1);
final LinearLayout main = (LinearLayout)findViewById(R.id.mainLinear);
final CheckBox freeBox = (CheckBox)findViewById(R.id.freeBox);
final EditText oldPrice = (EditText)findViewById(R.id.oldPrice);
final EditText newPrice = (EditText)findViewById(R.id.newPrice);
final CheckBox unlimited = (CheckBox)findViewById(R.id.unlimitedBox);
final EditText uses = (EditText)findViewById(R.id.uses);
final Button date = (Button)findViewById(R.id.startDate);
final Button time = (Button)findViewById(R.id.startTime);
create.setVisibility(View.INVISIBLE);
Intent intent = getIntent();
mUsername = intent.getStringExtra("key");
ParseQuery<ParseObject> query = ParseQuery.getQuery("appUsers");
query.whereEqualTo("username", mUsername);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> user, ParseException e) {
if(user.size() == 1 && e == null){
int admin = user.get(0).getInt("admin");
if(admin == 2){
ParseQuery<ParseObject> query = ParseQuery.getQuery("AdminNames");
query.whereEqualTo("username", mUsername);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> user, ParseException e) {
if(user.size() == 1 && e == null){
unlimited.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
uses.setVisibility(View.INVISIBLE);
view1.removeView(uses);
}else{
uses.setVisibility(View.VISIBLE);
view1.addView(uses);
}
}
});
freeBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
oldPrice.setVisibility(View.INVISIBLE);
newPrice.setVisibility(View.INVISIBLE);
view.removeView(oldPrice);
view.removeView(newPrice);
}else{
oldPrice.setVisibility(View.VISIBLE);
newPrice.setVisibility(View.VISIBLE);
view.addView(oldPrice);
view.addView(newPrice);
}
}
});
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog(main);
}
});
time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog(main);
}
});
progress.setVisibility(View.GONE);
view.removeView(progress);
create.setVisibility(View.VISIBLE);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(freeBox.isChecked()){
isFree = true;
mOldPrice = 0;
mNewPrice = 0;
}else{
mOldPrice = Double.parseDouble(oldPrice.getText().toString());
mNewPrice = Double.parseDouble(newPrice.getText().toString());
isFree = false;
}
if(unlimited.isChecked()){
isUnlimited = true;
mUses = 0;
}else{
mUses = Integer.parseInt(uses.getText().toString());
isUnlimited = false;
}
//Call create deal class
deal();
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! Database Hacked!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! You are not an Admin!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}else{
Context context = getApplicationContext();
CharSequence text = "Error!!! Database Hacked!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
private void deal() {
ParseObject newDeal = new ParseObject("Deals");
newDeal.put("uses", mUses);
newDeal.put("unlimitedUses", isUnlimited);
newDeal.put("description", mDescription);
newDeal.put("free", isFree);
newDeal.put("title", title);
newDeal.put("oldPrice", mOldPrice);
newDeal.put("newPrice", mNewPrice);
newDeal.put("location", location);
newDeal.put("username", mUsername);
newDeal.put("companyName", companyName);
newDeal.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Context context = getApplicationContext();
CharSequence text = "Deal Saved";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
And these are my Fragments:
Date:
package com.shotsevolved.app;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
Time:
package com.shotsevolved.app;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
And finally my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#1e1c1c"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="#dimen/height"
android:layout_alignParentTop="true"
android:background="#color/purple"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageButton
android:id="#+id/btn_backFromSettings"
android:layout_width="#dimen/width"
android:layout_height="fill_parent"
android:background="#drawable/ui_button_purple"
android:contentDescription="#string/desc"
android:src="#drawable/ico_left" />
<LinearLayout
android:layout_width="#dimen/divider_size"
android:layout_height="fill_parent"
android:background="#color/dark_purple" >
</LinearLayout>
<TextView
android:id="#+id/mainLogin"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:tag="bold"
android:text="#string/dealCreator"
android:textColor="#color/white"
android:textSize="#dimen/tex_size_xxlarge" />
<LinearLayout
android:layout_width="#dimen/divider_size"
android:layout_height="fill_parent"
android:background="#color/dark_purple" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/mainLinear">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/dim_20"
android:id="#+id/linView">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressIcon"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/titleOfDeal"
style="#style/EditText_Purple"
android:hint="Title of Deal"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/dealDescription"
android:gravity="top"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Describe company and deal"
android:layout_gravity="center_horizontal" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Free"
android:layout_marginTop="#dimen/dim_10"
style="#style/CheckBox_Purple"
android:textColor="#color/offwhite"
android:id="#+id/freeBox" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/oldPrice"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Old cost of product"
android:inputType="numberDecimal"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/newPrice"
android:layout_marginTop="#dimen/dim_10"
android:inputType="numberDecimal"
style="#style/EditText_Purple"
android:hint="New cost of product"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linView1"
android:paddingRight="#dimen/dim_20"
android:paddingLeft="#dimen/dim_20">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unlimited uses"
style="#style/CheckBox_Purple"
android:textColor="#color/offwhite"
android:id="#+id/unlimitedBox" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/uses"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Number of uses per customer"
android:inputType="number"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linView2"
android:gravity="center_horizontal"
android:layout_marginTop="#dimen/dim_10"
android:paddingRight="#dimen/dim_20"
android:paddingLeft="#dimen/dim_20">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startDate"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Start Date"
android:layout_marginRight="#dimen/dim_10"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/startTime"
android:layout_marginTop="#dimen/dim_10"
style="#style/EditText_Purple"
android:hint="Start Time"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/dim_10"
android:gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set expiry date"
android:layout_marginRight="#dimen/dim_10"
android:padding="#dimen/dim_10"
style="#style/Button_Purple"
android:id="#+id/dateButtonEnd"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set expiry time"
android:padding="#dimen/dim_10"
style="#style/Button_Purple"
android:id="#+id/timeButtonEnd"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Create"
android:padding="#dimen/dim_10"
android:layout_marginTop="#dimen/dim_10"
android:layout_marginLeft="#dimen/dim_20"
android:layout_marginRight="#dimen/dim_20"
style="#style/Button_Purple"
android:id="#+id/createButton"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Hmm, your code looks ok. Can you try adding android:focusable="false" to your buttons. I'm curious if the problem is that you're just requesting focus the first click and the second actually initiates the click.
Also, if this doesn't help, can you put some logs in your click listener and also in the public void showTimePickerDialog(View v) { method as well ... to see if it's triggered the first click at all.
Try to add delay on button click it will avoid multi click
date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
date.setEnabled(false);
showDatePickerDialog(main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
date.setEnabled(true);
}
}, 100);
}
});

how to switch from a fragment in a fragmentActivity to the Activity in android

I have a fragment class in with I am having few fragment tabs. each of them are opening another dedicated fragment. but I want to change one fragment to open an activity class. I have gone through many examples but didn't the problem solve. everytime my application goes crashed.
here is my fragment class.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.appdupe.flamer.LoginUsingFacebook;
import com.appdupe.flamer.LoginUsingFacebook.BackGroundTaskForFetchingDataFromFaceBook;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.androidquery.AQuery;
import com.androidquery.callback.ImageOptions;
import com.appdupe.androidpushnotifications.ChatActivity;
import com.appdupe.flamer.QuestionsActivity;
import com.appdupe.flamer.pojo.LikeMatcheddataForListview;
import com.appdupe.flamer.pojo.LikedMatcheData;
import com.appdupe.flamer.pojo.Likes;
import com.appdupe.flamer.utility.AlertDialogManager;
import com.appdupe.flamer.utility.AppLog;
import com.appdupe.flamer.utility.ConnectionDetector;
import com.appdupe.flamer.utility.Constant;
import com.appdupe.flamer.utility.ScalingUtilities;
import com.appdupe.flamer.utility.ScalingUtilities.ScalingLogic;
import com.appdupe.flamer.utility.SessionManager;
import com.appdupe.flamer.utility.Ultilities;
import com.appdupe.flamer.utility.Utility;
import com.appdupe.flamerchat.db.DatabaseHandler;
import com.appdupe.flamernofb.R;
import com.google.gson.Gson;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenListener;
public class MainActivity extends SherlockFragmentActivity implements
OnClickListener, OnOpenListener {
// MainLayout mLayout;
private static final String TAG = "MainActivity";
private ListView matcheslistview;
Button btMenu;
private Button buttonRightMenu;
TextView tvTitle;
private Typeface topbartextviewFont;
private Editor editor;
private SharedPreferences preferences;
private EditText etSerchFriend;
double mLatitude = 0;
double mLongitude = 0;
double dLatitude = 0;
double dLongitude = 0;
// private Session.StatusCallback statusCallback = new
// SessionStatusCallback();
private Dialog mdialog;
// private boolean usersignup = false;
private boolean isProfileclicked = false;
private ArrayList<LikeMatcheddataForListview> arryList;
private MatchedDataAdapter adapter;
private ImageView profileimage;
private LinearLayout profilelayout, homelayout, messages, settinglayout,
invitelayout, questionLayout;
public SlidingMenu menu;
private boolean flagforHome, flagForProfile, flagForsetting;
// private AQuery aQuery;
private ImageOptions options;
private ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// mLayout = (MainLayout)
// this.getLayoutInflater().inflate(R.layout.slidmenuxamplemainactivity,
// null);
// setContentView(mLayout);
cd = new ConnectionDetector(this);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
// aQuery = new AQuery(this);
options = new ImageOptions();
options.fileCache = true;
options.memCache = true;
setContentView(R.layout.slidmenuxamplemainactivity);
if (preferences.getBoolean(Constant.PREF_ISFIRST, true)) {
editor.putBoolean(Constant.PREF_ISFIRST, false);
editor.commit();
//startActivity(new Intent(this, QuestionsActivity.class));
}
tvTitle = (TextView) findViewById(R.id.activity_main_content_title);
topbartextviewFont = Typeface.createFromAsset(getAssets(),
"fonts/HelveticaLTStd-Light.otf");
tvTitle.setTypeface(topbartextviewFont);
tvTitle.setTextColor(Color.rgb(255, 255, 255));
tvTitle.setTextSize(20);
menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT_RIGHT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
Log.d(TAG, "onCreate before add menu ");
menu.setMenu(R.layout.leftmenu);
menu.setSecondaryMenu(R.layout.rightmenu);
Log.d(TAG, "onCreate add menu ");
menu.setSlidingEnabled(true);
Log.d(TAG, "onCreate finish");
// search
etSerchFriend = (EditText) menu
.findViewById(R.id.et_serch_right_side_menu);
// btnSerch = (Button) menu.findViewById(R.id.btn_serch_right_side);
View leftmenuview = menu.getMenu();
View rightmenuview = menu.getSecondaryMenu();
initLayoutComponent(leftmenuview, rightmenuview);
menu.setSecondaryOnOpenListner(this);
// lvMenuItems = getResources().getStringArray(R.array.menu_items);
// lvMenu.setAdapter(new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
// lvMenuItems));
matcheslistview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// logDebug("setOnItemClickListener onItemClick arg2 "+arg2);
LikeMatcheddataForListview matcheddataForListview = (LikeMatcheddataForListview) arg0
.getItemAtPosition(arg2);
String faceboolid = matcheddataForListview.getFacebookid();
// logDebug(" background setOnItemClickListener onItemClick friend facebook id faceboolid "+faceboolid);
// logDebug(" background setOnItemClickListener onItemClick user facebook id faceboolid"+new
// SessionManager(MainActivity.this).getFacebookId());
Bundle mBundle = new Bundle();
mBundle.putString(Constant.FRIENDFACEBOOKID, faceboolid);
mBundle.putString(Constant.CHECK_FOR_PUSH_OR_NOT, "1");
Intent mIntent = new Intent(MainActivity.this,
ChatActivity.class);
mIntent.putExtras(mBundle);
startActivity(mIntent);
menu.toggle();
}
});
buttonRightMenu = (Button) findViewById(R.id.button_right_menu);
btMenu = (Button) findViewById(R.id.button_menu);
btMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Show/hide the menu
toggleMenu(v);
}
});
try {
profilelayout.setOnClickListener(this);
homelayout.setOnClickListener(this);
messages.setOnClickListener(this);
settinglayout.setOnClickListener(this);
invitelayout.setOnClickListener(this);
questionLayout.setOnClickListener(this);
} catch (Exception e) {
AppLog.handleException("oncreate Exception ", e);
}
// Bundle extras = getIntent().getExtras();
System.out.println("Get Intent done");
try {
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FindMatches fragment = new FindMatches();
ft.add(R.id.activity_main_content_fragment, fragment);
tvTitle.setText(getResources().getString(R.string.app_name));
ft.commit();
setProfilePick(profileimage);
} catch (Exception e) {
AppLog.handleException("onCreate Exception ", e);
}
Ultilities mUltilities = new Ultilities();
int imageHeightAndWidht[] = mUltilities
.getImageHeightAndWidthForAlubumListview(this);
arryList = new ArrayList<LikeMatcheddataForListview>();
adapter = new MatchedDataAdapter(this, arryList, imageHeightAndWidht);
matcheslistview.setAdapter(adapter);
// final SessionManager sessionManager = new SessionManager(this);
buttonRightMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isProfileclicked) {
Intent mIntent = new Intent(MainActivity.this,
EditProfileNew.class);
startActivity(mIntent);
} else {
toggleRightMenu(v);
}
}
});
initSerchData();
}
private void initSerchData() {
etSerchFriend.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString().trim());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void setMenuTouchFullScreenEnable(boolean isEnable) {
if (isEnable) {
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
} else {
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
}
}
#Override
public void onOpen() {
AppLog.Log(TAG, "onOpen");
findLikedMatched();
}
#Override
protected void onResume() {
super.onResume();
AppLog.Log(TAG, " MainActivity onResume called");
}
private void setProfilePick(final ImageView userProfilImage) {
final Ultilities mUltilities = new Ultilities();
new Thread(new Runnable() {
#Override
public void run() {
final Bitmap bitmapimage = Utility.getBitmapFromURL(preferences
.getString(Constant.PREF_PROFILE_IMAGE_ONE, ""));
runOnUiThread(new Runnable() {
#Override
public void run() {
AppLog.Log(
TAG,
"Profile Image Url:"
+ preferences
.getString(
Constant.PREF_PROFILE_IMAGE_ONE,
""));
Bitmap cropedBitmap = null;
ScalingUtilities mScalingUtilities = new ScalingUtilities();
Bitmap mBitmap = null;
if (bitmapimage != null) {
cropedBitmap = mScalingUtilities
.createScaledBitmap(bitmapimage, 80, 80,
ScalingLogic.CROP);
bitmapimage.recycle();
mBitmap = mUltilities.getCircleBitmap(cropedBitmap,
1);
cropedBitmap.recycle();
userProfilImage.setImageBitmap(mBitmap);
// aQuery.id(userProfilImage).image(mBitmap);
} else {
}
}
});
}
}).start();
}
private void initLayoutComponent(View leftmenu, View rightmenu) {
matcheslistview = (ListView) rightmenu
.findViewById(R.id.menu_right_ListView);
profileimage = (ImageView) leftmenu.findViewById(R.id.profileimage);
profilelayout = (LinearLayout) leftmenu
.findViewById(R.id.profilelayout);
homelayout = (LinearLayout) leftmenu.findViewById(R.id.homelayout);
messages = (LinearLayout) leftmenu.findViewById(R.id.messages);
settinglayout = (LinearLayout) leftmenu
.findViewById(R.id.settinglayout);
invitelayout = (LinearLayout) leftmenu.findViewById(R.id.invitelayout);
/*questionLayout = (LinearLayout) leftmenu
.findViewById(R.id.questionLayout);*///devraj
}
private void findLikedMatched() {
AppLog.Log(TAG, "findLikedMatched");
String params[] = { preferences.getString(Constant.FACEBOOK_ID, "") };
new BackgroundTaskForFindLikeMatched().execute(params);
}
private class BackgroundTaskForFindLikeMatched extends
AsyncTask<String, Void, Void> {
private Ultilities mUltilities = new Ultilities();
private List<NameValuePair> getuserparameter;
private String likedmatchedata;
private LikedMatcheData matcheData;
private ArrayList<Likes> likesList;
private LikeMatcheddataForListview matcheddataForListview;
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
MainActivity.this);
private boolean isResponseSuccess = true;
#Override
protected Void doInBackground(String... params) {
try {
File appDirectory = mUltilities
.createAppDirectoy(getResources().getString(
R.string.appdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground appDirectory "
+ appDirectory);
File _picDir = new File(appDirectory, getResources().getString(
R.string.imagedirematchuserdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground ");
getuserparameter = mUltilities.getUserLikedParameter(params);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground getuserparameter "
+ getuserparameter);
likedmatchedata = mUltilities.makeHttpRequest(
Constant.getliked_url, Constant.methodeName,
getuserparameter);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likedmatchedata "
+ likedmatchedata);
Gson gson = new Gson();
matcheData = gson.fromJson(likedmatchedata,
LikedMatcheData.class);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground matcheData "
+ matcheData);
if (matcheData.getErrFlag() == 0) {
likesList = matcheData.getLikes();
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList "
+ likesList);
if (arryList != null) {
arryList.clear();
}
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList sized "
+ likesList.size());
for (int i = 0; i < likesList.size(); i++) {
matcheddataForListview = new LikeMatcheddataForListview();
String userName = likesList.get(i).getfName();
String facebookid = likesList.get(i).getFbId();
String picturl = likesList.get(i).getpPic();
int falg = likesList.get(i).getFlag();
String latd = likesList.get(i).getLadt();
matcheddataForListview.setFacebookid(facebookid);
matcheddataForListview.setUserName(userName);
matcheddataForListview.setImageUrl(picturl);
matcheddataForListview.setFlag("" + falg);
matcheddataForListview.setladt(latd);
File imageFile = mUltilities.createFileInSideDirectory(
_picDir, userName + facebookid + ".jpg");
Utility.addBitmapToSdCardFromURL(likesList.get(i)
.getpPic().replaceAll(" ", "%20"), imageFile);
matcheddataForListview.setFilePath(imageFile
.getAbsolutePath());
if (!preferences.getString(Constant.FACEBOOK_ID, "")
.equals(facebookid)) {
arryList.add(matcheddataForListview);
}
}
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
MainActivity.this);
ArrayList<LikeMatcheddataForListview> arryListtem = mDatabaseHandler
.getUserFindMatch();
AppLog.Log(TAG, "arryListtem " + arryListtem);
if (arryListtem != null && arryListtem.size() > 0) {
AppLog.Log(TAG, "arryList size " + arryListtem.size());
arryList.clear();
arryList.addAll(arryListtem);
mUltilities.showImage
}
}
// "errNum": "50",
// "errFlag": "1",
// "errMsg": "Sorry, no matches found!"
else if (matcheData.getErrFlag() == 1) {
ArrayList<LikeMatcheddataForListview> arryListtem = mDatabaseHandler
.getUserFindMatch();
AppLog.Log(TAG, "arryListtem " + arryListtem);
if (arryListtem != null && arryListtem.size() > 0) {
AppLog.Log(TAG, "arryList size " + arryListtem.size());
arryList.clear();
arryList.addAll(arryListtem);
}
} else {
}
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched doInBackground Exception ",
e);
isResponseSuccess = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPostExecute ");
try {
mdialog.dismiss();
} catch (Exception e) {
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched onPostExecute Exception "
+ e);
}
if (!isResponseSuccess) {
AlertDialogManager.errorMessage(MainActivity.this, "Alert",
"Request timeout");
}
adapter.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPreExecute ");
try {
mdialog = mUltilities.GetProcessDialog(MainActivity.this);
mdialog.setCancelable(false);
mdialog.show();
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched onPreExecute Exception ",
e);
}
}
}
private class MatchedDataAdapter extends
ArrayAdapter<LikeMatcheddataForListview> {
private AQuery aQuery;
private Activity mActivity;
private LayoutInflater mInflater;
private SessionManager sessionManager;
public MatchedDataAdapter(Activity context,
List<LikeMatcheddataForListview> objects,
int imageHeigthAndWidth[]) {
super(context, R.layout.matchedlistviewitem, objects);
mActivity = context;
mInflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// this.imageHeigthAndWidth=imageHeigthAndWidth;
sessionManager = new SessionManager(context);
aQuery = new AQuery(context);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public LikeMatcheddataForListview getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.matchedlistviewitem,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.userimage);
holder.textview = (TextView) convertView
.findViewById(R.id.userName);
holder.lastMasage = (TextView) convertView
.findViewById(R.id.lastmessage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview.setId(position);
holder.imageview.setId(position);
holder.lastMasage.setId(position);
holder.textview.setText(getItem(position).getUserName());
aQuery.id(holder.imageview).image(getItem(position).getImageUrl());
try {
holder.lastMasage.setText(sessionManager
.getLastMessage(getItem(position).getFacebookid()));
} catch (Exception e) {
AppLog.handleException(TAG + " getView Exception ", e);
}
return convertView;
}
class ViewHolder {
ImageView imageview;
TextView textview;
TextView lastMasage;
}
}
public void toggleMenu(View v) {
menu.toggle();
}
public void toggleRightMenu(View v) {
menu.showSecondaryMenu();
}
#Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.toggle();
} else if (menu.isSecondaryMenuShowing()) {
menu.showSecondaryMenu();
} else {
super.onBackPressed();
}
}
#Override
public void onStop() {
super.onStop();
if (mdialog != null) {
mdialog.dismiss();
mdialog = null;
}
}
#Override
protected void onDestroy() {
if (mdialog != null && mdialog.isShowing()) {
mdialog.dismiss();
}
super.onDestroy();
}
#Override
public void onClick(View v) {
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment = null;
if (v.getId() == R.id.homelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagforHome) {
menu.toggle();
return;
} else {
fragment = new FindMatches();
buttonRightMenu
.setBackgroundResource(R.drawable.selector_for_message_button);
tvTitle.setText(getResources().getString(R.string.app_name));
flagforHome = true;
flagForProfile = false;
flagForsetting = false;
isProfileclicked = false;
if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
}
menu.toggle();
}
} else if (v.getId() == R.id.profilelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagForProfile) {
menu.toggle();
return;
} else {
buttonRightMenu.setBackgroundResource(R.drawable.edit_btn);
isProfileclicked = true;
fragment = new UserProfile();
tvTitle.setText(getResources().getString(R.string.myprofile));
flagforHome = false;
flagForProfile = true;
flagForsetting = false;
if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
}
menu.toggle();
}
}
else if (v.getId() == R.id.settinglayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagForsetting) {
menu.toggle();
return;
} else {
buttonRightMenu
.setBackgroundResource(R.drawable.selector_for_message_button);
tvTitle.setText(getResources().getString(R.string.settings));
fragment = new SettingActivity();
flagforHome = false;
flagForProfile = false;
flagForsetting = true;
flagForInvite=false;
isProfileclicked = false;
/*if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
// tvTitle.setText(selectedItem);
}*/
menu.toggle();
/*Intent setIntent = new Intent(getApplicationContext(),Setting2.class);
startActivity(setIntent);*/
}
}
///devraj
else if (v.getId() == R.id.messages) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
toggleRightMenu(v);
} /*else if (v.getId() == R.id.questionLayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;*/
/*}
menu.toggle();
Intent questionIntent = new Intent(this, QuestionsActivity.class);
startActivity(questionIntent);*/
//}
else if (v.getId() == R.id.invitelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
// Change by Dilavar
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"I am using Flamer App ! Why don't you try it out...\nInstall Flamer now !\nhttps://play.google.com/store/apps/details?id=com.appdupe.flamernofb");
sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
" Flamer App !");
sendIntent.setType("message/rfc822"); //
sendIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[] { " info#appdupe.com" });
startActivity(Intent
.createChooser(sendIntent, "Send mail using..."));
}
/*settinglayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent mintent = new Intent(getApplicationContext(),Setting2.class);
startActivity(mintent);
}
});*/
}
}
I want Setting tab to open a new activity not fragment that is Setting2
here is my activity class that I have to open
import android.app.Activity;
import android.os.Bundle;
public class Setting2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.setting2);
}
}
Here is my layout , I am posting it here as it so long and don't have permission to post more lines in question.
<?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="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#088A08" >
<Button
android:id="#+id/button_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:background="#drawable/selector_for_menu_button"
android:onClick="toggleMenu" />
<TextView
android:id="#+id/activity_main_content_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Toker" />
<Button
android:id="#+id/button_right_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#drawable/selector_for_message_button"
android:onClick="rightmenu" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="150dp"
android:background="#088A08" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#088A08" >
<ImageView
android:id="#+id/imagev1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/btn_add_photo"
android:gravity="center_horizontal" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:background="#088A08"
android:gravity="center_horizontal"
android:text="View My Profile" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="5.0">
<RelativeLayout
android:id="#+id/lin1"
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:background="#ffffff"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignTop="#+id/imageView1"
android:layout_marginBottom="9dp"
android:layout_marginLeft="21dp"
android:layout_toRightOf="#+id/imageView1"
android:text="Discovery Settings"
android:textSize="12dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignLeft="#+id/textView1"
android:text="Change who you see" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/pref" />
<Button
android:id="#+id/morebtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/settings" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView2"
android:layout_marginLeft="23dp"
android:layout_toRightOf="#+id/imageView2"
android:text="App Settings"
android:textSize="12dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView2"
android:layout_alignLeft="#+id/textView3"
android:text="Notification and Resource" />
<Button
android:id="#+id/morebtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/filter" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView3"
android:layout_marginLeft="23dp"
android:layout_toRightOf="#+id/imageView3"
android:text="What are you into" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignTop="#+id/imageView3"
android:text="Your Interest"
android:textSize="12dp" />
<Button
android:id="#+id/morebtn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView8"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/reachout" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView5"
android:layout_marginLeft="27dp"
android:layout_toRightOf="#+id/imageView5"
android:text="We want to hear it all" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView6"
android:layout_alignTop="#+id/imageView5"
android:text="Get in Touch"
android:textSize="12dp" />
<Button
android:id="#+id/morebtn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView7"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/share" />
<Button
android:id="#+id/morebtn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView5"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/morebtn5"
android:layout_marginLeft="27dp"
android:layout_toRightOf="#+id/imageView4"
android:text="Help us spread the world" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView9"
android:layout_alignTop="#+id/imageView4"
android:text="Tell Your Friends"
android:textSize="12dp" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
</LinearLayout>
</LinearLayout>
Step 1
- declare your activity inside of the manifest
Step 2
- starActivity(new Intent(getAcivity(), MyClass.class));
Step 3
- post your logcat if this didn't help while it should !
Edit: the issue seems that you are not setting a height to your layouts, base on your layout that you posted you have five layouts that are missing android:layout_height please add that and force close shall be gone.

Categories

Resources