FrameLayout.getId() on a null object - android

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.

Related

How to create nested child on firebase android

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

Set on Android button click listener event on back button click on Android fragment

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

Rest Template PUT method In Android

I'm new to Android and Rest Template.I have developed a android
screen and display JSON data using Rest Template GET method on my
screen.My next step is to update some fields like edit name and add
missing things and save back to the rest Template.
public class MyPreferences extends AppCompatActivity {
TextView tv;
private Listcp = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
Resources resources = getResources();
Log.d("Consumer pojo", "onCreate:");
new HttpRequestTask().execute();
}
private class HttpRequestTask extends AsyncTask<Void, Void, ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile cp = restTemplate.getForObject(url, ConsumerProfile.class);
return cp;
}catch (Exception e){
Log.e("MainActivity", e.getMessage(),e );
}
return null;
}
#Override
protected void onPostExecute(ConsumerProfile cp){
super.onPostExecute(cp);
Log.d("cppppppppppppppppppppp", "onPostExecute: " + cp.getId());
TextView fname=(TextView)findViewById(R.id.editfname);
TextView mname=(TextView)findViewById(R.id.editmname);
TextView lname=(TextView)findViewById(R.id.editlname);
TextView nname=(TextView)findViewById(R.id.editnname);
TextView dob=(TextView)findViewById(R.id.editdob);
TextView status=(TextView)findViewById(R.id.editstatus);
TextView homeAddress=(TextView)findViewById(R.id.edithomeAddr);
TextView workAddress=(TextView)findViewById(R.id.editworkAddr);
TextView income=(TextView)findViewById(R.id.editincome);
fname.setText(cp.getFirstName());
mname.setText(cp.getMiddleName());
lname.setText(cp.getLastName());
nname.setText(cp.getNickName());
dob.setText(cp.getDob());
status.setText(cp.getStatus());
homeAddress.setText(cp.getHomeAddress());
workAddress.setText(cp.getWorkAddress());
income.setText(cp.getIncome());
}
}This Screen is for Get Method
This is what I did Up to Now.
This code is for Get method.
It'll display The screen like in image.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"><![CDATA[
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
]]>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView2" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"> <TextView
android:layout_width="wrap_content"
android:scrollbars="vertical"
android:layout_height="wrap_content"
android:text="firstName"/>
<EditText
android:id="#+id/editfname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="middleName"/>
<EditText
android:id="#+id/editmname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lastName"/>
<EditText
android:id="#+id/editlname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nickName"/>
<EditText
android:id="#+id/editnname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dob"/>
<EditText
android:id="#+id/editdob"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="status"/>
<EditText
android:id="#+id/editstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="homeAddress"/>
<EditText
android:id="#+id/edithomeAddr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="workAddress"/>
<EditText
android:id="#+id/editworkAddr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="income"/>
<EditText
android:id="#+id/editincome"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:scrollbars="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update Preferences"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
This is my layout.
Actually what I'm trying to do is Get User Information and Edit Information and save back to the same end point.
When the user select Update button Then it I'll Display the Updated Screen.
Any help Appreciated.
Anyone Provide code for that.
Thankful to them.
package com.nusecond.suredeal.app.suredeal.activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.http.HttpResponseCache;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.nusecond.suredeal.app.R;
import com.nusecond.suredeal.app.suredeal.pojo.Consumer;
import com.nusecond.suredeal.app.suredeal.pojo.ConsumerProfile;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
public class MyPreferences extends AppCompatActivity {
Button button;
TextView tv;
TextView fname,mname,lname,nname,dob,status,homeAddress,workAddress,income;
private String FName,MName,LName,NName,Dob,Status,HomeAddress,WorkAddress,Income;
private List<ConsumerProfile>cp = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
Resources resources = getResources();
Log.d("Consumer pojo", "onCreate:");
new HttpRequestTask().execute();
addListenerOnButton();
}
private void addListenerOnButton() {
//final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FName=fname.getText().toString();
MName=mname.getText().toString();
LName=lname.getText().toString();
NName=nname.getText().toString();
Dob=dob.getText().toString();
Status=status.getText().toString();
HomeAddress=homeAddress.getText().toString();
WorkAddress=workAddress.getText().toString();
new HttpUpdateTask().execute();
// Toast.makeText(addListenerOnButton(),"UpdatedSuccessfully",Toast.LENGTH_LONG).show();
Intent intent=new Intent(MyPreferences.this,MainActivity.class);
startActivity(intent);
}
});
}
private class HttpRequestTask extends AsyncTask<Void, Void, ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile cp = restTemplate.getForObject(url, ConsumerProfile.class);
return cp;
}catch (Exception e){
Log.e("MainActivity", e.getMessage(),e );
}
return null;
}
#Override
protected void onPostExecute(ConsumerProfile cp){
super.onPostExecute(cp);
Log.d("cppppppppppppppppppppp", "onPostExecute: " + cp.getId());
fname=(TextView)findViewById(R.id.editfname);
mname=(TextView)findViewById(R.id.editmname);
lname=(TextView)findViewById(R.id.editlname);
nname=(TextView)findViewById(R.id.editnname);
dob=(TextView)findViewById(R.id.editdob);
status=(TextView)findViewById(R.id.editstatus);
homeAddress=(TextView)findViewById(R.id.edithomeAddr);
workAddress=(TextView)findViewById(R.id.editworkAddr);
income=(TextView)findViewById(R.id.editincome);
fname.setText(cp.getFirstName());
mname.setText(cp.getMiddleName());
lname.setText(cp.getLastName());
nname.setText(cp.getNickName());
dob.setText(cp.getDob());
status.setText(cp.getStatus());
homeAddress.setText(cp.getHomeAddress());
workAddress.setText(cp.getWorkAddress());
income.setText(cp.getIncome());
//FName=fname.getText().toString();
}
}
private class HttpUpdateTask extends AsyncTask<Void,Void,ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/" + LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile consumerProfile = new ConsumerProfile();
// String m=FName;
consumerProfile.setFirstName(FName);
fname=(TextView)findViewById(R.id.editfname);
Log.d(" llllllllllllll", "doInBackground: " + FName);
consumerProfile.setMiddleName(MName);
consumerProfile.setLastName(LName);
consumerProfile.setNickName(NName);
consumerProfile.setDob(Dob);
consumerProfile.setStatus(Status);
consumerProfile.setHomeAddress(HomeAddress);
consumerProfile.setWorkAddress(WorkAddress);
consumerProfile.setDob(Income);
restTemplate.put(url,consumerProfile);
Log.d("ettttttttttttttt", "doInBackground: ");
return consumerProfile;
}catch (Exception e){
Log.e( "consumer", e.getMessage(),e);
}
return null;
}
}
}

onOptionsItemClick or onMenuItemClick not being called

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

Title not changed when running android application

I have made an application in android,now i have made activities notes.xml,contactinfo.xml and an android xml file named listplaceholder5.xml,i need is i've changed the android:text of textview to "notes"in "listplaceholder5.xml" file which is used in note.java but it ,not displaying "notes" its displaying "contact".i have tried sode a sbelow:please help me to change the code so that i can solve it,
Note.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
android:textColor="#000000"
android:textStyle="bold"
android:textSize="16sp"
android:paddingLeft="5dp"
/>
<TextView
android:id="#+id/item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="item_title"
android:textColor="#000000"
android:textStyle="bold"
android:textSize="16sp"
android:paddingLeft="5dp"
android:ellipsize="end"
android:lines="1"
android:scrollHorizontally="true"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<!--
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="#string/hello"
android:visibility="gone"
/>-->
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone : "
android:textColor="#000000"
android:textSize="14sp"
android:paddingLeft="5dp"
/>
<TextView
android:id="#+id/item_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item_subtitle"
android:textColor="#000000"
android:textSize="14sp"
/>
<TextView
android:id="#+id/item_subtitle1"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="14sp"
android:layout_width="wrap_content"
android:ellipsize="end"
android:lines="1"
android:scrollHorizontally="true"
/>
<!-- New Layout -->
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:paddingRight="10dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/forward" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
listplaceholder5.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/detailpage">
<LinearLayout android:layout_width="fill_parent"
android:weightSum="1"
android:background="#drawable/bottombackground"
android:id="#+id/linearLayout1"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:textColor="#FFFFFF"
android:layout_marginLeft="18dp"
android:layout_weight="0.88"
android:textSize="18sp"
android:textStyle="bold"
android:id="#+id/textView1"
android:text="Notes"
android:gravity="center"
android:layout_gravity="center"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
<ListView
android:id="#id/android:list"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:layout_width="fill_parent"
android:cacheColorHint="#00000000"
android:dividerHeight="2dp"
android:listSelector="#drawable/list_selector"
/>
<TextView
android:id="#id/android:empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="No data"/>
</LinearLayout>
NOteActivity.java
package com.hussain.realtylog;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hussain.realtylog.Contact.DownloadWebPageTask;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class NoteActivity extends ListActivity {
JSONArray jArray = null;
JSONObject json_data = null;
String getMLSID =null;
TextView titl;
// Button btnBuyer;
// Button btnRental;
String getJson =null;
public String user=null;
public static String urlContact=null;
public static String jsonContact=null;
ArrayList<HashMap<String, String>> mylist;
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
#Override
protected String doInBackground(String... urls) {
user= TabBarExample.getJsonUser;
urlContact = StoreSession.strBaseURL+"&username="+user+"&act=ContactList";
if( StoreSession.FlagContact == 0){
boolean isNet = checkInternetConnection();
if(isNet==true){
jsonContact = JSONfunctions.getJSONfromURL(urlContact);
}else{
alertbox("Contact", "Please check your mobile network setting and try again.");
}
}
mylist = new ArrayList<HashMap<String, String>>();
try{
jArray = new JSONArray(jsonContact);
for(int i=0;i<jArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("ID", e.getString("ID"));
map.put("username", e.getString("username"));
map.put("email", e.getString("email"));
map.put("phone", e.getString("phone"));
map.put("phone2", e.getString("phone2"));
map.put("fullname", e.getString("fullname"));
map.put("address", e.getString("address"));
map.put("notes", e.getString("info"));
map.put("active", e.getString("active"));
map.put("created", e.getString("created"));
map.put("lastUpdate", e.getString("lastUpdate"));
map.put("guest", e.getString("guest"));
map.put("category", "Category: "+e.getString("category"));
mylist.add(map);
}
}catch(JSONException e){
// Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListAdapter adapter = new SimpleAdapter(NoteActivity.this, mylist , R.layout.activity_note,
new String[] { "fullname", "phone" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
int[] colors = {0, 0xFFFF0000, 0}; // red for the example
lv.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
lv.setDividerHeight(1);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final ProgressDialog dialog = ProgressDialog.show(NoteActivity.this, "Loading",
"Please wait...", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
#SuppressWarnings("unchecked")
public void run() {
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
final String strName= o.get("fullname").toString();
final String strEmail= o.get("email").toString();
final String Phone= o.get("phone").toString();
final String Phone2= o.get("phone2").toString();
getMLSID = o.get("notes").toString();
Intent newActivityFirst = new Intent(NoteActivity.this, ContactInfo.class);
newActivityFirst.putExtra("name", strName);
newActivityFirst.putExtra("strEmail", strEmail);
newActivityFirst.putExtra("phone", Phone);
newActivityFirst.putExtra("phone2", Phone2);
newActivityFirst.putExtra("notes", getMLSID);
NoteActivity.this.startActivity(newActivityFirst);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
});
StoreSession.FlagContact=1;
//dialog.hide();
dialog.dismiss();
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected void onPreExecute() {
dialog = new ProgressDialog(NoteActivity.this);
dialog.setCancelable(true);
dialog.setMessage("Please wait...");
dialog.show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute();
setContentView(R.layout.listplaceholder5);
TextView title=(TextView)findViewById(R.id.textView1);
title.setText("Notes");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
StoreSession.FlagListing =0;
StoreSession.FlagBuyer =0;
StoreSession.FlagRental =0;
StoreSession.FlagDocument =0;
StoreSession.FlagContact =0;
ActiveShowingInfo.flagActiveClickCheck =0;
Main.username.setText("");
Main.pwd.setText("");
return false;
}
return super.onKeyDown(keyCode, event);
}
protected void alertbox(String title, String mymessage)
{
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){}
})
.show();
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
//Log.v("tag", "Internet Connection Not Present");
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_note, menu);
return true;
}
}
please help me to solve this problem.thanking you in advance.
after getting the title as follows:
title= (TextView) findViewById(R.id.item_title);
use setText method to set the title as you wish.
I think it will solve your problem.

Categories

Resources