(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.
Related
I have method loadFragment(); In which i load the DashboardFragment which is having a framelayout widget. But inside the loadFragment() i get a null pointer exception and i dont know why. I have attached the loadFragment(). please help me. Thanks!
The error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.FrameLayout.getId()' on a null object reference.
at com.qdocs.smartschool.fragments.StudentDashboardFragment.loadFragment(StudentDashboardFragment.java:241)
loadFragment(new DashboardCalender());
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(calenderFrame.getId(), fragment);
transaction.addToBackStack(null);
transaction.commit();
}
The studentDashboardFragment class
package com.qdocs.smartschool.fragments;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.qdocs.smartschool.R;
import com.qdocs.smartschool.students.StudentAttendance;
import com.qdocs.smartschool.students.StudentHomework;
import com.qdocs.smartschool.students.StudentTasks;
import com.qdocs.smartschool.utils.Constants;
import com.qdocs.smartschool.utils.Utility;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class StudentDashboardFragment extends Fragment {
RelativeLayout attendanceLayout, homeworkLayout, pendingTaskLayout;
TextView attendanceValue, homeworkValue, pendingTaskValue;
CardView attendanceCard, homeworkCard, pendingTaskCard;
FrameLayout calenderFrame;
public Map<String, String> headers = new HashMap<String, String>();
public Map<String, String> params = new Hashtable<String, String>();
public StudentDashboardFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.student_dashboard_fragment, container, false);
attendanceLayout = mainView.findViewById(R.id.student_dashboard_fragment_attendanceView);
homeworkLayout = mainView.findViewById(R.id.student_dashboard_fragment_homeworkView);
pendingTaskLayout = mainView.findViewById(R.id.student_dashboard_fragment_pendingTaskView);
attendanceCard = mainView.findViewById(R.id.student_dashboard_fragment_attendanceCard);
homeworkCard = mainView.findViewById(R.id.student_dashboard_fragment_homeworkCard);
pendingTaskCard = mainView.findViewById(R.id.student_dashboard_fragment_pendingTaskCard);
attendanceValue = mainView.findViewById(R.id.student_dashboard_fragment_attendance_value);
homeworkValue = mainView.findViewById(R.id.student_dashboard_fragment_homework_value);
pendingTaskValue = mainView.findViewById(R.id.student_dashboard_fragment_pendingTask_value);
calenderFrame = mainView.findViewById(R.id.dashboardViewPager);
loadData();
attendanceLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent asd = new Intent(getActivity().getApplicationContext(), StudentAttendance.class);
getActivity().startActivity(asd);
}
});
homeworkLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent asd = new Intent(getActivity().getApplicationContext(), StudentHomework.class);
getActivity().startActivity(asd);
}
});
pendingTaskLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent asd = new Intent(getActivity().getApplicationContext(), StudentTasks.class);
getActivity().startActivity(asd);
}
});
Log.e("STATUS", "onCreateView");
return mainView;
}
private void loadData() {
//decorate();
loadFragment(new DashboardCalender());
params.put("student_id", Utility.getSharedPreferences(getActivity().getApplicationContext(), Constants.studentId));
params.put("date_from", getDateOfMonth(new Date(), "first"));
params.put("date_to", getDateOfMonth(new Date(), "last"));
JSONObject obj=new JSONObject(params);
Log.e("params ", obj.toString());
getDataFromApi(obj.toString());
try {
JSONArray modulesArray = new JSONArray(Utility.getSharedPreferences(getActivity().getApplicationContext(), Constants.modulesArray));
if(modulesArray.length() != 0) {
ArrayList<String> moduleCodeList = new ArrayList<String>();
ArrayList<String> moduleStatusList = new ArrayList<String>();
for (int i = 0; i<modulesArray.length(); i++) {
if(modulesArray.getJSONObject(i).getString("short_code").equals("student_attendance")
&& modulesArray.getJSONObject(i).getString("is_active").equals("0") ) {
attendanceCard.setVisibility(View.GONE);
} if(modulesArray.getJSONObject(i).getString("short_code").equals("homework")
&& modulesArray.getJSONObject(i).getString("is_active").equals("0") ) {
homeworkCard.setVisibility(View.GONE);
} if(modulesArray.getJSONObject(i).getString("short_code").equals("calendar_to_do_list")
&& modulesArray.getJSONObject(i).getString("is_active").equals("0") ) {
pendingTaskCard.setVisibility(View.GONE);
calenderFrame.setVisibility(View.GONE);
}
}
}
} catch (JSONException e) {
Log.d("Error", e.toString());
}
}
private void getDataFromApi (String bodyParams) {
Log.e("RESULT PARAMS", bodyParams);
final ProgressDialog pd = new ProgressDialog(getActivity());
pd.setMessage("Loading");
pd.setCancelable(false);
pd.show();
final String requestBody = bodyParams;
String url = Utility.getSharedPreferences(getActivity().getApplicationContext(), "apiUrl") + Constants.getDashboardUrl;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String result) {
if (result != null) {
pd.dismiss();
try {
Log.e("Result", result);
JSONObject object = new JSONObject(result);
//TODO success
String success = "1"; //object.getString("success");
if (success.equals("1")) {
if(object.getString("attendence_type").equals("0")){
attendanceValue.setText(object.getString("student_attendence_percentage") + "%");
}else{
attendanceCard.setVisibility(View.GONE);
}
homeworkValue.setText(object.getString("student_homework_incomplete"));
pendingTaskValue.setText(object.getString("student_incomplete_task"));
String classid = object.getString("class_id");
Utility.setSharedPreference(getActivity().getApplicationContext(), Constants.classId, classid);
Utility.setSharedPreference(getActivity().getApplicationContext(), Constants.sectionId, object.getString("section_id"));
} else {
Toast.makeText(getActivity().getApplicationContext(), object.getString("errorMsg"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
pd.dismiss();
Toast.makeText(getActivity().getApplicationContext(), R.string.noInternetMsg, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
pd.dismiss();
Log.e("Volley Error", volleyError.toString());
Toast.makeText(getActivity(), R.string.slowInternetMsg, Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
headers.put("Client-Service", Constants.clientService);
headers.put("Auth-Key", Constants.authKey);
headers.put("Content-Type", Constants.contentType);
headers.put("User-ID", Utility.getSharedPreferences(getActivity().getApplicationContext(), "userId"));
headers.put("Authorization", Utility.getSharedPreferences(getActivity().getApplicationContext(), "accessToken"));
return headers;
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());//Creating a Request Queue
requestQueue.add(stringRequest);//Adding request to the queue
}
private void decorate() {
attendanceLayout.setBackgroundColor(Color.parseColor(Constants.defaultSecondaryColour));
homeworkLayout.setBackgroundColor(Color.parseColor(Constants.defaultSecondaryColour));
pendingTaskLayout.setBackgroundColor(Color.parseColor(Constants.defaultSecondaryColour));
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
// transaction.replace(calenderFrame.getId(), fragment);
transaction.addToBackStack(null);
transaction.commit();
}
public static String getDateOfMonth(Date date, String index){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if(index.equals("first")) {
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
} else {
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
}
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
return dateFormatter.format(cal.getTime());
}
}
The xml containing viewpager
<?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.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/student_dashboard_fragment_attendanceCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/CustomCardView"
>
<RelativeLayout
android:id="#+id/student_dashboard_fragment_attendanceView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingStart="10dp"
>
<ImageView
android:id="#+id/student_dashboard_fragment_attendanceView_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentStart="true"
android:src="#drawable/ic_dashboard_attendance"
android:layout_centerVertical="true"
android:layout_marginStart="10dp"
/>
<RelativeLayout
android:id="#+id/student_dashboard_fragment_attendance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="35dp"
android:layout_marginEnd="60dp"
android:layout_marginTop="10dp"
>
<TextView
android:id="#+id/student_dashboard_fragment_attendance_head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17sp"
android:gravity="start|center"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:textColor="#color/textHeading"
android:text="#string/attendance"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:gravity="start|center"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:text="#string/thisMonth"
android:textColor="#color/textHeading"
android:layout_below="#+id/student_dashboard_fragment_attendance_head"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="5dp"
>
<TextView
android:id="#+id/student_dashboard_fragment_attendance_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:gravity="center"
android:textColor="#color/textHeading"
/>
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/student_dashboard_fragment_homeworkCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/CustomCardView"
>
<RelativeLayout
android:id="#+id/student_dashboard_fragment_homeworkView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingStart="10dp"
>
<ImageView
android:id="#+id/student_dashboard_fragment_homeworkView_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentStart="true"
android:src="#drawable/ic_dashboard_homework"
android:layout_centerVertical="true"
android:layout_marginStart="10dp"
/>
<RelativeLayout
android:id="#+id/student_dashboard_fragment_homework"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="35dp"
android:layout_marginEnd="60dp"
android:layout_marginTop="10dp"
>
<TextView
android:id="#+id/student_dashboard_fragment_homework_head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17sp"
android:gravity="start|center"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:textColor="#color/textHeading"
android:text="#string/homework"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:gravity="start|center"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:text="#string/incomplete"
android:textColor="#color/textHeading"
android:layout_below="#+id/student_dashboard_fragment_homework_head"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="5dp"
>
<TextView
android:id="#+id/student_dashboard_fragment_homework_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:gravity="center"
android:textColor="#color/textHeading"
/>
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/student_dashboard_fragment_pendingTaskCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/CustomCardView"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/student_dashboard_fragment_pendingTaskView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingStart="10dp"
>
<ImageView
android:id="#+id/student_dashboard_fragment_pendingTaskView_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentStart="true"
android:src="#drawable/ic_dashboard_pandingtask"
android:layout_centerVertical="true"
android:layout_marginStart="10dp"
/>
<RelativeLayout
android:id="#+id/student_dashboard_fragment_pendingTask"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="35dp"
android:layout_marginEnd="60dp"
android:layout_marginTop="10dp">
<TextView
android:id="#+id/student_dashboard_fragment_pendingTask_head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17sp"
android:gravity="start|center"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:textColor="#color/textHeading"
android:text="#string/pendingTask" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:gravity="start|center"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:text="#string/today"
android:textColor="#color/textHeading"
android:layout_below="#+id/student_dashboard_fragment_pendingTask_head" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="5dp">
<TextView
android:id="#+id/student_dashboard_fragment_pendingTask_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:gravity="center"
android:textColor="#color/textHeading"
/>
</RelativeLayout>
</RelativeLayout>
<FrameLayout
android:id="#+id/dashboardViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/textHeading"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
the error is quite self-explanatory. calenderFrame is null, meaning that you never initialized it.
I have found the answer. In onCreate() of fragment my code was calling the loadFragment() method before initializing the calenderFrame.
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.
Profile.java
package com.synergywebdesigners.veebee;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Profile extends AppCompatActivity {
public TextView user,pass,email,mob,add;
public Button ChangePass;
FragmentManager fragmentManager = Profile.this.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final FrameLayout frame = (FrameLayout) findViewById(R.id.chg_frag);
user = (TextView) findViewById(R.id.user);
pass = (TextView) findViewById(R.id.pass);
email = (TextView) findViewById(R.id.email);
mob = (TextView) findViewById(R.id.mob);
add = (TextView) findViewById(R.id.add);
ChangePass = (Button) findViewById(R.id.chang_pass);
ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChangPass changPass = new ChangPass();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.chg_frag,changPass);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
fragmentTransaction = fragmentManager.beginTransaction();
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll);
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String user = sharedPreferences.getString(Config.USERNAME_SHARED_PREF,"Not Available");
String url = Config.DATA_URL+user;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(Profile.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String users="";
String passw="";
String emails = "";
String mobile = "";
String address = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
users = collegeData.getString(Config.KEY_UNAME);
passw = collegeData.getString(Config.KEY_PASS);
emails = collegeData.getString(Config.KEY_EMAIL);
mobile = collegeData.getString(Config.KEY_MOB);
address = collegeData.getString(Config.KEY_ADD);
} catch (JSONException e) {
e.printStackTrace();
}
user.setText("User :\t"+users);
pass.setText("Password :\t"+passw);
email.setText("Email Id :\t"+emails);
mob.setText("Mob No :\t"+mobile);
add.setText("Address :\t"+address);
}
//Logout function
private void logout(){
//Creating an alert dialog to confirm logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(Config.USERNAME_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(Profile.this, LoginActivity.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Adding our menu to toolbar
getMenuInflater().inflate(R.menu.vee_bee, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
//calling logout method when the logout button is clicked
logout();
}
return super.onOptionsItemSelected(item);
}
}
activity_profile.xml
<?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:id="#+id/scroll"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:background="#drawable/side_nav_bar"
tools:context="com.synergywebdesigners.veebee.Profile">
<RelativeLayout
android:id="#+id/profile_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/margin_header"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/margin_header"
android:background="#drawable/side_nav_bar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:orientation="vertical"
android:id="#+id/linearLayout1"
android:gravity="center">
<TextView
android:id="#+id/user_profile_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/name"
android:textAllCaps="true"
android:textColor="#color/defaults"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/user_profile_short_bio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/user_profile_name"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:text="#string/web_add"
android:textColor="#color/defaults"
android:textSize="14sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textColor="#color/defaults"
android:textStyle="bold"
android:clickable="true"
android:textAllCaps="true"
android:id="#+id/m_org"
android:gravity="center"
android:visibility="invisible"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#id/user_profile_short_bio"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:orientation="vertical"
android:id="#+id/linearLayout"
android:layout_below="#+id/linearLayout1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/user" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/pass"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/email"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/mob"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#color/defaults"
android:clickable="true"
android:elevation="4dp"
android:padding="#dimen/fab_margin"
android:id="#+id/add"/>
</LinearLayout>
<Button
android:id="#+id/chang_pass"
android:layout_below="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/margin_header"
android:background="#color/colorPrimaryDark"
android:textColor="#color/defaults"
android:textAllCaps="true"
android:textStyle="bold"
android:text="Change Password"/>
<FrameLayout
android:layout_below="#id/chang_pass"
android:id="#+id/chg_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
</ScrollView>
ChangePass.java
package com.synergywebdesigners.veebee;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;
public class ChangPass extends Fragment {
public EditText PrevPass,NewPass;
public Button Conform;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_chang_pass,container,false);
PrevPass = (EditText) view.findViewById(R.id.prev_pass);
NewPass = (EditText) view.findViewById(R.id.new_pass);
Conform = (Button) view.findViewById(R.id.send);
Conform.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChangePass();
//getActivity().finish();
}
});
return view;
}
private void ChangePass(){
class Addmessage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
SharedPreferences sharedPreferences = getContext().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String user = sharedPreferences.getString(Config.USERNAME_SHARED_PREF,"Not Available");
String prevpass = PrevPass.getText().toString().trim();
String newpass = NewPass.getText().toString().trim();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(getActivity(),"Sending Request..","..Please..Wait..",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getActivity(),s,Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put(Config.KEY_PASS_USER,user);
params.put(Config.KEY_PREV_PASS,prevpass);
params.put(Config.KEY_NEW_PASS,newpass);
ReuestHandler rh = new ReuestHandler();
String res = rh.sendPostRequest(Config.URL_CHANG_PASS, params);
return res;
}
}
Addmessage ae = new Addmessage();
ae.execute();
}
}
fragment_chang_pass.xml
<FrameLayout 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.synergywebdesigners.veebee.ChangPass">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/lbl_prev"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/defaults"
android:textStyle="bold"
android:text="Your Current Password"/>
<EditText
android:id="#+id/prev_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:layout_below="#+id/lbl_prev"
android:singleLine="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Password"
android:textColor="#color/defaults"
android:id="#+id/lbl_new"
android:textStyle="bold"
android:layout_below="#+id/prev_pass"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/new_pass"
android:inputType="text"
android:singleLine="true"
android:layout_below="#+id/lbl_new"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/send"
android:padding="10dp"
android:layout_below="#+id/new_pass"
android:textColor="#color/defaults"
android:background="#color/colorPrimary"
android:text="Confirm Password Change"
/>
</RelativeLayout>
</FrameLayout>
In the code, I want to add Conform button click listener event call Android back button. Like click on back button in fragment close fragment in this time.
public void pushFragment(Fragment fragment, boolean shouldAdd, Bundle bundle) {
stackFragmentMain.push(fragment);
FragmentManager man = getSupportFragmentManager();
FragmentTransaction ft = man.beginTransaction();
ft.replace(R.id.main_screens, fragmentholder.fragment);
ft.commitAllowingStateLoss();
}
public void popFragment() {
if (stackFragmentMain.size() >= 1) {
Fragment fragment = stackFragmentMain
.elementAt(stackFragmentMain.size() - 2);
stackFragmentMain.pop();
if (fragmentholder != null) {
FragmentManager man = getSupportFragmentManager();
FragmentTransaction ft = man.beginTransaction();
ft.replace(R.id.main_screens, fragmentholder.fragment);
ft.commitAllowingStateLoss();
}
}
}
EDIT
Change the following part of your onClick method :-
ChangPass changPass = new ChangPass();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.chg_frag,changPass);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
fragmentTransaction = fragmentManager.beginTransaction();
to
ChangPass changPass = new ChangPass();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.chg_frag,changPass);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
EDIT 2
Along with the above change, in your Conform.onClickListener() of your ChangePass fragment, add the following code :-
getActivity().getSupportFragmentManager().popBackStack();
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
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.